forked from johnezang/JSONKit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JSONKit.m
3059 lines (2505 loc) · 173 KB
/
JSONKit.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// JSONKit.m
// http://github.com/johnezang/JSONKit
// Dual licensed under either the terms of the BSD License, or alternatively
// under the terms of the Apache License, Version 2.0, as specified below.
//
/*
Copyright (c) 2011, John Engelhart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Zang Industries nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright 2011 John Engelhart
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Acknowledgments:
The bulk of the UTF8 / UTF32 conversion and verification comes
from ConvertUTF.[hc]. It has been modified from the original sources.
The original sources were obtained from http://www.unicode.org/.
However, the web site no longer seems to host the files. Instead,
the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4
points to International Components for Unicode (ICU)
http://site.icu-project.org/ as an example of how to write a UTF
converter.
The decision to use the ConvertUTF.[ch] code was made to leverage
"proven" code. Hopefully the local modifications are bug free.
The code in isValidCodePoint() is derived from the ICU code in
utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR.
From the original ConvertUTF.[ch]:
* Copyright 2001-2004 Unicode, Inc.
*
* Disclaimer
*
* This source code is provided as is by Unicode, Inc. No claims are
* made as to fitness for any particular purpose. No warranties of any
* kind are expressed or implied. The recipient agrees to determine
* applicability of information provided. If this file has been
* purchased on magnetic or optical media from Unicode, Inc., the
* sole remedy for any claim will be exchange of defective media
* within 90 days of receipt.
*
* Limitations on Rights to Redistribute This Code
*
* Unicode, Inc. hereby grants the right to freely use the information
* supplied in this file in the creation of products supporting the
* Unicode Standard, and to make copies of this file in any form
* for internal or external distribution as long as this notice
* remains attached.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include <sys/errno.h>
#include <math.h>
#include <limits.h>
#include <objc/runtime.h>
#import "JSONKit.h"
//#include <CoreFoundation/CoreFoundation.h>
#include <CoreFoundation/CFString.h>
#include <CoreFoundation/CFArray.h>
#include <CoreFoundation/CFDictionary.h>
#include <CoreFoundation/CFNumber.h>
//#import <Foundation/Foundation.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSException.h>
#import <Foundation/NSNull.h>
#import <Foundation/NSObjCRuntime.h>
#ifndef __has_feature
#define __has_feature(x) 0
#endif
#ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS
#warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option.
#endif
#ifdef __OBJC_GC__
#error JSONKit does not support Objective-C Garbage Collection
#endif
#if __has_feature(objc_arc)
#error JSONKit does not support Objective-C Automatic Reference Counting (ARC)
#endif
// The following checks are really nothing more than sanity checks.
// JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety.
// In practice, though, for the compilers and architectures we can reasonably expect this code to be compiled for, these pedantic nitpicks aren't really a problem.
// Since we're limited as to what we can do with pre-processor #if checks, these checks are not nearly as through as they should be.
#if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL))
#error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively.
#endif
#if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT))
#error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures.
#endif
// Cocoa / Foundation uses NS*Integer as the type for a lot of arguments. We make sure that NS*Integer is something we are expecting and is reasonably compatible with size_t / ssize_t
#if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN)
#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type.
#endif
#if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX)
#error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type.
#endif
// For DJB hash.
#define JK_HASH_INIT (1402737925UL)
// Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup.
#define JK_FAST_TRAILING_BYTES
// JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots.
#define JK_CACHE_SLOTS_BITS (10)
#define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS)
// JK_CACHE_PROBES is the number of probe attempts.
#define JK_CACHE_PROBES (4UL)
// JK_INIT_CACHE_AGE must be (1 << AGE) - 1
#define JK_INIT_CACHE_AGE (0)
// JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes)
#define JK_TOKENBUFFER_SIZE (1024UL * 2UL)
// JK_STACK_OBJS is the default number of spaces reserved on the stack for temporarily storing pointers to Obj-C objects before they can be transferred to a NSArray / NSDictionary.
#define JK_STACK_OBJS (1024UL * 1UL)
#define JK_JSONBUFFER_SIZE (1024UL * 4UL)
#define JK_UTF8BUFFER_SIZE (1024UL * 16UL)
#define JK_ENCODE_CACHE_SLOTS (1024UL)
#if defined (__GNUC__) && (__GNUC__ >= 4)
#define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__))
#define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect))
#define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U)
#define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U)
#define JK_PREFETCH(ptr) __builtin_prefetch(ptr)
#else // defined (__GNUC__) && (__GNUC__ >= 4)
#define JK_ATTRIBUTES(attr, ...)
#define JK_EXPECTED(cond, expect) (cond)
#define JK_EXPECT_T(cond) (cond)
#define JK_EXPECT_F(cond) (cond)
#define JK_PREFETCH(ptr)
#endif // defined (__GNUC__) && (__GNUC__ >= 4)
#define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline)
#define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg))
#define JK_UNUSED_ARG JK_ATTRIBUTES(unused)
#define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result)
#define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const)
#define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure)
#define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel)
#define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__))
#define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__))
#define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__))
#define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__))
#if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as))
#else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
#define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__))
#endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
@class JKArray, JKDictionaryEnumerator, JKDictionary;
enum {
JSONNumberStateStart = 0,
JSONNumberStateFinished = 1,
JSONNumberStateError = 2,
JSONNumberStateWholeNumberStart = 3,
JSONNumberStateWholeNumberMinus = 4,
JSONNumberStateWholeNumberZero = 5,
JSONNumberStateWholeNumber = 6,
JSONNumberStatePeriod = 7,
JSONNumberStateFractionalNumberStart = 8,
JSONNumberStateFractionalNumber = 9,
JSONNumberStateExponentStart = 10,
JSONNumberStateExponentPlusMinus = 11,
JSONNumberStateExponent = 12,
};
enum {
JSONStringStateStart = 0,
JSONStringStateParsing = 1,
JSONStringStateFinished = 2,
JSONStringStateError = 3,
JSONStringStateEscape = 4,
JSONStringStateEscapedUnicode1 = 5,
JSONStringStateEscapedUnicode2 = 6,
JSONStringStateEscapedUnicode3 = 7,
JSONStringStateEscapedUnicode4 = 8,
JSONStringStateEscapedUnicodeSurrogate1 = 9,
JSONStringStateEscapedUnicodeSurrogate2 = 10,
JSONStringStateEscapedUnicodeSurrogate3 = 11,
JSONStringStateEscapedUnicodeSurrogate4 = 12,
JSONStringStateEscapedNeedEscapeForSurrogate = 13,
JSONStringStateEscapedNeedEscapedUForSurrogate = 14,
};
enum {
JKParseAcceptValue = (1 << 0),
JKParseAcceptComma = (1 << 1),
JKParseAcceptEnd = (1 << 2),
JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd),
JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd),
};
enum {
JKClassUnknown = 0,
JKClassString = 1,
JKClassNumber = 2,
JKClassArray = 3,
JKClassDictionary = 4,
JKClassNull = 5,
};
enum {
JKManagedBufferOnStack = 1,
JKManagedBufferOnHeap = 2,
JKManagedBufferLocationMask = (0x3),
JKManagedBufferLocationShift = (0),
JKManagedBufferMustFree = (1 << 2),
};
typedef JKFlags JKManagedBufferFlags;
enum {
JKObjectStackOnStack = 1,
JKObjectStackOnHeap = 2,
JKObjectStackLocationMask = (0x3),
JKObjectStackLocationShift = (0),
JKObjectStackMustFree = (1 << 2),
};
typedef JKFlags JKObjectStackFlags;
enum {
JKTokenTypeInvalid = 0,
JKTokenTypeNumber = 1,
JKTokenTypeString = 2,
JKTokenTypeObjectBegin = 3,
JKTokenTypeObjectEnd = 4,
JKTokenTypeArrayBegin = 5,
JKTokenTypeArrayEnd = 6,
JKTokenTypeSeparator = 7,
JKTokenTypeComma = 8,
JKTokenTypeTrue = 9,
JKTokenTypeFalse = 10,
JKTokenTypeNull = 11,
JKTokenTypeWhiteSpace = 12,
};
typedef NSUInteger JKTokenType;
// These are prime numbers to assist with hash slot probing.
enum {
JKValueTypeNone = 0,
JKValueTypeString = 5,
JKValueTypeLongLong = 7,
JKValueTypeUnsignedLongLong = 11,
JKValueTypeDouble = 13,
};
typedef NSUInteger JKValueType;
enum {
JKEncodeOptionAsData = 1,
JKEncodeOptionAsString = 2,
JKEncodeOptionAsTypeMask = 0x7,
JKEncodeOptionCollectionObj = (1 << 3),
JKEncodeOptionStringObj = (1 << 4),
JKEncodeOptionStringObjTrimQuotes = (1 << 5),
};
typedef NSUInteger JKEncodeOptionType;
typedef NSUInteger JKHash;
typedef struct JKTokenCacheItem JKTokenCacheItem;
typedef struct JKTokenCache JKTokenCache;
typedef struct JKTokenValue JKTokenValue;
typedef struct JKParseToken JKParseToken;
typedef struct JKPtrRange JKPtrRange;
typedef struct JKObjectStack JKObjectStack;
typedef struct JKBuffer JKBuffer;
typedef struct JKConstBuffer JKConstBuffer;
typedef struct JKConstPtrRange JKConstPtrRange;
typedef struct JKRange JKRange;
typedef struct JKManagedBuffer JKManagedBuffer;
typedef struct JKFastClassLookup JKFastClassLookup;
typedef struct JKEncodeCache JKEncodeCache;
typedef struct JKEncodeState JKEncodeState;
typedef struct JKObjCImpCache JKObjCImpCache;
typedef struct JKHashTableEntry JKHashTableEntry;
typedef id (*NSNumberAllocImp)(id receiver, SEL selector);
typedef id (*NSNumberInitWithUnsignedLongLongImp)(id receiver, SEL selector, unsigned long long value);
typedef id (*JKClassFormatterIMP)(id receiver, SEL selector, id object);
#ifdef __BLOCKS__
typedef id (^JKClassFormatterBlock)(id formatObject);
#endif
struct JKPtrRange {
unsigned char *ptr;
size_t length;
};
struct JKConstPtrRange {
const unsigned char *ptr;
size_t length;
};
struct JKRange {
size_t location, length;
};
struct JKManagedBuffer {
JKPtrRange bytes;
JKManagedBufferFlags flags;
size_t roundSizeUpToMultipleOf;
};
struct JKObjectStack {
void **objects, **keys;
CFHashCode *cfHashes;
size_t count, index, roundSizeUpToMultipleOf;
JKObjectStackFlags flags;
};
struct JKBuffer {
JKPtrRange bytes;
};
struct JKConstBuffer {
JKConstPtrRange bytes;
};
struct JKTokenValue {
JKConstPtrRange ptrRange;
JKValueType type;
JKHash hash;
union {
long long longLongValue;
unsigned long long unsignedLongLongValue;
double doubleValue;
} number;
JKTokenCacheItem *cacheItem;
};
struct JKParseToken {
JKConstPtrRange tokenPtrRange;
JKTokenType type;
JKTokenValue value;
JKManagedBuffer tokenBuffer;
};
struct JKTokenCacheItem {
void *object;
JKHash hash;
CFHashCode cfHash;
size_t size;
unsigned char *bytes;
JKValueType type;
};
struct JKTokenCache {
JKTokenCacheItem *items;
size_t count;
unsigned int prng_lfsr;
unsigned char age[JK_CACHE_SLOTS];
};
struct JKObjCImpCache {
Class NSNumberClass;
NSNumberAllocImp NSNumberAlloc;
NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong;
};
struct JKParseState {
JKParseOptionFlags parseOptionFlags;
JKConstBuffer stringBuffer;
size_t atIndex, lineNumber, lineStartIndex;
size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex;
JKParseToken token;
JKObjectStack objectStack;
JKTokenCache cache;
JKObjCImpCache objCImpCache;
NSError *error;
int errorIsPrev;
BOOL mutableCollections;
};
struct JKFastClassLookup {
void *stringClass;
void *numberClass;
void *arrayClass;
void *dictionaryClass;
void *nullClass;
};
struct JKEncodeCache {
id object;
size_t offset;
size_t length;
};
struct JKEncodeState {
JKManagedBuffer utf8ConversionBuffer;
JKManagedBuffer stringBuffer;
size_t atIndex;
JKFastClassLookup fastClassLookup;
JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS];
JKSerializeOptionFlags serializeOptionFlags;
JKEncodeOptionType encodeOption;
size_t depth;
NSError *error;
id classFormatterDelegate;
SEL classFormatterSelector;
JKClassFormatterIMP classFormatterIMP;
#ifdef __BLOCKS__
JKClassFormatterBlock classFormatterBlock;
#endif
};
// This is a JSONKit private class.
@interface JKSerializer : NSObject {
JKEncodeState *encodeState;
}
#ifdef __BLOCKS__
#define JKSERIALIZER_BLOCKS_PROTO id(^)(id object)
#else
#define JKSERIALIZER_BLOCKS_PROTO id
#endif
+ (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption block:(JKSERIALIZER_BLOCKS_PROTO)block delegate:(id)delegate selector:(SEL)selector error:(NSError **)error;
- (void)releaseState;
@end
struct JKHashTableEntry {
NSUInteger keyHash;
id key, object;
};
typedef uint32_t UTF32; /* at least 32 bits */
typedef uint16_t UTF16; /* at least 16 bits */
typedef uint8_t UTF8; /* typically 8 bits */
typedef enum {
conversionOK, /* conversion successful */
sourceExhausted, /* partial character in source, but hit end */
targetExhausted, /* insuff. room in target for conversion */
sourceIllegal /* source sequence is illegal/malformed */
} ConversionResult;
#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
#define UNI_MAX_BMP (UTF32)0x0000FFFF
#define UNI_MAX_UTF16 (UTF32)0x0010FFFF
#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
#define UNI_SUR_HIGH_START (UTF32)0xD800
#define UNI_SUR_HIGH_END (UTF32)0xDBFF
#define UNI_SUR_LOW_START (UTF32)0xDC00
#define UNI_SUR_LOW_END (UTF32)0xDFFF
#if !defined(JK_FAST_TRAILING_BYTES)
static const char trailingBytesForUTF8[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};
#endif
static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
#define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex]))
#define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length]))
static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection);
static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex);
static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject);
static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex);
static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count);
static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection);
static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary);
static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary);
static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary);
static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry);
static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object);
static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey);
static void _JSONDecoderCleanup(JSONDecoder *decoder);
static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection);
static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer);
static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length);
static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize);
static void jk_objectStack_release(JKObjectStack *objectStack);
static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count);
static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount);
static void jk_error(JKParseState *parseState, NSString *format, ...);
static int jk_parse_string(JKParseState *parseState);
static int jk_parse_number(JKParseState *parseState);
static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr);
JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState);
JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState);
static int jk_parse_next_token(JKParseState *parseState);
static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String);
static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex);
static void *jk_parse_dictionary(JKParseState *parseState);
static void *jk_parse_array(JKParseState *parseState);
static void *jk_object_for_token(JKParseState *parseState);
static void *jk_cachedObjects(JKParseState *parseState);
JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState);
JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy);
static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...);
static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...);
static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format);
static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState);
static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format);
static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format);
static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length);
JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr);
JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object);
static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr);
#define jk_encode_write1(es, dc, f) (JK_EXPECT_F(_jk_encode_prettyPrint) ? jk_encode_write1slow(es, dc, f) : jk_encode_write1fast(es, dc, f))
JK_STATIC_INLINE size_t jk_min(size_t a, size_t b);
JK_STATIC_INLINE size_t jk_max(size_t a, size_t b);
JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c);
// JSONKit v1.4 used both a JKArray : NSArray and JKMutableArray : NSMutableArray, and the same for the dictionary collection type.
// However, Louis Gerbarg (via cocoa-dev) pointed out that Cocoa / Core Foundation actually implements only a single class that inherits from the
// mutable version, and keeps an ivar bit for whether or not that instance is mutable. This means that the immutable versions of the collection
// classes receive the mutating methods, but this is handled by having those methods throw an exception when the ivar bit is set to immutable.
// We adopt the same strategy here. It's both cleaner and gets rid of the method swizzling hackery used in JSONKit v1.4.
// This is a workaround for issue #23 https://github.com/johnezang/JSONKit/pull/23
// Basically, there seem to be a problem with using +load in static libraries on iOS. However, __attribute__ ((constructor)) does work correctly.
// Since we do not require anything "special" that +load provides, and we can accomplish the same thing using __attribute__ ((constructor)), the +load logic was moved here.
static Class _JKArrayClass = NULL;
static size_t _JKArrayInstanceSize = 0UL;
static Class _JKDictionaryClass = NULL;
static size_t _JKDictionaryInstanceSize = 0UL;
// For JSONDecoder...
static Class _jk_NSNumberClass = NULL;
static NSNumberAllocImp _jk_NSNumberAllocImp = NULL;
static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp = NULL;
extern void jk_collectionClassLoadTimeInitialization(void) __attribute__ ((constructor));
void jk_collectionClassLoadTimeInitialization(void) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at load time initialization may be less than ideal.
_JKArrayClass = objc_getClass("JKArray");
_JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass));
_JKDictionaryClass = objc_getClass("JKDictionary");
_JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass));
// For JSONDecoder...
_jk_NSNumberClass = [NSNumber class];
_jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)];
// Hacktacular. Need to do it this way due to the nature of class clusters.
id temp_NSNumber = [NSNumber alloc];
_jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)];
[[temp_NSNumber init] release];
temp_NSNumber = NULL;
[pool release]; pool = NULL;
}
#pragma mark -
@interface JKArray : NSMutableArray <NSCopying, NSMutableCopying, NSFastEnumeration> {
id *objects;
NSUInteger count, capacity, mutations;
}
@end
@implementation JKArray
+ (id)allocWithZone:(NSZone *)zone
{
#pragma unused(zone)
[NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])];
return(NULL);
}
static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) {
NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL));
JKArray *array = NULL;
if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc.
array->isa = _JKArrayClass;
if((array = [array init]) == NULL) { return(NULL); }
array->capacity = count;
array->count = count;
if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); }
memcpy(array->objects, objects, array->capacity * sizeof(id));
array->mutations = (mutableCollection == NO) ? 0UL : 1UL;
}
return(array);
}
// Note: The caller is responsible for -retaining the object that is to be added.
static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) {
NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL));
if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; }
if((array->count + 1UL) >= array->capacity) {
id *newObjects = NULL;
if((newObjects = (id *)realloc(array->objects, sizeof(id) * (array->capacity + 16UL))) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; }
array->objects = newObjects;
array->capacity += 16UL;
memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count));
}
array->count++;
if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; }
array->objects[objectIndex] = newObject;
}
// Note: The caller is responsible for -retaining the object that is to be added.
static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) {
NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL));
if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; }
CFRelease(array->objects[objectIndex]);
array->objects[objectIndex] = NULL;
array->objects[objectIndex] = newObject;
}
static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) {
NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL));
if(!((array != NULL) && (array->objects != NULL) && (array->count > 0UL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; }
CFRelease(array->objects[objectIndex]);
array->objects[objectIndex] = NULL;
if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count - 1UL] = NULL; }
array->count--;
}
- (void)dealloc
{
if(JK_EXPECT_T(objects != NULL)) {
NSUInteger atObject = 0UL;
for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } }
free(objects); objects = NULL;
}
[super dealloc];
}
- (NSUInteger)count
{
NSParameterAssert((objects != NULL) && (count <= capacity));
return(count);
}
- (void)getObjects:(id *)objectsPtr range:(NSRange)range
{
NSParameterAssert((objects != NULL) && (count <= capacity));
if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range)]; }
if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSMaxRange(range), count]; }
memcpy(objectsPtr, objects + range.location, range.length * sizeof(id));
}
- (id)objectAtIndex:(NSUInteger)objectIndex
{
if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL));
return(objects[objectIndex]);
}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
{
NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity));
if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
if(JK_EXPECT_F(state->state >= count)) { return(0UL); }
NSUInteger enumeratedCount = 0UL;
while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; }
return(enumeratedCount);
}
- (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex
{
if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
if(objectIndex > count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count + 1UL]; }
#ifdef __clang_analyzer__
[anObject retain]; // Stupid clang analyzer... Issue #19.
#else
anObject = [anObject retain];
#endif
_JKArrayInsertObjectAtIndex(self, anObject, objectIndex);
mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
}
- (void)removeObjectAtIndex:(NSUInteger)objectIndex
{
if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
_JKArrayRemoveObjectAtIndex(self, objectIndex);
mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
}
- (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject
{
if(mutations == 0UL) { [NSException raise:NSInternalInconsistencyException format:@"*** -[%@ %@]: mutating method sent to immutable object", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), objectIndex, count]; }
#ifdef __clang_analyzer__
[anObject retain]; // Stupid clang analyzer... Issue #19.
#else
anObject = [anObject retain];
#endif
_JKArrayReplaceObjectAtIndexWithObject(self, objectIndex, anObject);
mutations = (mutations == NSUIntegerMax) ? 1UL : mutations + 1UL;
}
- (id)copyWithZone:(NSZone *)zone
{
NSParameterAssert((objects != NULL) && (count <= capacity));
return((mutations == 0UL) ? [self retain] : [(NSArray *)[NSArray allocWithZone:zone] initWithObjects:objects count:count]);
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
NSParameterAssert((objects != NULL) && (count <= capacity));
return([(NSMutableArray *)[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
}
@end
#pragma mark -
@interface JKDictionaryEnumerator : NSEnumerator {
id collection;
NSUInteger nextObject;
}
- (id)initWithJKDictionary:(JKDictionary *)initDictionary;
- (NSArray *)allObjects;
- (id)nextObject;
@end
@implementation JKDictionaryEnumerator
- (id)initWithJKDictionary:(JKDictionary *)initDictionary
{
NSParameterAssert(initDictionary != NULL);
if((self = [super init]) == NULL) { return(NULL); }
if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); }
return(self);
}
- (void)dealloc
{
if(collection != NULL) { CFRelease(collection); collection = NULL; }
[super dealloc];
}
- (NSArray *)allObjects
{
NSParameterAssert(collection != NULL);
NSUInteger count = [collection count], atObject = 0UL;
id objects[count];
while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; }
return([NSArray arrayWithObjects:objects count:atObject]);
}
- (id)nextObject
{
NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL));
JKHashTableEntry *entry = _JKDictionaryHashEntry(collection);
NSUInteger capacity = _JKDictionaryCapacity(collection);
id returnObject = NULL;
if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } }
return(returnObject);
}
@end
#pragma mark -
@interface JKDictionary : NSMutableDictionary <NSCopying, NSMutableCopying, NSFastEnumeration> {
NSUInteger count, capacity, mutations;
JKHashTableEntry *entry;
}
@end
@implementation JKDictionary
+ (id)allocWithZone:(NSZone *)zone
{
#pragma unused(zone)
[NSException raise:NSInvalidArgumentException format:@"*** - [%@ %@]: The %@ class is private to JSONKit and should not be used in this fashion.", NSStringFromClass([self class]), NSStringFromSelector(_cmd), NSStringFromClass([self class])];
return(NULL);
}
// These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too.
static const NSUInteger jk_dictionaryCapacities[] = {
0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL,
2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL,
214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL,
6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL,
111638519UL, 180634607UL, 292272623UL, 472907251UL
};
static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) {
NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33));
while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } }
return(jk_dictionaryCapacities[bottom]);
}
static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
NSUInteger capacityForCount = 0UL;
if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize
NSUInteger oldCapacity = dictionary->capacity;
#ifndef NS_BLOCK_ASSERTIONS
NSUInteger oldCount = dictionary->count;
#endif
JKHashTableEntry *oldEntry = dictionary->entry;
if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; }
dictionary->capacity = capacityForCount;
dictionary->count = 0UL;
NSUInteger idx = 0UL;
for(idx = 0UL; idx < oldCapacity; idx++) { if(oldEntry[idx].key != NULL) { _JKDictionaryAddObject(dictionary, oldEntry[idx].keyHash, oldEntry[idx].key, oldEntry[idx].object); oldEntry[idx].keyHash = 0UL; oldEntry[idx].key = NULL; oldEntry[idx].object = NULL; } }
NSCParameterAssert((oldCount == dictionary->count));
free(oldEntry); oldEntry = NULL;
}
}
static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) {
NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL));
JKDictionary *dictionary = NULL;
if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKDictionary instance via calloc.
dictionary->isa = _JKDictionaryClass;
if((dictionary = [dictionary init]) == NULL) { return(NULL); }
dictionary->capacity = _JKDictionaryCapacityForCount(count);
dictionary->count = 0UL;
if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); }
NSUInteger idx = 0UL;
for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); }
dictionary->mutations = (mutableCollection == NO) ? 0UL : 1UL;
}
return(dictionary);
}
- (void)dealloc
{
if(JK_EXPECT_T(entry != NULL)) {
NSUInteger atEntry = 0UL;
for(atEntry = 0UL; atEntry < capacity; atEntry++) {
if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; }
if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; }
}
free(entry); entry = NULL;
}
[super dealloc];
}
static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) {
NSCParameterAssert(dictionary != NULL);
return(dictionary->entry);
}
static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) {
NSCParameterAssert(dictionary != NULL);
return(dictionary->capacity);
}
static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) {
NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL) && (dictionary->count <= dictionary->capacity));
CFRelease(entry->key); entry->key = NULL;
CFRelease(entry->object); entry->object = NULL;
entry->keyHash = 0UL;
dictionary->count--;
// In order for certain invariants that are used to speed up the search for a particular key, we need to "re-add" all the entries in the hash table following this entry until we hit a NULL entry.
NSUInteger removeIdx = entry - dictionary->entry, idx = 0UL;
NSCParameterAssert((removeIdx < dictionary->capacity));
for(idx = 0UL; idx < dictionary->capacity; idx++) {
NSUInteger entryIdx = (removeIdx + idx + 1UL) % dictionary->capacity;
JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
if(atEntry->key == NULL) { break; }
NSUInteger keyHash = atEntry->keyHash;
id key = atEntry->key, object = atEntry->object;
NSCParameterAssert(object != NULL);
atEntry->keyHash = 0UL;
atEntry->key = NULL;
atEntry->object = NULL;
NSUInteger addKeyEntry = keyHash % dictionary->capacity, addIdx = 0UL;
for(addIdx = 0UL; addIdx < dictionary->capacity; addIdx++) {
JKHashTableEntry *atAddEntry = &dictionary->entry[((addKeyEntry + addIdx) % dictionary->capacity)];
if(JK_EXPECT_T(atAddEntry->key == NULL)) { NSCParameterAssert((atAddEntry->keyHash == 0UL) && (atAddEntry->object == NULL)); atAddEntry->key = key; atAddEntry->object = object; atAddEntry->keyHash = keyHash; break; }
}
}
}
static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) {
NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL));
NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL;
for(idx = 0UL; idx < dictionary->capacity; idx++) {
NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity;