JSONKit.m 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000
  1. //
  2. // JSONKit.m
  3. // http://github.com/johnezang/JSONKit
  4. // Licensed under the terms of the BSD License, as specified below.
  5. //
  6. /*
  7. Copyright (c) 2011, John Engelhart
  8. All rights reserved.
  9. Redistribution and use in source and binary forms, with or without
  10. modification, are permitted provided that the following conditions are met:
  11. * Redistributions of source code must retain the above copyright
  12. notice, this list of conditions and the following disclaimer.
  13. * Redistributions in binary form must reproduce the above copyright
  14. notice, this list of conditions and the following disclaimer in the
  15. documentation and/or other materials provided with the distribution.
  16. * Neither the name of the Zang Industries nor the names of its
  17. contributors may be used to endorse or promote products derived from
  18. this software without specific prior written permission.
  19. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  25. TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  26. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  27. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  28. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  29. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. /*
  32. Acknowledgments:
  33. The bulk of the UTF8 / UTF32 conversion and verification comes
  34. from ConvertUTF.[hc]. It has been modified from the original sources.
  35. The original sources were obtained from http://www.unicode.org/.
  36. However, the web site no longer seems to host the files. Instead,
  37. the Unicode FAQ http://www.unicode.org/faq//utf_bom.html#gen4
  38. points to International Components for Unicode (ICU)
  39. http://site.icu-project.org/ as an example of how to write a UTF
  40. converter.
  41. The decision to use the ConvertUTF.[ch] code was made to leverage
  42. "proven" code. Hopefully the local modifications are bug free.
  43. The code in isValidCodePoint() is derived from the ICU code in
  44. utf.h for the macros U_IS_UNICODE_NONCHAR and U_IS_UNICODE_CHAR.
  45. From the original ConvertUTF.[ch]:
  46. * Copyright 2001-2004 Unicode, Inc.
  47. *
  48. * Disclaimer
  49. *
  50. * This source code is provided as is by Unicode, Inc. No claims are
  51. * made as to fitness for any particular purpose. No warranties of any
  52. * kind are expressed or implied. The recipient agrees to determine
  53. * applicability of information provided. If this file has been
  54. * purchased on magnetic or optical media from Unicode, Inc., the
  55. * sole remedy for any claim will be exchange of defective media
  56. * within 90 days of receipt.
  57. *
  58. * Limitations on Rights to Redistribute This Code
  59. *
  60. * Unicode, Inc. hereby grants the right to freely use the information
  61. * supplied in this file in the creation of products supporting the
  62. * Unicode Standard, and to make copies of this file in any form
  63. * for internal or external distribution as long as this notice
  64. * remains attached.
  65. */
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <stdint.h>
  69. #include <string.h>
  70. #include <assert.h>
  71. #include <sys/errno.h>
  72. #include <math.h>
  73. #include <limits.h>
  74. #include <objc/runtime.h>
  75. #import "JSONKit.h"
  76. //#include <CoreFoundation/CoreFoundation.h>
  77. #include <CoreFoundation/CFString.h>
  78. #include <CoreFoundation/CFArray.h>
  79. #include <CoreFoundation/CFDictionary.h>
  80. #include <CoreFoundation/CFNumber.h>
  81. //#import <Foundation/Foundation.h>
  82. #import <Foundation/NSArray.h>
  83. #import <Foundation/NSAutoreleasePool.h>
  84. #import <Foundation/NSData.h>
  85. #import <Foundation/NSDictionary.h>
  86. #import <Foundation/NSException.h>
  87. #import <Foundation/NSNull.h>
  88. #import <Foundation/NSObjCRuntime.h>
  89. #ifdef JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS
  90. #warning As of JSONKit v1.4, JK_ENABLE_CF_TRANSFER_OWNERSHIP_CALLBACKS is no longer required. It is no longer a valid option.
  91. #endif
  92. #ifdef __OBJC_GC__
  93. #error JSONKit does not support Objective-C Garbage Collection
  94. #endif
  95. // The following checks are really nothing more than sanity checks.
  96. // JSONKit technically has a few problems from a "strictly C99 conforming" standpoint, though they are of the pedantic nitpicking variety.
  97. // 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.
  98. // 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.
  99. #if (UINT_MAX != 0xffffffffU) || (INT_MIN != (-0x7fffffff-1)) || (ULLONG_MAX != 0xffffffffffffffffULL) || (LLONG_MIN != (-0x7fffffffffffffffLL-1LL))
  100. #error JSONKit requires the C 'int' and 'long long' types to be 32 and 64 bits respectively.
  101. #endif
  102. #if !defined(__LP64__) && ((UINT_MAX != ULONG_MAX) || (INT_MAX != LONG_MAX) || (INT_MIN != LONG_MIN) || (WORD_BIT != LONG_BIT))
  103. #error JSONKit requires the C 'int' and 'long' types to be the same on 32-bit architectures.
  104. #endif
  105. // 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
  106. #if (NSUIntegerMax != ULONG_MAX) || (NSIntegerMax != LONG_MAX) || (NSIntegerMin != LONG_MIN)
  107. #error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'long' type.
  108. #endif
  109. #if (NSUIntegerMax != SIZE_MAX) || (NSIntegerMax != SSIZE_MAX)
  110. #error JSONKit requires NSInteger and NSUInteger to be the same size as the C 'size_t' type.
  111. #endif
  112. // For DJB hash.
  113. #define JK_HASH_INIT (1402737925UL)
  114. // Use __builtin_clz() instead of trailingBytesForUTF8[] table lookup.
  115. #define JK_FAST_TRAILING_BYTES
  116. // JK_CACHE_SLOTS must be a power of 2. Default size is 1024 slots.
  117. #define JK_CACHE_SLOTS_BITS (10)
  118. #define JK_CACHE_SLOTS (1UL << JK_CACHE_SLOTS_BITS)
  119. // JK_CACHE_PROBES is the number of probe attempts.
  120. #define JK_CACHE_PROBES (4UL)
  121. // JK_INIT_CACHE_AGE must be (1 << AGE) - 1
  122. #define JK_INIT_CACHE_AGE (0)
  123. // JK_TOKENBUFFER_SIZE is the default stack size for the temporary buffer used to hold "non-simple" strings (i.e., contains \ escapes)
  124. #define JK_TOKENBUFFER_SIZE (1024UL * 2UL)
  125. // 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.
  126. #define JK_STACK_OBJS (1024UL * 1UL)
  127. #define JK_JSONBUFFER_SIZE (1024UL * 4UL)
  128. #define JK_UTF8BUFFER_SIZE (1024UL * 16UL)
  129. #define JK_ENCODE_CACHE_SLOTS (1024UL)
  130. #if defined (__GNUC__) && (__GNUC__ >= 4)
  131. #define JK_ATTRIBUTES(attr, ...) __attribute__((attr, ##__VA_ARGS__))
  132. #define JK_EXPECTED(cond, expect) __builtin_expect((long)(cond), (expect))
  133. #define JK_EXPECT_T(cond) JK_EXPECTED(cond, 1U)
  134. #define JK_EXPECT_F(cond) JK_EXPECTED(cond, 0U)
  135. #define JK_PREFETCH(ptr) __builtin_prefetch(ptr)
  136. #else // defined (__GNUC__) && (__GNUC__ >= 4)
  137. #define JK_ATTRIBUTES(attr, ...)
  138. #define JK_EXPECTED(cond, expect) (cond)
  139. #define JK_EXPECT_T(cond) (cond)
  140. #define JK_EXPECT_F(cond) (cond)
  141. #define JK_PREFETCH(ptr)
  142. #endif // defined (__GNUC__) && (__GNUC__ >= 4)
  143. #define JK_STATIC_INLINE static __inline__ JK_ATTRIBUTES(always_inline)
  144. #define JK_ALIGNED(arg) JK_ATTRIBUTES(aligned(arg))
  145. #define JK_UNUSED_ARG JK_ATTRIBUTES(unused)
  146. #define JK_WARN_UNUSED JK_ATTRIBUTES(warn_unused_result)
  147. #define JK_WARN_UNUSED_CONST JK_ATTRIBUTES(warn_unused_result, const)
  148. #define JK_WARN_UNUSED_PURE JK_ATTRIBUTES(warn_unused_result, pure)
  149. #define JK_WARN_UNUSED_SENTINEL JK_ATTRIBUTES(warn_unused_result, sentinel)
  150. #define JK_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(nonnull(arg, ##__VA_ARGS__))
  151. #define JK_WARN_UNUSED_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(arg, ##__VA_ARGS__))
  152. #define JK_WARN_UNUSED_CONST_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, const, nonnull(arg, ##__VA_ARGS__))
  153. #define JK_WARN_UNUSED_PURE_NONNULL_ARGS(arg, ...) JK_ATTRIBUTES(warn_unused_result, pure, nonnull(arg, ##__VA_ARGS__))
  154. #if defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
  155. #define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__), alloc_size(as))
  156. #else // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
  157. #define JK_ALLOC_SIZE_NON_NULL_ARGS_WARN_UNUSED(as, nn, ...) JK_ATTRIBUTES(warn_unused_result, nonnull(nn, ##__VA_ARGS__))
  158. #endif // defined (__GNUC__) && (__GNUC__ >= 4) && (__GNUC_MINOR__ >= 3)
  159. @class JKArray, JKDictionaryEnumerator, JKDictionary;
  160. enum {
  161. JSONNumberStateStart = 0,
  162. JSONNumberStateFinished = 1,
  163. JSONNumberStateError = 2,
  164. JSONNumberStateWholeNumberStart = 3,
  165. JSONNumberStateWholeNumberMinus = 4,
  166. JSONNumberStateWholeNumberZero = 5,
  167. JSONNumberStateWholeNumber = 6,
  168. JSONNumberStatePeriod = 7,
  169. JSONNumberStateFractionalNumberStart = 8,
  170. JSONNumberStateFractionalNumber = 9,
  171. JSONNumberStateExponentStart = 10,
  172. JSONNumberStateExponentPlusMinus = 11,
  173. JSONNumberStateExponent = 12,
  174. };
  175. enum {
  176. JSONStringStateStart = 0,
  177. JSONStringStateParsing = 1,
  178. JSONStringStateFinished = 2,
  179. JSONStringStateError = 3,
  180. JSONStringStateEscape = 4,
  181. JSONStringStateEscapedUnicode1 = 5,
  182. JSONStringStateEscapedUnicode2 = 6,
  183. JSONStringStateEscapedUnicode3 = 7,
  184. JSONStringStateEscapedUnicode4 = 8,
  185. JSONStringStateEscapedUnicodeSurrogate1 = 9,
  186. JSONStringStateEscapedUnicodeSurrogate2 = 10,
  187. JSONStringStateEscapedUnicodeSurrogate3 = 11,
  188. JSONStringStateEscapedUnicodeSurrogate4 = 12,
  189. JSONStringStateEscapedNeedEscapeForSurrogate = 13,
  190. JSONStringStateEscapedNeedEscapedUForSurrogate = 14,
  191. };
  192. enum {
  193. JKParseAcceptValue = (1 << 0),
  194. JKParseAcceptComma = (1 << 1),
  195. JKParseAcceptEnd = (1 << 2),
  196. JKParseAcceptValueOrEnd = (JKParseAcceptValue | JKParseAcceptEnd),
  197. JKParseAcceptCommaOrEnd = (JKParseAcceptComma | JKParseAcceptEnd),
  198. };
  199. enum {
  200. JKClassUnknown = 0,
  201. JKClassString = 1,
  202. JKClassNumber = 2,
  203. JKClassArray = 3,
  204. JKClassDictionary = 4,
  205. JKClassNull = 5,
  206. };
  207. enum {
  208. JKManagedBufferOnStack = 1,
  209. JKManagedBufferOnHeap = 2,
  210. JKManagedBufferLocationMask = (0x3),
  211. JKManagedBufferLocationShift = (0),
  212. JKManagedBufferMustFree = (1 << 2),
  213. };
  214. typedef JKFlags JKManagedBufferFlags;
  215. enum {
  216. JKObjectStackOnStack = 1,
  217. JKObjectStackOnHeap = 2,
  218. JKObjectStackLocationMask = (0x3),
  219. JKObjectStackLocationShift = (0),
  220. JKObjectStackMustFree = (1 << 2),
  221. };
  222. typedef JKFlags JKObjectStackFlags;
  223. enum {
  224. JKTokenTypeInvalid = 0,
  225. JKTokenTypeNumber = 1,
  226. JKTokenTypeString = 2,
  227. JKTokenTypeObjectBegin = 3,
  228. JKTokenTypeObjectEnd = 4,
  229. JKTokenTypeArrayBegin = 5,
  230. JKTokenTypeArrayEnd = 6,
  231. JKTokenTypeSeparator = 7,
  232. JKTokenTypeComma = 8,
  233. JKTokenTypeTrue = 9,
  234. JKTokenTypeFalse = 10,
  235. JKTokenTypeNull = 11,
  236. JKTokenTypeWhiteSpace = 12,
  237. };
  238. typedef NSUInteger JKTokenType;
  239. // These are prime numbers to assist with hash slot probing.
  240. enum {
  241. JKValueTypeNone = 0,
  242. JKValueTypeString = 5,
  243. JKValueTypeLongLong = 7,
  244. JKValueTypeUnsignedLongLong = 11,
  245. JKValueTypeDouble = 13,
  246. };
  247. typedef NSUInteger JKValueType;
  248. enum {
  249. JKEncodeOptionAsData = 1,
  250. JKEncodeOptionAsString = 2,
  251. JKEncodeOptionAsTypeMask = 0x7,
  252. JKEncodeOptionCollectionObj = (1 << 3),
  253. JKEncodeOptionStringObj = (1 << 4),
  254. JKEncodeOptionStringObjTrimQuotes = (1 << 5),
  255. };
  256. typedef NSUInteger JKEncodeOptionType;
  257. typedef NSUInteger JKHash;
  258. typedef struct JKTokenCacheItem JKTokenCacheItem;
  259. typedef struct JKTokenCache JKTokenCache;
  260. typedef struct JKTokenValue JKTokenValue;
  261. typedef struct JKParseToken JKParseToken;
  262. typedef struct JKPtrRange JKPtrRange;
  263. typedef struct JKObjectStack JKObjectStack;
  264. typedef struct JKBuffer JKBuffer;
  265. typedef struct JKConstBuffer JKConstBuffer;
  266. typedef struct JKConstPtrRange JKConstPtrRange;
  267. typedef struct JKRange JKRange;
  268. typedef struct JKManagedBuffer JKManagedBuffer;
  269. typedef struct JKFastClassLookup JKFastClassLookup;
  270. typedef struct JKEncodeCache JKEncodeCache;
  271. typedef struct JKEncodeState JKEncodeState;
  272. typedef struct JKObjCImpCache JKObjCImpCache;
  273. typedef struct JKHashTableEntry JKHashTableEntry;
  274. typedef id (*NSNumberAllocImp)(id object, SEL selector);
  275. typedef id (*NSNumberInitWithUnsignedLongLongImp)(id object, SEL selector, unsigned long long value);
  276. struct JKPtrRange {
  277. unsigned char *ptr;
  278. size_t length;
  279. };
  280. struct JKConstPtrRange {
  281. const unsigned char *ptr;
  282. size_t length;
  283. };
  284. struct JKRange {
  285. size_t location, length;
  286. };
  287. struct JKManagedBuffer {
  288. JKPtrRange bytes;
  289. JKManagedBufferFlags flags;
  290. size_t roundSizeUpToMultipleOf;
  291. };
  292. struct JKObjectStack {
  293. void **objects, **keys;
  294. CFHashCode *cfHashes;
  295. size_t count, index, roundSizeUpToMultipleOf;
  296. JKObjectStackFlags flags;
  297. };
  298. struct JKBuffer {
  299. JKPtrRange bytes;
  300. };
  301. struct JKConstBuffer {
  302. JKConstPtrRange bytes;
  303. };
  304. struct JKTokenValue {
  305. JKConstPtrRange ptrRange;
  306. JKValueType type;
  307. JKHash hash;
  308. union {
  309. long long longLongValue;
  310. unsigned long long unsignedLongLongValue;
  311. double doubleValue;
  312. } number;
  313. JKTokenCacheItem *cacheItem;
  314. };
  315. struct JKParseToken {
  316. JKConstPtrRange tokenPtrRange;
  317. JKTokenType type;
  318. JKTokenValue value;
  319. JKManagedBuffer tokenBuffer;
  320. };
  321. struct JKTokenCacheItem {
  322. void *object;
  323. JKHash hash;
  324. CFHashCode cfHash;
  325. size_t size;
  326. unsigned char *bytes;
  327. JKValueType type;
  328. };
  329. struct JKTokenCache {
  330. JKTokenCacheItem *items;
  331. size_t count;
  332. unsigned int prng_lfsr;
  333. unsigned char age[JK_CACHE_SLOTS];
  334. };
  335. struct JKObjCImpCache {
  336. Class NSNumberClass;
  337. NSNumberAllocImp NSNumberAlloc;
  338. NSNumberInitWithUnsignedLongLongImp NSNumberInitWithUnsignedLongLong;
  339. };
  340. struct JKParseState {
  341. JKParseOptionFlags parseOptionFlags;
  342. JKConstBuffer stringBuffer;
  343. size_t atIndex, lineNumber, lineStartIndex;
  344. size_t prev_atIndex, prev_lineNumber, prev_lineStartIndex;
  345. JKParseToken token;
  346. JKObjectStack objectStack;
  347. JKTokenCache cache;
  348. JKObjCImpCache objCImpCache;
  349. NSError *error;
  350. int errorIsPrev;
  351. BOOL mutableCollections;
  352. };
  353. struct JKFastClassLookup {
  354. void *stringClass;
  355. void *numberClass;
  356. void *arrayClass;
  357. void *dictionaryClass;
  358. void *nullClass;
  359. };
  360. struct JKEncodeCache {
  361. id object;
  362. size_t offset;
  363. size_t length;
  364. };
  365. struct JKEncodeState {
  366. JKManagedBuffer utf8ConversionBuffer;
  367. JKManagedBuffer stringBuffer;
  368. size_t atIndex;
  369. JKFastClassLookup fastClassLookup;
  370. JKEncodeCache cache[JK_ENCODE_CACHE_SLOTS];
  371. JKSerializeOptionFlags serializeOptionFlags;
  372. JKEncodeOptionType encodeOption;
  373. size_t depth;
  374. NSError *error;
  375. };
  376. // This is a JSONKit private class.
  377. @interface JKSerializer : NSObject {
  378. JKEncodeState *encodeState;
  379. }
  380. + (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption error:(NSError **)error;
  381. - (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption error:(NSError **)error;
  382. - (void)releaseState;
  383. @end
  384. struct JKHashTableEntry {
  385. NSUInteger keyHash;
  386. id key, object;
  387. };
  388. typedef uint32_t UTF32; /* at least 32 bits */
  389. typedef uint16_t UTF16; /* at least 16 bits */
  390. typedef uint8_t UTF8; /* typically 8 bits */
  391. typedef enum {
  392. conversionOK, /* conversion successful */
  393. sourceExhausted, /* partial character in source, but hit end */
  394. targetExhausted, /* insuff. room in target for conversion */
  395. sourceIllegal /* source sequence is illegal/malformed */
  396. } ConversionResult;
  397. #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD
  398. #define UNI_MAX_BMP (UTF32)0x0000FFFF
  399. #define UNI_MAX_UTF16 (UTF32)0x0010FFFF
  400. #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
  401. #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
  402. #define UNI_SUR_HIGH_START (UTF32)0xD800
  403. #define UNI_SUR_HIGH_END (UTF32)0xDBFF
  404. #define UNI_SUR_LOW_START (UTF32)0xDC00
  405. #define UNI_SUR_LOW_END (UTF32)0xDFFF
  406. #if !defined(JK_FAST_TRAILING_BYTES)
  407. static const char trailingBytesForUTF8[256] = {
  408. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  409. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  410. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  411. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  412. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  413. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  414. 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,
  415. 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
  416. };
  417. #endif
  418. static const UTF32 offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL };
  419. static const UTF8 firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  420. #define JK_AT_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->atIndex]))
  421. #define JK_END_STRING_PTR(x) (&((x)->stringBuffer.bytes.ptr[(x)->stringBuffer.bytes.length]))
  422. static void jk_swizzleInstanceMethod(Class fromClass, Class toClass, SEL selector);
  423. static void jk_swizzleClassMethod(Class fromClass, Class toClass, SEL selector);
  424. static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection);
  425. static NSUInteger _JKArrayCount(JKArray *array);
  426. static void _JKArrayIncrementMutations(JKArray *array);
  427. static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex);
  428. static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject);
  429. static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex);
  430. static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count);
  431. static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection);
  432. static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary);
  433. static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary);
  434. static NSUInteger _JKDictionaryCount(JKDictionary *dictionary);
  435. static void _JKDictionaryIncrementMutations(JKDictionary *dictionary);
  436. static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary);
  437. static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry);
  438. static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object);
  439. static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey);
  440. static NSUInteger _JKDictionaryGetKeysAndObjects(JKDictionary *dictionary, NSUInteger arrayLength, id keys[arrayLength], id objects[arrayLength]);
  441. static void _JSONDecoderCleanup(JSONDecoder *decoder);
  442. static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection);
  443. static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer);
  444. static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length);
  445. static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize);
  446. static void jk_objectStack_release(JKObjectStack *objectStack);
  447. static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count);
  448. static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount);
  449. static void jk_error(JKParseState *parseState, NSString *format, ...);
  450. static int jk_parse_string(JKParseState *parseState);
  451. static int jk_parse_number(JKParseState *parseState);
  452. static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr);
  453. JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState);
  454. JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState);
  455. static int jk_parse_next_token(JKParseState *parseState);
  456. static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String);
  457. static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex);
  458. static void *jk_parse_dictionary(JKParseState *parseState);
  459. static void *jk_parse_array(JKParseState *parseState);
  460. static void *jk_object_for_token(JKParseState *parseState);
  461. static void *jk_cachedObjects(JKParseState *parseState);
  462. JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState);
  463. JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy);
  464. static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...);
  465. static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...);
  466. static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format);
  467. static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState);
  468. static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format);
  469. static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format);
  470. static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length);
  471. JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr);
  472. JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object);
  473. static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr);
  474. #define jk_encode_write1(es, dc, f) (_jk_encode_useWrite1Fast ? jk_encode_write1fast(es, dc, f) : jk_encode_write1slow(es, dc, f))
  475. JK_STATIC_INLINE size_t jk_min(size_t a, size_t b);
  476. JK_STATIC_INLINE size_t jk_max(size_t a, size_t b);
  477. JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c);
  478. #pragma mark -
  479. #pragma mark ObjC Voodoo
  480. // These two functions are used to perform some ObjC swizzling voodoo to implement our mutable collection classes.
  481. static void jk_swizzleInstanceMethod(Class fromClass, Class toClass, SEL selector) {
  482. fromClass = class_isMetaClass(fromClass) ? objc_getClass(class_getName(fromClass)) : fromClass;
  483. toClass = class_isMetaClass(toClass) ? objc_getClass(class_getName(toClass)) : toClass;
  484. class_replaceMethod(fromClass, selector, method_getImplementation(class_getInstanceMethod(toClass, selector)), method_getTypeEncoding(class_getInstanceMethod(fromClass, selector)));
  485. }
  486. static void jk_swizzleClassMethod(Class fromClass, Class toClass, SEL selector) {
  487. fromClass = class_isMetaClass(fromClass) ? fromClass : objc_getMetaClass(class_getName(fromClass));
  488. toClass = class_isMetaClass(toClass) ? toClass : objc_getMetaClass(class_getName(toClass));
  489. class_replaceMethod(fromClass, selector, method_getImplementation(class_getClassMethod(toClass, selector)), method_getTypeEncoding(class_getClassMethod(fromClass, selector)));
  490. }
  491. #pragma mark -
  492. @interface JKArray : NSArray <NSCopying, NSMutableCopying, NSFastEnumeration> {
  493. id *objects;
  494. NSUInteger count, capacity, mutations;
  495. }
  496. @end
  497. @implementation JKArray
  498. static Class _JKArrayClass = NULL;
  499. static Class _JKMutableArrayClass = NULL;
  500. static size_t _JKArrayInstanceSize = 0UL;
  501. + (void)load
  502. {
  503. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
  504. _JKArrayClass = objc_getClass("JKArray");
  505. _JKMutableArrayClass = objc_getClass("JKMutableArray");
  506. _JKArrayInstanceSize = jk_max(16UL, class_getInstanceSize(_JKArrayClass));
  507. [pool release]; pool = NULL;
  508. }
  509. + (id)allocWithZone:(NSZone *)zone
  510. {
  511. #pragma unused(zone)
  512. [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])];
  513. return(NULL);
  514. }
  515. static JKArray *_JKArrayCreate(id *objects, NSUInteger count, BOOL mutableCollection) {
  516. NSCParameterAssert((objects != NULL) && (_JKArrayClass != NULL) && (_JKArrayInstanceSize > 0UL));
  517. JKArray *array = NULL;
  518. if(JK_EXPECT_T((array = (JKArray *)calloc(1UL, _JKArrayInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc.
  519. object_setClass(array, (mutableCollection == NO) ? _JKArrayClass : _JKMutableArrayClass);
  520. if((array = [array init]) == NULL) { return(NULL); }
  521. array->capacity = count;
  522. array->count = count;
  523. if(JK_EXPECT_F((array->objects = (id *)malloc(sizeof(id) * array->capacity)) == NULL)) { [array autorelease]; return(NULL); }
  524. memcpy(array->objects, objects, array->capacity * sizeof(id));
  525. }
  526. return(array);
  527. }
  528. static NSUInteger _JKArrayCount(JKArray *array) {
  529. NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity));
  530. return(array->count);
  531. }
  532. static void _JKArrayIncrementMutations(JKArray *array) {
  533. NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity));
  534. array->mutations++;
  535. }
  536. // Note: The caller is responsible for -retaining the object that is to be added.
  537. static void _JKArrayInsertObjectAtIndex(JKArray *array, id newObject, NSUInteger objectIndex) {
  538. NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex <= array->count) && (newObject != NULL));
  539. if(!((array != NULL) && (array->objects != NULL) && (objectIndex <= array->count) && (newObject != NULL))) { [newObject autorelease]; return; }
  540. array->count++;
  541. if(array->count >= array->capacity) {
  542. array->capacity += 16UL;
  543. id *newObjects = NULL;
  544. if((newObjects = (id *)realloc(array->objects, sizeof(id) * array->capacity)) == NULL) { [NSException raise:NSMallocException format:@"Unable to resize objects array."]; }
  545. array->objects = newObjects;
  546. memset(&array->objects[array->count], 0, sizeof(id) * (array->capacity - array->count));
  547. }
  548. if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex + 1UL], &array->objects[objectIndex], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[objectIndex] = NULL; }
  549. array->objects[objectIndex] = newObject;
  550. }
  551. // Note: The caller is responsible for -retaining the object that is to be added.
  552. static void _JKArrayReplaceObjectAtIndexWithObject(JKArray *array, NSUInteger objectIndex, id newObject) {
  553. NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL));
  554. if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL) && (newObject != NULL))) { [newObject autorelease]; return; }
  555. CFRelease(array->objects[objectIndex]);
  556. array->objects[objectIndex] = NULL;
  557. array->objects[objectIndex] = newObject;
  558. }
  559. static void _JKArrayRemoveObjectAtIndex(JKArray *array, NSUInteger objectIndex) {
  560. NSCParameterAssert((array != NULL) && (array->objects != NULL) && (array->count <= array->capacity) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL));
  561. if(!((array != NULL) && (array->objects != NULL) && (objectIndex < array->count) && (array->objects[objectIndex] != NULL))) { return; }
  562. CFRelease(array->objects[objectIndex]);
  563. array->objects[objectIndex] = NULL;
  564. if((objectIndex + 1UL) < array->count) { memmove(&array->objects[objectIndex], &array->objects[objectIndex + 1UL], sizeof(id) * ((array->count - 1UL) - objectIndex)); array->objects[array->count] = NULL; }
  565. array->count--;
  566. }
  567. - (void)dealloc
  568. {
  569. if(JK_EXPECT_T(objects != NULL)) {
  570. NSUInteger atObject = 0UL;
  571. for(atObject = 0UL; atObject < count; atObject++) { if(JK_EXPECT_T(objects[atObject] != NULL)) { CFRelease(objects[atObject]); objects[atObject] = NULL; } }
  572. free(objects); objects = NULL;
  573. }
  574. [super dealloc];
  575. }
  576. - (NSUInteger)count
  577. {
  578. NSParameterAssert((objects != NULL) && (count <= capacity));
  579. return(count);
  580. }
  581. - (void)getObjects:(id *)objectsPtr range:(NSRange)range
  582. {
  583. NSParameterAssert((objects != NULL) && (count <= capacity));
  584. if((objectsPtr == NULL) && (NSMaxRange(range) > 0UL)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: pointer to objects array is NULL but range length is %lu", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range)]; }
  585. if((range.location > count) || (NSMaxRange(range) > count)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)NSMaxRange(range), (unsigned long)count]; }
  586. memcpy(objectsPtr, objects + range.location, range.length * sizeof(id));
  587. }
  588. - (id)objectAtIndex:(NSUInteger)objectIndex
  589. {
  590. if(objectIndex >= count) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)count]; }
  591. NSParameterAssert((objects != NULL) && (count <= capacity) && (objects[objectIndex] != NULL));
  592. return(objects[objectIndex]);
  593. }
  594. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
  595. {
  596. NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (objects != NULL) && (count <= capacity));
  597. if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
  598. if(JK_EXPECT_F(state->state >= count)) { return(0UL); }
  599. NSUInteger enumeratedCount = 0UL;
  600. while(JK_EXPECT_T(enumeratedCount < len) && JK_EXPECT_T(state->state < count)) { NSParameterAssert(objects[state->state] != NULL); stackbuf[enumeratedCount++] = objects[state->state++]; }
  601. return(enumeratedCount);
  602. }
  603. - (id)copyWithZone:(NSZone *)zone
  604. {
  605. #pragma unused(zone)
  606. NSParameterAssert((objects != NULL) && (count <= capacity));
  607. return([self retain]);
  608. }
  609. - (id)mutableCopyWithZone:(NSZone *)zone
  610. {
  611. NSParameterAssert((objects != NULL) && (count <= capacity));
  612. return([[NSMutableArray allocWithZone:zone] initWithObjects:objects count:count]);
  613. }
  614. @end
  615. #pragma mark -
  616. @interface JKMutableArray : NSMutableArray
  617. @end
  618. @implementation JKMutableArray
  619. + (void)load
  620. {
  621. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
  622. Class JKMutableArrayClass = objc_getClass("JKMutableArray"); Class JKArrayClass = objc_getClass("JKArray");
  623. // We swizzle the methods from JKArray in to this class (JKArrayDictionary).
  624. jk_swizzleClassMethod(JKMutableArrayClass, JKArrayClass, @selector(allocWithZone:));
  625. jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(dealloc));
  626. jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(count));
  627. jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(objectAtIndex:));
  628. jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(getObjects:range:));
  629. jk_swizzleInstanceMethod(JKMutableArrayClass, JKArrayClass, @selector(countByEnumeratingWithState:objects:count:));
  630. [pool release]; pool = NULL;
  631. }
  632. - (void)insertObject:(id)anObject atIndex:(NSUInteger)objectIndex
  633. {
  634. if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
  635. if(objectIndex > _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, _JKArrayCount((JKArray *)self) + 1UL]; }
  636. anObject = [anObject retain];
  637. _JKArrayInsertObjectAtIndex((JKArray *)self, anObject, objectIndex);
  638. _JKArrayIncrementMutations((JKArray *)self);
  639. }
  640. - (void)removeObjectAtIndex:(NSUInteger)objectIndex
  641. {
  642. if(objectIndex >= _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)_JKArrayCount((JKArray *)self)]; }
  643. _JKArrayRemoveObjectAtIndex((JKArray *)self, objectIndex);
  644. _JKArrayIncrementMutations((JKArray *)self);
  645. }
  646. - (void)replaceObjectAtIndex:(NSUInteger)objectIndex withObject:(id)anObject
  647. {
  648. if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
  649. if(objectIndex >= _JKArrayCount((JKArray *)self)) { [NSException raise:NSRangeException format:@"*** -[%@ %@]: index (%lu) beyond bounds (%lu)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), (unsigned long)objectIndex, (unsigned long)_JKArrayCount((JKArray *)self)]; }
  650. anObject = [anObject retain];
  651. _JKArrayReplaceObjectAtIndexWithObject((JKArray *)self, objectIndex, anObject);
  652. _JKArrayIncrementMutations((JKArray *)self);
  653. }
  654. - (id)copyWithZone:(NSZone *)zone
  655. {
  656. NSUInteger arrayCount = [self count];
  657. if(arrayCount == 0UL) { return([[NSArray allocWithZone:zone] init]); }
  658. id stackObjects[arrayCount];
  659. [self getObjects:stackObjects range:NSMakeRange(0UL, arrayCount)];
  660. return([[NSArray allocWithZone:zone] initWithObjects:stackObjects count:arrayCount]);
  661. }
  662. - (id)mutableCopyWithZone:(NSZone *)zone
  663. {
  664. NSUInteger arrayCount = [self count];
  665. if(arrayCount == 0UL) { return([[NSMutableArray allocWithZone:zone] init]); }
  666. id stackObjects[arrayCount];
  667. [self getObjects:stackObjects range:NSMakeRange(0UL, arrayCount)];
  668. return([[NSMutableArray allocWithZone:zone] initWithObjects:stackObjects count:arrayCount]);
  669. }
  670. @end
  671. #pragma mark -
  672. @interface JKDictionaryEnumerator : NSEnumerator {
  673. id collection;
  674. NSUInteger nextObject;
  675. }
  676. - (id)initWithJKDictionary:(JKDictionary *)initDictionary;
  677. - (NSArray *)allObjects;
  678. - (id)nextObject;
  679. @end
  680. @implementation JKDictionaryEnumerator
  681. - (id)initWithJKDictionary:(JKDictionary *)initDictionary
  682. {
  683. NSParameterAssert(initDictionary != NULL);
  684. if((self = [super init]) == NULL) { return(NULL); }
  685. if((collection = (id)CFRetain(initDictionary)) == NULL) { [self autorelease]; return(NULL); }
  686. return(self);
  687. }
  688. - (void)dealloc
  689. {
  690. if(collection != NULL) { CFRelease(collection); collection = NULL; }
  691. [super dealloc];
  692. }
  693. - (NSArray *)allObjects
  694. {
  695. NSParameterAssert(collection != NULL);
  696. NSUInteger count = [collection count], atObject = 0UL;
  697. id objects[count];
  698. while((objects[atObject] = [self nextObject]) != NULL) { NSParameterAssert(atObject < count); atObject++; }
  699. return([NSArray arrayWithObjects:objects count:atObject]);
  700. }
  701. - (id)nextObject
  702. {
  703. NSParameterAssert((collection != NULL) && (_JKDictionaryHashEntry(collection) != NULL));
  704. JKHashTableEntry *entry = _JKDictionaryHashEntry(collection);
  705. NSUInteger capacity = _JKDictionaryCapacity(collection);
  706. id returnObject = NULL;
  707. if(entry != NULL) { while((nextObject < capacity) && ((returnObject = entry[nextObject++].key) == NULL)) { /* ... */ } }
  708. return(returnObject);
  709. }
  710. @end
  711. #pragma mark -
  712. @interface JKDictionary : NSDictionary <NSCopying, NSMutableCopying, NSFastEnumeration> {
  713. NSUInteger count, capacity, mutations;
  714. JKHashTableEntry *entry;
  715. }
  716. @end
  717. @implementation JKDictionary
  718. static Class _JKDictionaryClass = NULL;
  719. static Class _JKMutableDictionaryClass = NULL;
  720. static size_t _JKDictionaryInstanceSize = 0UL;
  721. + (void)load
  722. {
  723. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
  724. _JKDictionaryClass = objc_getClass("JKDictionary");
  725. _JKMutableDictionaryClass = objc_getClass("JKMutableDictionary");
  726. _JKDictionaryInstanceSize = jk_max(16UL, class_getInstanceSize(_JKDictionaryClass));
  727. [pool release]; pool = NULL;
  728. }
  729. + (id)allocWithZone:(NSZone *)zone
  730. {
  731. #pragma unused(zone)
  732. [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])];
  733. return(NULL);
  734. }
  735. // These values are taken from Core Foundation CF-550 CFBasicHash.m. As a bonus, they align very well with our JKHashTableEntry struct too.
  736. static const NSUInteger jk_dictionaryCapacities[] = {
  737. 0UL, 3UL, 7UL, 13UL, 23UL, 41UL, 71UL, 127UL, 191UL, 251UL, 383UL, 631UL, 1087UL, 1723UL,
  738. 2803UL, 4523UL, 7351UL, 11959UL, 19447UL, 31231UL, 50683UL, 81919UL, 132607UL,
  739. 214519UL, 346607UL, 561109UL, 907759UL, 1468927UL, 2376191UL, 3845119UL,
  740. 6221311UL, 10066421UL, 16287743UL, 26354171UL, 42641881UL, 68996069UL,
  741. 111638519UL, 180634607UL, 292272623UL, 472907251UL
  742. };
  743. static NSUInteger _JKDictionaryCapacityForCount(NSUInteger count) {
  744. NSUInteger bottom = 0UL, top = sizeof(jk_dictionaryCapacities) / sizeof(NSUInteger), mid = 0UL, tableSize = lround(floor((count) * 1.33));
  745. while(top > bottom) { mid = (top + bottom) / 2UL; if(jk_dictionaryCapacities[mid] < tableSize) { bottom = mid + 1UL; } else { top = mid; } }
  746. return(jk_dictionaryCapacities[bottom]);
  747. }
  748. static void _JKDictionaryResizeIfNeccessary(JKDictionary *dictionary) {
  749. NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
  750. NSUInteger capacityForCount = 0UL;
  751. if(dictionary->capacity < (capacityForCount = _JKDictionaryCapacityForCount(dictionary->count + 1UL))) { // resize
  752. NSUInteger oldCapacity = dictionary->capacity;
  753. #ifndef NS_BLOCK_ASSERTIONS
  754. NSUInteger oldCount = dictionary->count;
  755. #endif
  756. JKHashTableEntry *oldEntry = dictionary->entry;
  757. if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * capacityForCount)) == NULL)) { [NSException raise:NSMallocException format:@"Unable to allocate memory for hash table."]; }
  758. dictionary->capacity = capacityForCount;
  759. dictionary->count = 0UL;
  760. NSUInteger idx = 0UL;
  761. 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; } }
  762. NSCParameterAssert((oldCount == dictionary->count));
  763. free(oldEntry); oldEntry = NULL;
  764. }
  765. }
  766. static JKDictionary *_JKDictionaryCreate(id *keys, NSUInteger *keyHashes, id *objects, NSUInteger count, BOOL mutableCollection) {
  767. NSCParameterAssert((keys != NULL) && (keyHashes != NULL) && (objects != NULL) && (_JKDictionaryClass != NULL) && (_JKDictionaryInstanceSize > 0UL));
  768. JKDictionary *dictionary = NULL;
  769. if(JK_EXPECT_T((dictionary = (JKDictionary *)calloc(1UL, _JKDictionaryInstanceSize)) != NULL)) { // Directly allocate the JKArray instance via calloc.
  770. object_setClass(dictionary, (mutableCollection == NO) ? _JKDictionaryClass : _JKMutableDictionaryClass);
  771. if((dictionary = [dictionary init]) == NULL) { return(NULL); }
  772. dictionary->capacity = _JKDictionaryCapacityForCount(count);
  773. dictionary->count = 0UL;
  774. if(JK_EXPECT_F((dictionary->entry = (JKHashTableEntry *)calloc(1UL, sizeof(JKHashTableEntry) * dictionary->capacity)) == NULL)) { [dictionary autorelease]; return(NULL); }
  775. NSUInteger idx = 0UL;
  776. for(idx = 0UL; idx < count; idx++) { _JKDictionaryAddObject(dictionary, keyHashes[idx], keys[idx], objects[idx]); }
  777. }
  778. return(dictionary);
  779. }
  780. - (void)dealloc
  781. {
  782. if(JK_EXPECT_T(entry != NULL)) {
  783. NSUInteger atEntry = 0UL;
  784. for(atEntry = 0UL; atEntry < capacity; atEntry++) {
  785. if(JK_EXPECT_T(entry[atEntry].key != NULL)) { CFRelease(entry[atEntry].key); entry[atEntry].key = NULL; }
  786. if(JK_EXPECT_T(entry[atEntry].object != NULL)) { CFRelease(entry[atEntry].object); entry[atEntry].object = NULL; }
  787. }
  788. free(entry); entry = NULL;
  789. }
  790. [super dealloc];
  791. }
  792. static JKHashTableEntry *_JKDictionaryHashEntry(JKDictionary *dictionary) {
  793. NSCParameterAssert(dictionary != NULL);
  794. return(dictionary->entry);
  795. }
  796. static NSUInteger _JKDictionaryCapacity(JKDictionary *dictionary) {
  797. NSCParameterAssert(dictionary != NULL);
  798. return(dictionary->capacity);
  799. }
  800. static NSUInteger _JKDictionaryCount(JKDictionary *dictionary) {
  801. NSCParameterAssert(dictionary != NULL);
  802. return(dictionary->count);
  803. }
  804. static void _JKDictionaryIncrementMutations(JKDictionary *dictionary) {
  805. NSCParameterAssert(dictionary != NULL);
  806. if(++dictionary->mutations == 0UL) { dictionary->mutations = 1UL; }
  807. }
  808. static void _JKDictionaryRemoveObjectWithEntry(JKDictionary *dictionary, JKHashTableEntry *entry) {
  809. NSCParameterAssert((dictionary != NULL) && (entry != NULL) && (entry->key != NULL) && (entry->object != NULL) && (dictionary->count > 0UL));
  810. CFRelease(entry->key); entry->key = NULL;
  811. CFRelease(entry->object); entry->object = NULL;
  812. entry->keyHash = 0UL;
  813. dictionary->count--;
  814. }
  815. static void _JKDictionaryAddObject(JKDictionary *dictionary, NSUInteger keyHash, id key, id object) {
  816. NSCParameterAssert((dictionary != NULL) && (key != NULL) && (object != NULL) && (dictionary->count < dictionary->capacity) && (dictionary->entry != NULL));
  817. NSUInteger keyEntry = keyHash % dictionary->capacity, idx = 0UL;
  818. for(idx = 0UL; idx < dictionary->capacity; idx++) {
  819. NSUInteger entryIdx = (keyEntry + idx) % dictionary->capacity;
  820. JKHashTableEntry *atEntry = &dictionary->entry[entryIdx];
  821. 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); }
  822. if(JK_EXPECT_T(atEntry->key == NULL)) { atEntry->key = key; atEntry->object = object; atEntry->keyHash = keyHash; dictionary->count++; return; }
  823. }
  824. // We should never get here. If we do, we -release the key / object because it's our responsibility.
  825. CFRelease(key);
  826. CFRelease(object);
  827. }
  828. - (NSUInteger)count
  829. {
  830. return(count);
  831. }
  832. static JKHashTableEntry *_JKDictionaryHashTableEntryForKey(JKDictionary *dictionary, id aKey) {
  833. NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
  834. if(aKey == NULL) { return(NULL); }
  835. NSUInteger keyHash = CFHash(aKey), keyEntry = (keyHash % dictionary->capacity), idx = 0UL;
  836. JKHashTableEntry *atEntry = NULL;
  837. for(idx = 0UL; idx < dictionary->capacity; idx++) {
  838. atEntry = &dictionary->entry[(keyEntry + idx) % dictionary->capacity];
  839. 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; }
  840. 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.
  841. }
  842. return(NULL);
  843. }
  844. - (id)objectForKey:(id)aKey
  845. {
  846. NSParameterAssert((entry != NULL) && (count <= capacity));
  847. JKHashTableEntry *atEntry = _JKDictionaryHashTableEntryForKey(self, aKey);
  848. return((atEntry != NULL) ? atEntry->object : NULL);
  849. }
  850. static NSUInteger _JKDictionaryGetKeysAndObjects(JKDictionary *dictionary, NSUInteger arrayLength, id keys[arrayLength], id objects[arrayLength]) {
  851. NSCParameterAssert((dictionary != NULL) && (dictionary->entry != NULL) && (dictionary->count <= dictionary->capacity));
  852. NSUInteger atEntry = 0UL; NSUInteger arrayIdx = 0UL;
  853. for(atEntry = 0UL; (atEntry < dictionary->capacity) && (arrayIdx < arrayLength); atEntry++) {
  854. if(JK_EXPECT_T(dictionary->entry[atEntry].key != NULL)) {
  855. NSCParameterAssert((dictionary->entry[atEntry].object != NULL) && (arrayIdx < dictionary->count));
  856. if(JK_EXPECT_T(keys != NULL)) { keys[arrayIdx] = dictionary->entry[atEntry].key; }
  857. if(JK_EXPECT_T(objects != NULL)) { objects[arrayIdx] = dictionary->entry[atEntry].object; }
  858. arrayIdx++;
  859. }
  860. }
  861. NSCParameterAssert(arrayIdx == dictionary->count);
  862. return(arrayIdx);
  863. }
  864. - (void)getObjects:(id *)objects andKeys:(id *)keys
  865. {
  866. NSParameterAssert((entry != NULL) && (count <= capacity));
  867. _JKDictionaryGetKeysAndObjects(self, count, keys, objects);
  868. }
  869. - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len
  870. {
  871. NSParameterAssert((state != NULL) && (stackbuf != NULL) && (len > 0UL) && (entry != NULL) && (count <= capacity));
  872. if(JK_EXPECT_F(state->state == 0UL)) { state->mutationsPtr = (unsigned long *)&mutations; state->itemsPtr = stackbuf; }
  873. if(JK_EXPECT_F(state->state >= capacity)) { return(0UL); }
  874. NSUInteger enumeratedCount = 0UL;
  875. 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++; }
  876. return(enumeratedCount);
  877. }
  878. - (NSEnumerator *)keyEnumerator
  879. {
  880. return([[[JKDictionaryEnumerator alloc] initWithJKDictionary:self] autorelease]);
  881. }
  882. - (id)copyWithZone:(NSZone *)zone
  883. {
  884. #pragma unused(zone)
  885. NSParameterAssert((entry != NULL) && (count <= capacity));
  886. return([self retain]);
  887. }
  888. - (id)mutableCopyWithZone:(NSZone *)zone
  889. {
  890. NSParameterAssert((entry != NULL) && (count <= capacity));
  891. id stackKeys[count], stackObjects[count];
  892. NSUInteger gotCount = _JKDictionaryGetKeysAndObjects(self, count, stackKeys, stackObjects);
  893. NSParameterAssert(gotCount == count);
  894. return([[NSMutableDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
  895. }
  896. @end
  897. #pragma mark -
  898. @interface JKMutableDictionary : NSMutableDictionary
  899. @end
  900. @implementation JKMutableDictionary
  901. + (void)load
  902. {
  903. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
  904. Class JKMutableDictionaryClass = objc_getClass("JKMutableDictionary"), JKDictionaryClass = objc_getClass("JKDictionary");
  905. // We swizzle the methods from JKDictionary in to this class (JKMutableDictionary).
  906. jk_swizzleClassMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(allocWithZone:));
  907. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(dealloc));
  908. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(count));
  909. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(objectForKey:));
  910. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(getObjects:andKeys:));
  911. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(keyEnumerator));
  912. jk_swizzleInstanceMethod(JKMutableDictionaryClass, JKDictionaryClass, @selector(countByEnumeratingWithState:objects:count:));
  913. [pool release]; pool = NULL;
  914. }
  915. - (void)setObject:(id)anObject forKey:(id)aKey
  916. {
  917. if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
  918. if(anObject == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to insert nil value (key: %@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), aKey]; }
  919. _JKDictionaryResizeIfNeccessary((JKDictionary *)self);
  920. #ifndef __clang_analyzer__
  921. aKey = [aKey copy]; // Why on earth would clang complain that this -copy "might leak",
  922. anObject = [anObject retain]; // but this -retain doesn't!?
  923. #endif // __clang_analyzer__
  924. _JKDictionaryAddObject((JKDictionary *)self, CFHash(aKey), aKey, anObject);
  925. _JKDictionaryIncrementMutations((JKDictionary *)self);
  926. }
  927. - (void)removeObjectForKey:(id)aKey
  928. {
  929. if(aKey == NULL) { [NSException raise:NSInvalidArgumentException format:@"*** -[%@ %@]: attempt to remove nil key", NSStringFromClass([self class]), NSStringFromSelector(_cmd)]; }
  930. JKHashTableEntry *entry = _JKDictionaryHashTableEntryForKey((JKDictionary *)self, aKey);
  931. if(entry != NULL) {
  932. _JKDictionaryRemoveObjectWithEntry((JKDictionary *)self, entry);
  933. _JKDictionaryIncrementMutations((JKDictionary *)self);
  934. }
  935. }
  936. - (id)copyWithZone:(NSZone *)zone
  937. {
  938. NSUInteger dictionaryCount = _JKDictionaryCount((JKDictionary *)self);
  939. id stackKeys[dictionaryCount], stackObjects[dictionaryCount];
  940. NSUInteger gotCount = _JKDictionaryGetKeysAndObjects((JKDictionary *)self, dictionaryCount, stackKeys, stackObjects);
  941. NSParameterAssert(gotCount == dictionaryCount);
  942. return([[NSDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
  943. }
  944. - (id)mutableCopyWithZone:(NSZone *)zone
  945. {
  946. NSUInteger dictionaryCount = _JKDictionaryCount((JKDictionary *)self);
  947. id stackKeys[dictionaryCount], stackObjects[dictionaryCount];
  948. NSUInteger gotCount = _JKDictionaryGetKeysAndObjects((JKDictionary *)self, dictionaryCount, stackKeys, stackObjects);
  949. NSParameterAssert(gotCount == dictionaryCount);
  950. return([[NSMutableDictionary allocWithZone:zone] initWithObjects:stackObjects forKeys:stackKeys count:gotCount]);
  951. }
  952. @end
  953. #pragma mark -
  954. JK_STATIC_INLINE size_t jk_min(size_t a, size_t b) { return((a < b) ? a : b); }
  955. JK_STATIC_INLINE size_t jk_max(size_t a, size_t b) { return((a > b) ? a : b); }
  956. JK_STATIC_INLINE JKHash calculateHash(JKHash currentHash, unsigned char c) { return(((currentHash << 5) + currentHash) + c); }
  957. static void jk_error(JKParseState *parseState, NSString *format, ...) {
  958. NSCParameterAssert((parseState != NULL) && (format != NULL));
  959. va_list varArgsList;
  960. va_start(varArgsList, format);
  961. NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
  962. va_end(varArgsList);
  963. #if 0
  964. const unsigned char *lineStart = parseState->stringBuffer.bytes.ptr + parseState->lineStartIndex;
  965. const unsigned char *lineEnd = lineStart;
  966. const unsigned char *atCharacterPtr = NULL;
  967. for(atCharacterPtr = lineStart; atCharacterPtr < JK_END_STRING_PTR(parseState); atCharacterPtr++) { lineEnd = atCharacterPtr; if(jk_parse_is_newline(parseState, atCharacterPtr)) { break; } }
  968. NSString *lineString = @"", *carretString = @"";
  969. if(lineStart < JK_END_STRING_PTR(parseState)) {
  970. lineString = [[[NSString alloc] initWithBytes:lineStart length:(lineEnd - lineStart) encoding:NSUTF8StringEncoding] autorelease];
  971. carretString = [NSString stringWithFormat:@"%*.*s^", (int)(parseState->atIndex - parseState->lineStartIndex), (int)(parseState->atIndex - parseState->lineStartIndex), " "];
  972. }
  973. #endif
  974. if(parseState->error == NULL) {
  975. parseState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
  976. [NSDictionary dictionaryWithObjectsAndKeys:
  977. formatString, NSLocalizedDescriptionKey,
  978. [NSNumber numberWithUnsignedLong:parseState->atIndex], @"JKAtIndexKey",
  979. [NSNumber numberWithUnsignedLong:parseState->lineNumber], @"JKLineNumberKey",
  980. //lineString, @"JKErrorLine0Key",
  981. //carretString, @"JKErrorLine1Key",
  982. NULL]];
  983. }
  984. }
  985. #pragma mark -
  986. #pragma mark Buffer and Object Stack management functions
  987. static void jk_managedBuffer_release(JKManagedBuffer *managedBuffer) {
  988. if((managedBuffer->flags & JKManagedBufferMustFree)) {
  989. if(managedBuffer->bytes.ptr != NULL) { free(managedBuffer->bytes.ptr); managedBuffer->bytes.ptr = NULL; }
  990. managedBuffer->flags &= ~JKManagedBufferMustFree;
  991. }
  992. managedBuffer->bytes.ptr = NULL;
  993. managedBuffer->bytes.length = 0UL;
  994. managedBuffer->flags &= ~JKManagedBufferLocationMask;
  995. }
  996. static void jk_managedBuffer_setToStackBuffer(JKManagedBuffer *managedBuffer, unsigned char *ptr, size_t length) {
  997. jk_managedBuffer_release(managedBuffer);
  998. managedBuffer->bytes.ptr = ptr;
  999. managedBuffer->bytes.length = length;
  1000. managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | JKManagedBufferOnStack;
  1001. }
  1002. static unsigned char *jk_managedBuffer_resize(JKManagedBuffer *managedBuffer, size_t newSize) {
  1003. size_t roundedUpNewSize = newSize;
  1004. if(managedBuffer->roundSizeUpToMultipleOf > 0UL) { roundedUpNewSize = newSize + ((managedBuffer->roundSizeUpToMultipleOf - (newSize % managedBuffer->roundSizeUpToMultipleOf)) % managedBuffer->roundSizeUpToMultipleOf); }
  1005. if((roundedUpNewSize != managedBuffer->bytes.length) && (roundedUpNewSize > managedBuffer->bytes.length)) {
  1006. if((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnStack) {
  1007. NSCParameterAssert((managedBuffer->flags & JKManagedBufferMustFree) == 0);
  1008. unsigned char *newBuffer = NULL, *oldBuffer = managedBuffer->bytes.ptr;
  1009. if((newBuffer = (unsigned char *)malloc(roundedUpNewSize)) == NULL) { return(NULL); }
  1010. memcpy(newBuffer, oldBuffer, jk_min(managedBuffer->bytes.length, roundedUpNewSize));
  1011. managedBuffer->flags = (managedBuffer->flags & ~JKManagedBufferLocationMask) | (JKManagedBufferOnHeap | JKManagedBufferMustFree);
  1012. managedBuffer->bytes.ptr = newBuffer;
  1013. managedBuffer->bytes.length = roundedUpNewSize;
  1014. } else {
  1015. NSCParameterAssert(((managedBuffer->flags & JKManagedBufferMustFree) != 0) && ((managedBuffer->flags & JKManagedBufferLocationMask) == JKManagedBufferOnHeap));
  1016. if((managedBuffer->bytes.ptr = (unsigned char *)reallocf(managedBuffer->bytes.ptr, roundedUpNewSize)) == NULL) { return(NULL); }
  1017. managedBuffer->bytes.length = roundedUpNewSize;
  1018. }
  1019. }
  1020. return(managedBuffer->bytes.ptr);
  1021. }
  1022. static void jk_objectStack_release(JKObjectStack *objectStack) {
  1023. NSCParameterAssert(objectStack != NULL);
  1024. NSCParameterAssert(objectStack->index <= objectStack->count);
  1025. size_t atIndex = 0UL;
  1026. for(atIndex = 0UL; atIndex < objectStack->index; atIndex++) {
  1027. if(objectStack->objects[atIndex] != NULL) { CFRelease(objectStack->objects[atIndex]); objectStack->objects[atIndex] = NULL; }
  1028. if(objectStack->keys[atIndex] != NULL) { CFRelease(objectStack->keys[atIndex]); objectStack->keys[atIndex] = NULL; }
  1029. }
  1030. objectStack->index = 0UL;
  1031. if(objectStack->flags & JKObjectStackMustFree) {
  1032. NSCParameterAssert((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap);
  1033. if(objectStack->objects != NULL) { free(objectStack->objects); objectStack->objects = NULL; }
  1034. if(objectStack->keys != NULL) { free(objectStack->keys); objectStack->keys = NULL; }
  1035. if(objectStack->cfHashes != NULL) { free(objectStack->cfHashes); objectStack->cfHashes = NULL; }
  1036. objectStack->flags &= ~JKObjectStackMustFree;
  1037. }
  1038. objectStack->objects = NULL;
  1039. objectStack->keys = NULL;
  1040. objectStack->cfHashes = NULL;
  1041. objectStack->count = 0UL;
  1042. objectStack->flags &= ~JKObjectStackLocationMask;
  1043. }
  1044. static void jk_objectStack_setToStackBuffer(JKObjectStack *objectStack, void **objects, void **keys, CFHashCode *cfHashes, size_t count) {
  1045. NSCParameterAssert((objectStack != NULL) && (objects != NULL) && (keys != NULL) && (cfHashes != NULL) && (count > 0UL));
  1046. jk_objectStack_release(objectStack);
  1047. objectStack->objects = objects;
  1048. objectStack->keys = keys;
  1049. objectStack->cfHashes = cfHashes;
  1050. objectStack->count = count;
  1051. objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | JKObjectStackOnStack;
  1052. #ifndef NS_BLOCK_ASSERTIONS
  1053. size_t idx;
  1054. for(idx = 0UL; idx < objectStack->count; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
  1055. #endif
  1056. }
  1057. static int jk_objectStack_resize(JKObjectStack *objectStack, size_t newCount) {
  1058. size_t roundedUpNewCount = newCount;
  1059. int returnCode = 0;
  1060. void **newObjects = NULL, **newKeys = NULL;
  1061. CFHashCode *newCFHashes = NULL;
  1062. if(objectStack->roundSizeUpToMultipleOf > 0UL) { roundedUpNewCount = newCount + ((objectStack->roundSizeUpToMultipleOf - (newCount % objectStack->roundSizeUpToMultipleOf)) % objectStack->roundSizeUpToMultipleOf); }
  1063. if((roundedUpNewCount != objectStack->count) && (roundedUpNewCount > objectStack->count)) {
  1064. if((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnStack) {
  1065. NSCParameterAssert((objectStack->flags & JKObjectStackMustFree) == 0);
  1066. if((newObjects = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
  1067. memcpy(newObjects, objectStack->objects, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
  1068. if((newKeys = (void ** )calloc(1UL, roundedUpNewCount * sizeof(void * ))) == NULL) { returnCode = 1; goto errorExit; }
  1069. memcpy(newKeys, objectStack->keys, jk_min(objectStack->count, roundedUpNewCount) * sizeof(void *));
  1070. if((newCFHashes = (CFHashCode *)calloc(1UL, roundedUpNewCount * sizeof(CFHashCode))) == NULL) { returnCode = 1; goto errorExit; }
  1071. memcpy(newCFHashes, objectStack->cfHashes, jk_min(objectStack->count, roundedUpNewCount) * sizeof(CFHashCode));
  1072. objectStack->flags = (objectStack->flags & ~JKObjectStackLocationMask) | (JKObjectStackOnHeap | JKObjectStackMustFree);
  1073. objectStack->objects = newObjects; newObjects = NULL;
  1074. objectStack->keys = newKeys; newKeys = NULL;
  1075. objectStack->cfHashes = newCFHashes; newCFHashes = NULL;
  1076. objectStack->count = roundedUpNewCount;
  1077. } else {
  1078. NSCParameterAssert(((objectStack->flags & JKObjectStackMustFree) != 0) && ((objectStack->flags & JKObjectStackLocationMask) == JKObjectStackOnHeap));
  1079. if((newObjects = (void ** )realloc(objectStack->objects, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->objects = newObjects; newObjects = NULL; } else { returnCode = 1; goto errorExit; }
  1080. if((newKeys = (void ** )realloc(objectStack->keys, roundedUpNewCount * sizeof(void * ))) != NULL) { objectStack->keys = newKeys; newKeys = NULL; } else { returnCode = 1; goto errorExit; }
  1081. if((newCFHashes = (CFHashCode *)realloc(objectStack->cfHashes, roundedUpNewCount * sizeof(CFHashCode))) != NULL) { objectStack->cfHashes = newCFHashes; newCFHashes = NULL; } else { returnCode = 1; goto errorExit; }
  1082. #ifndef NS_BLOCK_ASSERTIONS
  1083. size_t idx;
  1084. for(idx = objectStack->count; idx < roundedUpNewCount; idx++) { objectStack->objects[idx] = NULL; objectStack->keys[idx] = NULL; objectStack->cfHashes[idx] = 0UL; }
  1085. #endif
  1086. objectStack->count = roundedUpNewCount;
  1087. }
  1088. }
  1089. errorExit:
  1090. if(newObjects != NULL) { free(newObjects); newObjects = NULL; }
  1091. if(newKeys != NULL) { free(newKeys); newKeys = NULL; }
  1092. if(newCFHashes != NULL) { free(newCFHashes); newCFHashes = NULL; }
  1093. return(returnCode);
  1094. }
  1095. ////////////
  1096. #pragma mark -
  1097. #pragma mark Unicode related functions
  1098. JK_STATIC_INLINE ConversionResult isValidCodePoint(UTF32 *u32CodePoint) {
  1099. ConversionResult result = conversionOK;
  1100. UTF32 ch = *u32CodePoint;
  1101. 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; }
  1102. 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; }
  1103. if(JK_EXPECT_F(ch == 0U)) { result = sourceIllegal; ch = UNI_REPLACEMENT_CHAR; goto finished; }
  1104. finished:
  1105. *u32CodePoint = ch;
  1106. return(result);
  1107. }
  1108. static int isLegalUTF8(const UTF8 *source, size_t length) {
  1109. const UTF8 *srcptr = source + length;
  1110. UTF8 a;
  1111. switch(length) {
  1112. default: return(0); // Everything else falls through when "true"...
  1113. case 4: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
  1114. case 3: if(JK_EXPECT_F(((a = (*--srcptr)) < 0x80) || (a > 0xBF))) { return(0); }
  1115. case 2: if(JK_EXPECT_F( (a = (*--srcptr)) > 0xBF )) { return(0); }
  1116. switch(*source) { // no fall-through in this inner switch
  1117. case 0xE0: if(JK_EXPECT_F(a < 0xA0)) { return(0); } break;
  1118. case 0xED: if(JK_EXPECT_F(a > 0x9F)) { return(0); } break;
  1119. case 0xF0: if(JK_EXPECT_F(a < 0x90)) { return(0); } break;
  1120. case 0xF4: if(JK_EXPECT_F(a > 0x8F)) { return(0); } break;
  1121. default: if(JK_EXPECT_F(a < 0x80)) { return(0); }
  1122. }
  1123. case 1: if(JK_EXPECT_F((JK_EXPECT_T(*source < 0xC2)) && JK_EXPECT_F(*source >= 0x80))) { return(0); }
  1124. }
  1125. if(JK_EXPECT_F(*source > 0xF4)) { return(0); }
  1126. return(1);
  1127. }
  1128. static ConversionResult ConvertSingleCodePointInUTF8(const UTF8 *sourceStart, const UTF8 *sourceEnd, UTF8 const **nextUTF8, UTF32 *convertedUTF32) {
  1129. ConversionResult result = conversionOK;
  1130. const UTF8 *source = sourceStart;
  1131. UTF32 ch = 0UL;
  1132. #if !defined(JK_FAST_TRAILING_BYTES)
  1133. unsigned short extraBytesToRead = trailingBytesForUTF8[*source];
  1134. #else
  1135. unsigned short extraBytesToRead = __builtin_clz(((*source)^0xff) << 25);
  1136. #endif
  1137. if(JK_EXPECT_F((source + extraBytesToRead + 1) > sourceEnd) || JK_EXPECT_F(!isLegalUTF8(source, extraBytesToRead + 1))) {
  1138. source++;
  1139. while((source < sourceEnd) && (((*source) & 0xc0) == 0x80) && ((source - sourceStart) < (extraBytesToRead + 1))) { source++; }
  1140. NSCParameterAssert(source <= sourceEnd);
  1141. result = ((source < sourceEnd) && (((*source) & 0xc0) != 0x80)) ? sourceIllegal : ((sourceStart + extraBytesToRead + 1) > sourceEnd) ? sourceExhausted : sourceIllegal;
  1142. ch = UNI_REPLACEMENT_CHAR;
  1143. goto finished;
  1144. }
  1145. switch(extraBytesToRead) { // The cases all fall through.
  1146. case 5: ch += *source++; ch <<= 6;
  1147. case 4: ch += *source++; ch <<= 6;
  1148. case 3: ch += *source++; ch <<= 6;
  1149. case 2: ch += *source++; ch <<= 6;
  1150. case 1: ch += *source++; ch <<= 6;
  1151. case 0: ch += *source++;
  1152. }
  1153. ch -= offsetsFromUTF8[extraBytesToRead];
  1154. result = isValidCodePoint(&ch);
  1155. finished:
  1156. *nextUTF8 = source;
  1157. *convertedUTF32 = ch;
  1158. return(result);
  1159. }
  1160. static ConversionResult ConvertUTF32toUTF8 (UTF32 u32CodePoint, UTF8 **targetStart, UTF8 *targetEnd) {
  1161. const UTF32 byteMask = 0xBF, byteMark = 0x80;
  1162. ConversionResult result = conversionOK;
  1163. UTF8 *target = *targetStart;
  1164. UTF32 ch = u32CodePoint;
  1165. unsigned short bytesToWrite = 0;
  1166. result = isValidCodePoint(&ch);
  1167. // Figure out how many bytes the result will require. Turn any illegally large UTF32 things (> Plane 17) into replacement chars.
  1168. if(ch < (UTF32)0x80) { bytesToWrite = 1; }
  1169. else if(ch < (UTF32)0x800) { bytesToWrite = 2; }
  1170. else if(ch < (UTF32)0x10000) { bytesToWrite = 3; }
  1171. else if(ch <= UNI_MAX_LEGAL_UTF32) { bytesToWrite = 4; }
  1172. else { bytesToWrite = 3; ch = UNI_REPLACEMENT_CHAR; result = sourceIllegal; }
  1173. target += bytesToWrite;
  1174. if (target > targetEnd) { target -= bytesToWrite; result = targetExhausted; goto finished; }
  1175. switch (bytesToWrite) { // note: everything falls through.
  1176. case 4: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
  1177. case 3: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
  1178. case 2: *--target = (UTF8)((ch | byteMark) & byteMask); ch >>= 6;
  1179. case 1: *--target = (UTF8) (ch | firstByteMark[bytesToWrite]);
  1180. }
  1181. target += bytesToWrite;
  1182. finished:
  1183. *targetStart = target;
  1184. return(result);
  1185. }
  1186. JK_STATIC_INLINE int jk_string_add_unicodeCodePoint(JKParseState *parseState, uint32_t unicodeCodePoint, size_t *tokenBufferIdx, JKHash *stringHash) {
  1187. UTF8 *u8s = &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx];
  1188. ConversionResult result;
  1189. if((result = ConvertUTF32toUTF8(unicodeCodePoint, &u8s, (parseState->token.tokenBuffer.bytes.ptr + parseState->token.tokenBuffer.bytes.length))) != conversionOK) { if(result == targetExhausted) { return(1); } }
  1190. size_t utf8len = u8s - &parseState->token.tokenBuffer.bytes.ptr[*tokenBufferIdx], nextIdx = (*tokenBufferIdx) + utf8len;
  1191. while(*tokenBufferIdx < nextIdx) { *stringHash = calculateHash(*stringHash, parseState->token.tokenBuffer.bytes.ptr[(*tokenBufferIdx)++]); }
  1192. return(0);
  1193. }
  1194. ////////////
  1195. #pragma mark -
  1196. #pragma mark Decoding / parsing / deserializing functions
  1197. static int jk_parse_string(JKParseState *parseState) {
  1198. NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
  1199. const unsigned char *stringStart = JK_AT_STRING_PTR(parseState) + 1;
  1200. const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
  1201. const unsigned char *atStringCharacter = stringStart;
  1202. unsigned char *tokenBuffer = parseState->token.tokenBuffer.bytes.ptr;
  1203. size_t tokenStartIndex = parseState->atIndex;
  1204. size_t tokenBufferIdx = 0UL;
  1205. int onlySimpleString = 1, stringState = JSONStringStateStart;
  1206. uint16_t escapedUnicode1 = 0U, escapedUnicode2 = 0U;
  1207. uint32_t escapedUnicodeCodePoint = 0U;
  1208. JKHash stringHash = JK_HASH_INIT;
  1209. while(1) {
  1210. unsigned long currentChar;
  1211. if(JK_EXPECT_F(atStringCharacter == endOfBuffer)) { /* XXX Add error message */ stringState = JSONStringStateError; goto finishedParsing; }
  1212. if(JK_EXPECT_F((currentChar = *atStringCharacter++) >= 0x80UL)) {
  1213. const unsigned char *nextValidCharacter = NULL;
  1214. UTF32 u32ch = 0U;
  1215. ConversionResult result;
  1216. if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter - 1, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { goto switchToSlowPath; }
  1217. stringHash = calculateHash(stringHash, currentChar);
  1218. while(atStringCharacter < nextValidCharacter) { NSCParameterAssert(JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)); stringHash = calculateHash(stringHash, *atStringCharacter++); }
  1219. continue;
  1220. } else {
  1221. if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; goto finishedParsing; }
  1222. if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) {
  1223. switchToSlowPath:
  1224. onlySimpleString = 0;
  1225. stringState = JSONStringStateParsing;
  1226. tokenBufferIdx = (atStringCharacter - stringStart) - 1L;
  1227. 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; } }
  1228. memcpy(tokenBuffer, stringStart, tokenBufferIdx);
  1229. goto slowMatch;
  1230. }
  1231. if(JK_EXPECT_F(currentChar < 0x20UL)) { jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing; }
  1232. stringHash = calculateHash(stringHash, currentChar);
  1233. }
  1234. }
  1235. slowMatch:
  1236. for(atStringCharacter = (stringStart + ((atStringCharacter - stringStart) - 1L)); (atStringCharacter < endOfBuffer) && (tokenBufferIdx < parseState->token.tokenBuffer.bytes.length); atStringCharacter++) {
  1237. 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; } }
  1238. NSCParameterAssert(tokenBufferIdx < parseState->token.tokenBuffer.bytes.length);
  1239. unsigned long currentChar = (*atStringCharacter), escapedChar;
  1240. if(JK_EXPECT_T(stringState == JSONStringStateParsing)) {
  1241. if(JK_EXPECT_T(currentChar >= 0x20UL)) {
  1242. if(JK_EXPECT_T(currentChar < (unsigned long)0x80)) { // Not a UTF8 sequence
  1243. if(JK_EXPECT_F(currentChar == (unsigned long)'"')) { stringState = JSONStringStateFinished; atStringCharacter++; goto finishedParsing; }
  1244. if(JK_EXPECT_F(currentChar == (unsigned long)'\\')) { stringState = JSONStringStateEscape; continue; }
  1245. stringHash = calculateHash(stringHash, currentChar);
  1246. tokenBuffer[tokenBufferIdx++] = currentChar;
  1247. continue;
  1248. } else { // UTF8 sequence
  1249. const unsigned char *nextValidCharacter = NULL;
  1250. UTF32 u32ch = 0U;
  1251. ConversionResult result;
  1252. if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(atStringCharacter, endOfBuffer, (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) {
  1253. if((result == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal UTF8 sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
  1254. if(result == sourceExhausted) { jk_error(parseState, @"End of buffer reached while parsing UTF8 in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; }
  1255. 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; }
  1256. atStringCharacter = nextValidCharacter - 1;
  1257. continue;
  1258. } else {
  1259. while(atStringCharacter < nextValidCharacter) { tokenBuffer[tokenBufferIdx++] = *atStringCharacter; stringHash = calculateHash(stringHash, *atStringCharacter++); }
  1260. atStringCharacter--;
  1261. continue;
  1262. }
  1263. }
  1264. } else { // currentChar < 0x20
  1265. jk_error(parseState, @"Invalid character < 0x20 found in string: 0x%2.2x.", currentChar); stringState = JSONStringStateError; goto finishedParsing;
  1266. }
  1267. } else { // stringState != JSONStringStateParsing
  1268. int isSurrogate = 1;
  1269. switch(stringState) {
  1270. case JSONStringStateEscape:
  1271. switch(currentChar) {
  1272. case 'u': escapedUnicode1 = 0U; escapedUnicode2 = 0U; escapedUnicodeCodePoint = 0U; stringState = JSONStringStateEscapedUnicode1; break;
  1273. case 'b': escapedChar = '\b'; goto parsedEscapedChar;
  1274. case 'f': escapedChar = '\f'; goto parsedEscapedChar;
  1275. case 'n': escapedChar = '\n'; goto parsedEscapedChar;
  1276. case 'r': escapedChar = '\r'; goto parsedEscapedChar;
  1277. case 't': escapedChar = '\t'; goto parsedEscapedChar;
  1278. case '\\': escapedChar = '\\'; goto parsedEscapedChar;
  1279. case '/': escapedChar = '/'; goto parsedEscapedChar;
  1280. case '"': escapedChar = '"'; goto parsedEscapedChar;
  1281. parsedEscapedChar:
  1282. stringState = JSONStringStateParsing;
  1283. stringHash = calculateHash(stringHash, escapedChar);
  1284. tokenBuffer[tokenBufferIdx++] = escapedChar;
  1285. break;
  1286. default: jk_error(parseState, @"Invalid escape sequence found in \"\" string."); stringState = JSONStringStateError; goto finishedParsing; break;
  1287. }
  1288. break;
  1289. case JSONStringStateEscapedUnicode1:
  1290. case JSONStringStateEscapedUnicode2:
  1291. case JSONStringStateEscapedUnicode3:
  1292. case JSONStringStateEscapedUnicode4: isSurrogate = 0;
  1293. case JSONStringStateEscapedUnicodeSurrogate1:
  1294. case JSONStringStateEscapedUnicodeSurrogate2:
  1295. case JSONStringStateEscapedUnicodeSurrogate3:
  1296. case JSONStringStateEscapedUnicodeSurrogate4:
  1297. {
  1298. uint16_t hexValue = 0U;
  1299. switch(currentChar) {
  1300. case '0' ... '9': hexValue = currentChar - '0'; goto parsedHex;
  1301. case 'a' ... 'f': hexValue = (currentChar - 'a') + 10U; goto parsedHex;
  1302. case 'A' ... 'F': hexValue = (currentChar - 'A') + 10U; goto parsedHex;
  1303. parsedHex:
  1304. if(!isSurrogate) { escapedUnicode1 = (escapedUnicode1 << 4) | hexValue; } else { escapedUnicode2 = (escapedUnicode2 << 4) | hexValue; }
  1305. if(stringState == JSONStringStateEscapedUnicode4) {
  1306. if(((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xE000U))) {
  1307. if((escapedUnicode1 >= 0xD800U) && (escapedUnicode1 < 0xDC00U)) { stringState = JSONStringStateEscapedNeedEscapeForSurrogate; }
  1308. else if((escapedUnicode1 >= 0xDC00U) && (escapedUnicode1 < 0xE000U)) {
  1309. if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
  1310. else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
  1311. }
  1312. }
  1313. else { escapedUnicodeCodePoint = escapedUnicode1; }
  1314. }
  1315. if(stringState == JSONStringStateEscapedUnicodeSurrogate4) {
  1316. if((escapedUnicode2 < 0xdc00) || (escapedUnicode2 > 0xdfff)) {
  1317. if((parseState->parseOptionFlags & JKParseOptionLooseUnicode)) { escapedUnicodeCodePoint = UNI_REPLACEMENT_CHAR; }
  1318. else { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
  1319. }
  1320. else { escapedUnicodeCodePoint = ((escapedUnicode1 - 0xd800) * 0x400) + (escapedUnicode2 - 0xdc00) + 0x10000; }
  1321. }
  1322. if((stringState == JSONStringStateEscapedUnicode4) || (stringState == JSONStringStateEscapedUnicodeSurrogate4)) {
  1323. if((isValidCodePoint(&escapedUnicodeCodePoint) == sourceIllegal) && ((parseState->parseOptionFlags & JKParseOptionLooseUnicode) == 0)) { jk_error(parseState, @"Illegal \\u Unicode escape sequence."); stringState = JSONStringStateError; goto finishedParsing; }
  1324. stringState = JSONStringStateParsing;
  1325. 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; }
  1326. }
  1327. else if((stringState >= JSONStringStateEscapedUnicode1) && (stringState <= JSONStringStateEscapedUnicodeSurrogate4)) { stringState++; }
  1328. break;
  1329. 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;
  1330. }
  1331. }
  1332. break;
  1333. case JSONStringStateEscapedNeedEscapeForSurrogate:
  1334. if(currentChar == '\\') { stringState = JSONStringStateEscapedNeedEscapedUForSurrogate; }
  1335. else {
  1336. 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; }
  1337. 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; } }
  1338. }
  1339. break;
  1340. case JSONStringStateEscapedNeedEscapedUForSurrogate:
  1341. if(currentChar == 'u') { stringState = JSONStringStateEscapedUnicodeSurrogate1; }
  1342. else {
  1343. 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; }
  1344. 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; } }
  1345. }
  1346. break;
  1347. default: jk_error(parseState, @"Internal error: Unknown stringState. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); stringState = JSONStringStateError; goto finishedParsing; break;
  1348. }
  1349. }
  1350. }
  1351. finishedParsing:
  1352. if(JK_EXPECT_T(stringState == JSONStringStateFinished)) {
  1353. NSCParameterAssert((parseState->stringBuffer.bytes.ptr + tokenStartIndex) < atStringCharacter);
  1354. parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + tokenStartIndex;
  1355. parseState->token.tokenPtrRange.length = (atStringCharacter - parseState->token.tokenPtrRange.ptr);
  1356. if(JK_EXPECT_T(onlySimpleString)) {
  1357. NSCParameterAssert(((parseState->token.tokenPtrRange.ptr + 1) < endOfBuffer) && (parseState->token.tokenPtrRange.length >= 2UL) && (((parseState->token.tokenPtrRange.ptr + 1) + (parseState->token.tokenPtrRange.length - 2)) < endOfBuffer));
  1358. parseState->token.value.ptrRange.ptr = parseState->token.tokenPtrRange.ptr + 1;
  1359. parseState->token.value.ptrRange.length = parseState->token.tokenPtrRange.length - 2UL;
  1360. } else {
  1361. parseState->token.value.ptrRange.ptr = parseState->token.tokenBuffer.bytes.ptr;
  1362. parseState->token.value.ptrRange.length = tokenBufferIdx;
  1363. }
  1364. parseState->token.value.hash = stringHash;
  1365. parseState->token.value.type = JKValueTypeString;
  1366. parseState->atIndex = (atStringCharacter - parseState->stringBuffer.bytes.ptr);
  1367. }
  1368. if(JK_EXPECT_F(stringState != JSONStringStateFinished)) { jk_error(parseState, @"Invalid string."); }
  1369. return(JK_EXPECT_T(stringState == JSONStringStateFinished) ? 0 : 1);
  1370. }
  1371. static int jk_parse_number(JKParseState *parseState) {
  1372. NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
  1373. const unsigned char *numberStart = JK_AT_STRING_PTR(parseState);
  1374. const unsigned char *endOfBuffer = JK_END_STRING_PTR(parseState);
  1375. const unsigned char *atNumberCharacter = NULL;
  1376. int numberState = JSONNumberStateWholeNumberStart, isFloatingPoint = 0, isNegative = 0, backup = 0;
  1377. size_t startingIndex = parseState->atIndex;
  1378. for(atNumberCharacter = numberStart; (JK_EXPECT_T(atNumberCharacter < endOfBuffer)) && (JK_EXPECT_T(!(JK_EXPECT_F(numberState == JSONNumberStateFinished) || JK_EXPECT_F(numberState == JSONNumberStateError)))); atNumberCharacter++) {
  1379. unsigned long currentChar = (unsigned long)(*atNumberCharacter), lowerCaseCC = currentChar | 0x20UL;
  1380. switch(numberState) {
  1381. case JSONNumberStateWholeNumberStart: if (currentChar == '-') { numberState = JSONNumberStateWholeNumberMinus; isNegative = 1; break; }
  1382. case JSONNumberStateWholeNumberMinus: if (currentChar == '0') { numberState = JSONNumberStateWholeNumberZero; break; }
  1383. else if( (currentChar >= '1') && (currentChar <= '9')) { numberState = JSONNumberStateWholeNumber; break; }
  1384. else { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
  1385. case JSONNumberStateExponentStart: if( (currentChar == '+') || (currentChar == '-')) { numberState = JSONNumberStateExponentPlusMinus; break; }
  1386. case JSONNumberStateFractionalNumberStart:
  1387. case JSONNumberStateExponentPlusMinus:if(!((currentChar >= '0') && (currentChar <= '9'))) { /* XXX Add error message */ numberState = JSONNumberStateError; break; }
  1388. else { if(numberState == JSONNumberStateFractionalNumberStart) { numberState = JSONNumberStateFractionalNumber; }
  1389. else { numberState = JSONNumberStateExponent; } break; }
  1390. case JSONNumberStateWholeNumberZero:
  1391. case JSONNumberStateWholeNumber: if (currentChar == '.') { numberState = JSONNumberStateFractionalNumberStart; isFloatingPoint = 1; break; }
  1392. case JSONNumberStateFractionalNumber: if (lowerCaseCC == 'e') { numberState = JSONNumberStateExponentStart; isFloatingPoint = 1; break; }
  1393. case JSONNumberStateExponent: if(!((currentChar >= '0') && (currentChar <= '9')) || (numberState == JSONNumberStateWholeNumberZero)) { numberState = JSONNumberStateFinished; backup = 1; break; }
  1394. break;
  1395. default: /* XXX Add error message */ numberState = JSONNumberStateError; break;
  1396. }
  1397. }
  1398. parseState->token.tokenPtrRange.ptr = parseState->stringBuffer.bytes.ptr + startingIndex;
  1399. parseState->token.tokenPtrRange.length = (atNumberCharacter - parseState->token.tokenPtrRange.ptr) - backup;
  1400. parseState->atIndex = (parseState->token.tokenPtrRange.ptr + parseState->token.tokenPtrRange.length) - parseState->stringBuffer.bytes.ptr;
  1401. if(JK_EXPECT_T(numberState == JSONNumberStateFinished)) {
  1402. unsigned char numberTempBuf[parseState->token.tokenPtrRange.length + 4UL];
  1403. unsigned char *endOfNumber = NULL;
  1404. memcpy(numberTempBuf, parseState->token.tokenPtrRange.ptr, parseState->token.tokenPtrRange.length);
  1405. numberTempBuf[parseState->token.tokenPtrRange.length] = 0;
  1406. errno = 0;
  1407. // Treat "-0" as a floating point number, which is capable of representing negative zeros.
  1408. if(JK_EXPECT_F(parseState->token.tokenPtrRange.length == 2UL) && JK_EXPECT_F(numberTempBuf[1] == '0') && JK_EXPECT_F(isNegative)) { isFloatingPoint = 1; }
  1409. if(isFloatingPoint) {
  1410. 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).
  1411. parseState->token.value.type = JKValueTypeDouble;
  1412. parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.doubleValue;
  1413. parseState->token.value.ptrRange.length = sizeof(double);
  1414. parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type);
  1415. } else {
  1416. if(isNegative) {
  1417. parseState->token.value.number.longLongValue = strtoll((const char *)numberTempBuf, (char **)&endOfNumber, 10);
  1418. parseState->token.value.type = JKValueTypeLongLong;
  1419. parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.longLongValue;
  1420. parseState->token.value.ptrRange.length = sizeof(long long);
  1421. parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.longLongValue;
  1422. } else {
  1423. parseState->token.value.number.unsignedLongLongValue = strtoull((const char *)numberTempBuf, (char **)&endOfNumber, 10);
  1424. parseState->token.value.type = JKValueTypeUnsignedLongLong;
  1425. parseState->token.value.ptrRange.ptr = (const unsigned char *)&parseState->token.value.number.unsignedLongLongValue;
  1426. parseState->token.value.ptrRange.length = sizeof(unsigned long long);
  1427. parseState->token.value.hash = (JK_HASH_INIT + parseState->token.value.type) + (JKHash)parseState->token.value.number.unsignedLongLongValue;
  1428. }
  1429. }
  1430. if(JK_EXPECT_F(errno != 0)) {
  1431. numberState = JSONNumberStateError;
  1432. if(errno == ERANGE) {
  1433. switch(parseState->token.value.type) {
  1434. 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.
  1435. case JKValueTypeLongLong: jk_error(parseState, @"The value '%s' exceeded the minimum value that could be represented: %lld.", numberTempBuf, parseState->token.value.number.longLongValue); break;
  1436. case JKValueTypeUnsignedLongLong: jk_error(parseState, @"The value '%s' exceeded the maximum value that could be represented: %llu.", numberTempBuf, parseState->token.value.number.unsignedLongLongValue); break;
  1437. default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
  1438. }
  1439. }
  1440. }
  1441. 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."); }
  1442. size_t hashIndex = 0UL;
  1443. 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]); }
  1444. }
  1445. if(JK_EXPECT_F(numberState != JSONNumberStateFinished)) { jk_error(parseState, @"Invalid number."); }
  1446. return(JK_EXPECT_T((numberState == JSONNumberStateFinished)) ? 0 : 1);
  1447. }
  1448. JK_STATIC_INLINE void jk_set_parsed_token(JKParseState *parseState, const unsigned char *ptr, size_t length, JKTokenType type, size_t advanceBy) {
  1449. parseState->token.tokenPtrRange.ptr = ptr;
  1450. parseState->token.tokenPtrRange.length = length;
  1451. parseState->token.type = type;
  1452. parseState->atIndex += advanceBy;
  1453. }
  1454. static size_t jk_parse_is_newline(JKParseState *parseState, const unsigned char *atCharacterPtr) {
  1455. NSCParameterAssert((parseState != NULL) && (atCharacterPtr != NULL) && (atCharacterPtr >= parseState->stringBuffer.bytes.ptr) && (atCharacterPtr < JK_END_STRING_PTR(parseState)));
  1456. const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
  1457. if(JK_EXPECT_F(atCharacterPtr >= endOfStringPtr)) { return(0UL); }
  1458. if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\n')) { return(1UL); }
  1459. if(JK_EXPECT_F((*(atCharacterPtr + 0)) == '\r')) { if((JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr)) && ((*(atCharacterPtr + 1)) == '\n')) { return(2UL); } return(1UL); }
  1460. if(parseState->parseOptionFlags & JKParseOptionUnicodeNewlines) {
  1461. if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xc2)) && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x85))) { return(2UL); }
  1462. if((JK_EXPECT_F((*(atCharacterPtr + 0)) == 0xe2)) && (((atCharacterPtr + 2) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == 0x80) && (((*(atCharacterPtr + 2)) == 0xa8) || ((*(atCharacterPtr + 2)) == 0xa9)))) { return(3UL); }
  1463. }
  1464. return(0UL);
  1465. }
  1466. JK_STATIC_INLINE int jk_parse_skip_newline(JKParseState *parseState) {
  1467. size_t newlineAdvanceAtIndex = 0UL;
  1468. 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); }
  1469. return(0);
  1470. }
  1471. JK_STATIC_INLINE void jk_parse_skip_whitespace(JKParseState *parseState) {
  1472. #ifndef __clang_analyzer__
  1473. NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
  1474. const unsigned char *atCharacterPtr = NULL;
  1475. const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
  1476. for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
  1477. if(((*(atCharacterPtr + 0)) == ' ') || ((*(atCharacterPtr + 0)) == '\t')) { continue; }
  1478. if(jk_parse_skip_newline(parseState)) { continue; }
  1479. if(parseState->parseOptionFlags & JKParseOptionComments) {
  1480. if((JK_EXPECT_F((*(atCharacterPtr + 0)) == '/')) && (JK_EXPECT_T((atCharacterPtr + 1) < endOfStringPtr))) {
  1481. if((*(atCharacterPtr + 1)) == '/') {
  1482. parseState->atIndex++;
  1483. 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; } }
  1484. continue;
  1485. }
  1486. if((*(atCharacterPtr + 1)) == '*') {
  1487. parseState->atIndex++;
  1488. for(atCharacterPtr = JK_AT_STRING_PTR(parseState); (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr)); parseState->atIndex++) {
  1489. if(jk_parse_skip_newline(parseState)) { continue; }
  1490. if(((*(atCharacterPtr + 0)) == '*') && (((atCharacterPtr + 1) < endOfStringPtr) && ((*(atCharacterPtr + 1)) == '/'))) { parseState->atIndex++; break; }
  1491. }
  1492. continue;
  1493. }
  1494. }
  1495. }
  1496. break;
  1497. }
  1498. #endif
  1499. }
  1500. static int jk_parse_next_token(JKParseState *parseState) {
  1501. NSCParameterAssert((parseState != NULL) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
  1502. const unsigned char *atCharacterPtr = NULL;
  1503. const unsigned char *endOfStringPtr = JK_END_STRING_PTR(parseState);
  1504. unsigned char currentCharacter = 0U;
  1505. int stopParsing = 0;
  1506. parseState->prev_atIndex = parseState->atIndex;
  1507. parseState->prev_lineNumber = parseState->lineNumber;
  1508. parseState->prev_lineStartIndex = parseState->lineStartIndex;
  1509. jk_parse_skip_whitespace(parseState);
  1510. if((JK_AT_STRING_PTR(parseState) == endOfStringPtr)) { stopParsing = 1; }
  1511. if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((atCharacterPtr = JK_AT_STRING_PTR(parseState)) < endOfStringPtr))) {
  1512. currentCharacter = *atCharacterPtr;
  1513. 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); } }
  1514. else if(JK_EXPECT_T(currentCharacter == ':')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeSeparator, 1UL); }
  1515. else if(JK_EXPECT_T(currentCharacter == ',')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeComma, 1UL); }
  1516. 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); } }
  1517. else if(JK_EXPECT_T(currentCharacter == '{')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectBegin, 1UL); }
  1518. else if(JK_EXPECT_T(currentCharacter == '}')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeObjectEnd, 1UL); }
  1519. else if(JK_EXPECT_T(currentCharacter == '[')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayBegin, 1UL); }
  1520. else if(JK_EXPECT_T(currentCharacter == ']')) { jk_set_parsed_token(parseState, atCharacterPtr, 1UL, JKTokenTypeArrayEnd, 1UL); }
  1521. 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); } }
  1522. 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); } }
  1523. 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); } }
  1524. else { stopParsing = 1; /* XXX Add error message */ }
  1525. }
  1526. if(JK_EXPECT_F(stopParsing)) { jk_error(parseState, @"Unexpected token, wanted '{', '}', '[', ']', ',', ':', 'true', 'false', 'null', '\"STRING\"', 'NUMBER'."); }
  1527. return(stopParsing);
  1528. }
  1529. static void jk_error_parse_accept_or3(JKParseState *parseState, int state, NSString *or1String, NSString *or2String, NSString *or3String) {
  1530. NSString *acceptStrings[16];
  1531. int acceptIdx = 0;
  1532. if(state & JKParseAcceptValue) { acceptStrings[acceptIdx++] = or1String; }
  1533. if(state & JKParseAcceptComma) { acceptStrings[acceptIdx++] = or2String; }
  1534. if(state & JKParseAcceptEnd) { acceptStrings[acceptIdx++] = or3String; }
  1535. 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); }
  1536. 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); }
  1537. 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); }
  1538. }
  1539. static void *jk_parse_array(JKParseState *parseState) {
  1540. size_t startingObjectIndex = parseState->objectStack.index;
  1541. int arrayState = JKParseAcceptValueOrEnd, stopParsing = 0;
  1542. void *parsedArray = NULL;
  1543. while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
  1544. 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; } }
  1545. if(JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)) {
  1546. void *object = NULL;
  1547. #ifndef NS_BLOCK_ASSERTIONS
  1548. parseState->objectStack.objects[parseState->objectStack.index] = NULL;
  1549. parseState->objectStack.keys [parseState->objectStack.index] = NULL;
  1550. #endif
  1551. switch(parseState->token.type) {
  1552. case JKTokenTypeNumber:
  1553. case JKTokenTypeString:
  1554. case JKTokenTypeTrue:
  1555. case JKTokenTypeFalse:
  1556. case JKTokenTypeNull:
  1557. case JKTokenTypeArrayBegin:
  1558. case JKTokenTypeObjectBegin:
  1559. if(JK_EXPECT_F((arrayState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
  1560. 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; }
  1561. break;
  1562. 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;
  1563. case JKTokenTypeComma: if(JK_EXPECT_T(arrayState & JKParseAcceptComma)) { arrayState = JKParseAcceptValue; } else { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected ','."); stopParsing = 1; } break;
  1564. default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, arrayState, @"a value", @"a comma", @"a ']'"); stopParsing = 1; break;
  1565. }
  1566. }
  1567. }
  1568. 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; } } }
  1569. #if !defined(NS_BLOCK_ASSERTIONS)
  1570. else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
  1571. #endif
  1572. parseState->objectStack.index = startingObjectIndex;
  1573. return(parsedArray);
  1574. }
  1575. static void *jk_create_dictionary(JKParseState *parseState, size_t startingObjectIndex) {
  1576. void *parsedDictionary = NULL;
  1577. parseState->objectStack.index--;
  1578. parsedDictionary = _JKDictionaryCreate((id *)&parseState->objectStack.keys[startingObjectIndex], (NSUInteger *)&parseState->objectStack.cfHashes[startingObjectIndex], (id *)&parseState->objectStack.objects[startingObjectIndex], (parseState->objectStack.index - startingObjectIndex), parseState->mutableCollections);
  1579. return(parsedDictionary);
  1580. }
  1581. static void *jk_parse_dictionary(JKParseState *parseState) {
  1582. size_t startingObjectIndex = parseState->objectStack.index;
  1583. int dictState = JKParseAcceptValueOrEnd, stopParsing = 0;
  1584. void *parsedDictionary = NULL;
  1585. while(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length)))) {
  1586. 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; } }
  1587. size_t objectStackIndex = parseState->objectStack.index++;
  1588. parseState->objectStack.keys[objectStackIndex] = NULL;
  1589. parseState->objectStack.objects[objectStackIndex] = NULL;
  1590. void *key = NULL, *object = NULL;
  1591. if(JK_EXPECT_T((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0)))) {
  1592. switch(parseState->token.type) {
  1593. case JKTokenTypeString:
  1594. if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected string."); stopParsing = 1; break; }
  1595. if(JK_EXPECT_F((key = jk_object_for_token(parseState)) == NULL)) { jk_error(parseState, @"Internal error: Key == NULL."); stopParsing = 1; break; }
  1596. else {
  1597. parseState->objectStack.keys[objectStackIndex] = key;
  1598. 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; }
  1599. else { parseState->objectStack.cfHashes[objectStackIndex] = CFHash(key); }
  1600. }
  1601. break;
  1602. 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;
  1603. 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;
  1604. default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a \"STRING\"", @"a comma", @"a '}'"); stopParsing = 1; break;
  1605. }
  1606. }
  1607. if(JK_EXPECT_T(stopParsing == 0)) {
  1608. 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; } }
  1609. }
  1610. if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
  1611. switch(parseState->token.type) {
  1612. case JKTokenTypeNumber:
  1613. case JKTokenTypeString:
  1614. case JKTokenTypeTrue:
  1615. case JKTokenTypeFalse:
  1616. case JKTokenTypeNull:
  1617. case JKTokenTypeArrayBegin:
  1618. case JKTokenTypeObjectBegin:
  1619. if(JK_EXPECT_F((dictState & JKParseAcceptValue) == 0)) { parseState->errorIsPrev = 1; jk_error(parseState, @"Unexpected value."); stopParsing = 1; break; }
  1620. 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; }
  1621. break;
  1622. default: parseState->errorIsPrev = 1; jk_error_parse_accept_or3(parseState, dictState, @"a value", @"a comma", @"a '}'"); stopParsing = 1; break;
  1623. }
  1624. }
  1625. }
  1626. 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; } } }
  1627. #if !defined(NS_BLOCK_ASSERTIONS)
  1628. else { size_t idx = 0UL; for(idx = startingObjectIndex; idx < parseState->objectStack.index; idx++) { parseState->objectStack.objects[idx] = NULL; parseState->objectStack.keys[idx] = NULL; } }
  1629. #endif
  1630. parseState->objectStack.index = startingObjectIndex;
  1631. return(parsedDictionary);
  1632. }
  1633. static id json_parse_it(JKParseState *parseState) {
  1634. id parsedObject = NULL;
  1635. int stopParsing = 0;
  1636. while((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T(parseState->atIndex < parseState->stringBuffer.bytes.length))) {
  1637. if((JK_EXPECT_T(stopParsing == 0)) && (JK_EXPECT_T((stopParsing = jk_parse_next_token(parseState)) == 0))) {
  1638. switch(parseState->token.type) {
  1639. case JKTokenTypeArrayBegin:
  1640. case JKTokenTypeObjectBegin: parsedObject = [(id)jk_object_for_token(parseState) autorelease]; stopParsing = 1; break;
  1641. default: jk_error(parseState, @"Expected either '[' or '{'."); stopParsing = 1; break;
  1642. }
  1643. }
  1644. }
  1645. NSCParameterAssert((parseState->objectStack.index == 0) && (JK_AT_STRING_PTR(parseState) <= JK_END_STRING_PTR(parseState)));
  1646. if((parsedObject == NULL) && (JK_AT_STRING_PTR(parseState) == JK_END_STRING_PTR(parseState))) { jk_error(parseState, @"Reached the end of the buffer."); }
  1647. if(parsedObject == NULL) { jk_error(parseState, @"Unable to parse JSON."); }
  1648. if((parsedObject != NULL) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
  1649. jk_parse_skip_whitespace(parseState);
  1650. if((parsedObject != NULL) && ((parseState->parseOptionFlags & JKParseOptionPermitTextAfterValidJSON) == 0) && (JK_AT_STRING_PTR(parseState) < JK_END_STRING_PTR(parseState))) {
  1651. jk_error(parseState, @"A valid JSON object was parsed but there were additional non-white-space characters remaining.");
  1652. parsedObject = NULL;
  1653. }
  1654. }
  1655. return(parsedObject);
  1656. }
  1657. ////////////
  1658. #pragma mark -
  1659. #pragma mark Object cache
  1660. // 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.
  1661. // NOTE: A LFSR *MUST* be initialized to a non-zero value and must always have a non-zero value.
  1662. JK_STATIC_INLINE void jk_cache_age(JKParseState *parseState) {
  1663. NSCParameterAssert((parseState != NULL) && (parseState->cache.prng_lfsr != 0U));
  1664. parseState->cache.prng_lfsr = (parseState->cache.prng_lfsr >> 1) ^ ((0U - (parseState->cache.prng_lfsr & 1U)) & 0x80200003U);
  1665. parseState->cache.age[parseState->cache.prng_lfsr & (parseState->cache.count - 1UL)] >>= 1;
  1666. }
  1667. // The object cache is nothing more than a hash table with open addressing collision resolution that is bounded by JK_CACHE_PROBES attempts.
  1668. //
  1669. // 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].
  1670. //
  1671. // 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.
  1672. // 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).
  1673. // The reason for this is it allows us to perform saturated adds and subtractions and is branchless.
  1674. // The primitive C type MUST be unsigned. It is currently a "char", which allows (at a minimum and in practice) 8 bits.
  1675. //
  1676. // A "useable bucket" is a bucket that is not in use (never populated), or has an age == 0.
  1677. //
  1678. // When an item is found in the cache, it's age is incremented.
  1679. // If a useable bucket hasn't been found, the current item (bucket) is aged along with two random items.
  1680. //
  1681. // If a value is not found in the cache, and no useable bucket has been found, that value is not added to the cache.
  1682. static void *jk_cachedObjects(JKParseState *parseState) {
  1683. unsigned long bucket = parseState->token.value.hash & (parseState->cache.count - 1UL), setBucket = 0UL, useableBucket = 0UL, x = 0UL;
  1684. void *parsedAtom = NULL;
  1685. if(JK_EXPECT_F(parseState->token.value.ptrRange.length == 0UL) && JK_EXPECT_T(parseState->token.value.type == JKValueTypeString)) { return(@""); }
  1686. for(x = 0UL; x < JK_CACHE_PROBES; x++) {
  1687. if(JK_EXPECT_F(parseState->cache.items[bucket].object == NULL)) { setBucket = 1UL; useableBucket = bucket; break; }
  1688. 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))) {
  1689. parseState->cache.age[bucket] = (parseState->cache.age[bucket] << 1) | 1U;
  1690. parseState->token.value.cacheItem = &parseState->cache.items[bucket];
  1691. NSCParameterAssert(parseState->cache.items[bucket].object != NULL);
  1692. return((void *)CFRetain(parseState->cache.items[bucket].object));
  1693. } else {
  1694. if(JK_EXPECT_F(setBucket == 0UL) && JK_EXPECT_F(parseState->cache.age[bucket] == 0U)) { setBucket = 1UL; useableBucket = bucket; }
  1695. if(JK_EXPECT_F(setBucket == 0UL)) { parseState->cache.age[bucket] >>= 1; jk_cache_age(parseState); jk_cache_age(parseState); }
  1696. // 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.
  1697. // 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.
  1698. 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);
  1699. }
  1700. }
  1701. switch(parseState->token.value.type) {
  1702. case JKValueTypeString: parsedAtom = (void *)CFStringCreateWithBytes(NULL, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length, kCFStringEncodingUTF8, 0); break;
  1703. case JKValueTypeLongLong: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.longLongValue); break;
  1704. case JKValueTypeUnsignedLongLong:
  1705. if(parseState->token.value.number.unsignedLongLongValue <= LLONG_MAX) { parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberLongLongType, &parseState->token.value.number.unsignedLongLongValue); }
  1706. else { parsedAtom = (void *)parseState->objCImpCache.NSNumberInitWithUnsignedLongLong(parseState->objCImpCache.NSNumberAlloc(parseState->objCImpCache.NSNumberClass, @selector(alloc)), @selector(initWithUnsignedLongLong:), parseState->token.value.number.unsignedLongLongValue); }
  1707. break;
  1708. case JKValueTypeDouble: parsedAtom = (void *)CFNumberCreate(NULL, kCFNumberDoubleType, &parseState->token.value.number.doubleValue); break;
  1709. default: jk_error(parseState, @"Internal error: Unknown token value type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
  1710. }
  1711. if(JK_EXPECT_T(setBucket) && (JK_EXPECT_T(parsedAtom != NULL))) {
  1712. bucket = useableBucket;
  1713. if(JK_EXPECT_T((parseState->cache.items[bucket].object != NULL))) { CFRelease(parseState->cache.items[bucket].object); parseState->cache.items[bucket].object = NULL; }
  1714. if(JK_EXPECT_T((parseState->cache.items[bucket].bytes = (unsigned char *)reallocf(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.length)) != NULL)) {
  1715. memcpy(parseState->cache.items[bucket].bytes, parseState->token.value.ptrRange.ptr, parseState->token.value.ptrRange.length);
  1716. parseState->cache.items[bucket].object = (void *)CFRetain(parsedAtom);
  1717. parseState->cache.items[bucket].hash = parseState->token.value.hash;
  1718. parseState->cache.items[bucket].cfHash = 0UL;
  1719. parseState->cache.items[bucket].size = parseState->token.value.ptrRange.length;
  1720. parseState->cache.items[bucket].type = parseState->token.value.type;
  1721. parseState->token.value.cacheItem = &parseState->cache.items[bucket];
  1722. parseState->cache.age[bucket] = JK_INIT_CACHE_AGE;
  1723. } else { // The realloc failed, so clear the appropriate fields.
  1724. parseState->cache.items[bucket].hash = 0UL;
  1725. parseState->cache.items[bucket].cfHash = 0UL;
  1726. parseState->cache.items[bucket].size = 0UL;
  1727. parseState->cache.items[bucket].type = 0UL;
  1728. }
  1729. }
  1730. return(parsedAtom);
  1731. }
  1732. static void *jk_object_for_token(JKParseState *parseState) {
  1733. void *parsedAtom = NULL;
  1734. parseState->token.value.cacheItem = NULL;
  1735. switch(parseState->token.type) {
  1736. case JKTokenTypeString: parsedAtom = jk_cachedObjects(parseState); break;
  1737. case JKTokenTypeNumber: parsedAtom = jk_cachedObjects(parseState); break;
  1738. case JKTokenTypeObjectBegin: parsedAtom = jk_parse_dictionary(parseState); break;
  1739. case JKTokenTypeArrayBegin: parsedAtom = jk_parse_array(parseState); break;
  1740. case JKTokenTypeTrue: parsedAtom = (void *)kCFBooleanTrue; break;
  1741. case JKTokenTypeFalse: parsedAtom = (void *)kCFBooleanFalse; break;
  1742. case JKTokenTypeNull: parsedAtom = (void *)kCFNull; break;
  1743. default: jk_error(parseState, @"Internal error: Unknown token type. %@ line #%ld", [NSString stringWithUTF8String:__FILE__], (long)__LINE__); break;
  1744. }
  1745. return(parsedAtom);
  1746. }
  1747. #pragma mark -
  1748. @implementation JSONDecoder
  1749. static Class _jk_NSNumberClass;
  1750. static NSNumberAllocImp _jk_NSNumberAllocImp;
  1751. static NSNumberInitWithUnsignedLongLongImp _jk_NSNumberInitWithUnsignedLongLongImp;
  1752. + (void)load
  1753. {
  1754. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Though technically not required, the run time environment at +load time may be less than ideal.
  1755. _jk_NSNumberClass = [NSNumber class];
  1756. _jk_NSNumberAllocImp = (NSNumberAllocImp)[NSNumber methodForSelector:@selector(alloc)];
  1757. // Hacktacular. Need to do it this way due to the nature of class clusters.
  1758. id temp_NSNumber = [NSNumber alloc];
  1759. _jk_NSNumberInitWithUnsignedLongLongImp = (NSNumberInitWithUnsignedLongLongImp)[temp_NSNumber methodForSelector:@selector(initWithUnsignedLongLong:)];
  1760. [[temp_NSNumber init] release];
  1761. temp_NSNumber = NULL;
  1762. [pool release]; pool = NULL;
  1763. }
  1764. + (id)decoder
  1765. {
  1766. return([self decoderWithParseOptions:JKParseOptionStrict]);
  1767. }
  1768. + (id)decoderWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  1769. {
  1770. return([[[self alloc] initWithParseOptions:parseOptionFlags] autorelease]);
  1771. }
  1772. - (id)init
  1773. {
  1774. return([self initWithParseOptions:JKParseOptionStrict]);
  1775. }
  1776. - (id)initWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  1777. {
  1778. if((self = [super init]) == NULL) { return(NULL); }
  1779. if(parseOptionFlags & ~JKParseOptionValidFlags) { [self autorelease]; [NSException raise:NSInvalidArgumentException format:@"Invalid parse options."]; }
  1780. if((parseState = (JKParseState *)calloc(1UL, sizeof(JKParseState))) == NULL) { goto errorExit; }
  1781. parseState->parseOptionFlags = parseOptionFlags;
  1782. parseState->token.tokenBuffer.roundSizeUpToMultipleOf = 4096UL;
  1783. parseState->objectStack.roundSizeUpToMultipleOf = 2048UL;
  1784. parseState->objCImpCache.NSNumberClass = _jk_NSNumberClass;
  1785. parseState->objCImpCache.NSNumberAlloc = _jk_NSNumberAllocImp;
  1786. parseState->objCImpCache.NSNumberInitWithUnsignedLongLong = _jk_NSNumberInitWithUnsignedLongLongImp;
  1787. parseState->cache.prng_lfsr = 1U;
  1788. parseState->cache.count = JK_CACHE_SLOTS;
  1789. if((parseState->cache.items = (JKTokenCacheItem *)calloc(1UL, sizeof(JKTokenCacheItem) * parseState->cache.count)) == NULL) { goto errorExit; }
  1790. return(self);
  1791. errorExit:
  1792. if(self) { [self autorelease]; self = NULL; }
  1793. return(NULL);
  1794. }
  1795. // 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.
  1796. static void _JSONDecoderCleanup(JSONDecoder *decoder) {
  1797. if((decoder != NULL) && (decoder->parseState != NULL)) {
  1798. jk_managedBuffer_release(&decoder->parseState->token.tokenBuffer);
  1799. jk_objectStack_release(&decoder->parseState->objectStack);
  1800. [decoder clearCache];
  1801. if(decoder->parseState->cache.items != NULL) { free(decoder->parseState->cache.items); decoder->parseState->cache.items = NULL; }
  1802. free(decoder->parseState); decoder->parseState = NULL;
  1803. }
  1804. }
  1805. - (void)dealloc
  1806. {
  1807. _JSONDecoderCleanup(self);
  1808. [super dealloc];
  1809. }
  1810. - (void)clearCache
  1811. {
  1812. if(JK_EXPECT_T(parseState != NULL)) {
  1813. if(JK_EXPECT_T(parseState->cache.items != NULL)) {
  1814. size_t idx = 0UL;
  1815. for(idx = 0UL; idx < parseState->cache.count; idx++) {
  1816. if(JK_EXPECT_T(parseState->cache.items[idx].object != NULL)) { CFRelease(parseState->cache.items[idx].object); parseState->cache.items[idx].object = NULL; }
  1817. if(JK_EXPECT_T(parseState->cache.items[idx].bytes != NULL)) { free(parseState->cache.items[idx].bytes); parseState->cache.items[idx].bytes = NULL; }
  1818. memset(&parseState->cache.items[idx], 0, sizeof(JKTokenCacheItem));
  1819. parseState->cache.age[idx] = 0U;
  1820. }
  1821. }
  1822. }
  1823. }
  1824. // This needs to be completely rewritten.
  1825. static id _JKParseUTF8String(JKParseState *parseState, BOOL mutableCollections, const unsigned char *string, size_t length, NSError **error) {
  1826. NSCParameterAssert((parseState != NULL) && (string != NULL) && (parseState->cache.prng_lfsr != 0U));
  1827. parseState->stringBuffer.bytes.ptr = string;
  1828. parseState->stringBuffer.bytes.length = length;
  1829. parseState->atIndex = 0UL;
  1830. parseState->lineNumber = 1UL;
  1831. parseState->lineStartIndex = 0UL;
  1832. parseState->prev_atIndex = 0UL;
  1833. parseState->prev_lineNumber = 1UL;
  1834. parseState->prev_lineStartIndex = 0UL;
  1835. parseState->error = NULL;
  1836. parseState->errorIsPrev = 0;
  1837. parseState->mutableCollections = (mutableCollections == NO) ? NO : YES;
  1838. unsigned char stackTokenBuffer[JK_TOKENBUFFER_SIZE] JK_ALIGNED(64);
  1839. jk_managedBuffer_setToStackBuffer(&parseState->token.tokenBuffer, stackTokenBuffer, sizeof(stackTokenBuffer));
  1840. void *stackObjects [JK_STACK_OBJS] JK_ALIGNED(64);
  1841. void *stackKeys [JK_STACK_OBJS] JK_ALIGNED(64);
  1842. CFHashCode stackCFHashes[JK_STACK_OBJS] JK_ALIGNED(64);
  1843. jk_objectStack_setToStackBuffer(&parseState->objectStack, stackObjects, stackKeys, stackCFHashes, JK_STACK_OBJS);
  1844. id parsedJSON = json_parse_it(parseState);
  1845. if((error != NULL) && (parseState->error != NULL)) { *error = parseState->error; }
  1846. jk_managedBuffer_release(&parseState->token.tokenBuffer);
  1847. jk_objectStack_release(&parseState->objectStack);
  1848. parseState->stringBuffer.bytes.ptr = NULL;
  1849. parseState->stringBuffer.bytes.length = 0UL;
  1850. parseState->atIndex = 0UL;
  1851. parseState->lineNumber = 1UL;
  1852. parseState->lineStartIndex = 0UL;
  1853. parseState->prev_atIndex = 0UL;
  1854. parseState->prev_lineNumber = 1UL;
  1855. parseState->prev_lineStartIndex = 0UL;
  1856. parseState->error = NULL;
  1857. parseState->errorIsPrev = 0;
  1858. parseState->mutableCollections = NO;
  1859. return(parsedJSON);
  1860. }
  1861. ////////////
  1862. #pragma mark Deprecated as of v1.4
  1863. ////////////
  1864. // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length: instead.
  1865. - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length
  1866. {
  1867. return([self objectWithUTF8String:string length:length error:NULL]);
  1868. }
  1869. // Deprecated in JSONKit v1.4. Use objectWithUTF8String:length:error: instead.
  1870. - (id)parseUTF8String:(const unsigned char *)string length:(size_t)length error:(NSError **)error
  1871. {
  1872. return([self objectWithUTF8String:string length:length error:error]);
  1873. }
  1874. // Deprecated in JSONKit v1.4. Use objectWithData: instead.
  1875. - (id)parseJSONData:(NSData *)jsonData
  1876. {
  1877. return([self objectWithData:jsonData error:NULL]);
  1878. }
  1879. // Deprecated in JSONKit v1.4. Use objectWithData:error: instead.
  1880. - (id)parseJSONData:(NSData *)jsonData error:(NSError **)error
  1881. {
  1882. return([self objectWithData:jsonData error:error]);
  1883. }
  1884. ////////////
  1885. #pragma mark Methods that return immutable collection objects
  1886. ////////////
  1887. - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
  1888. {
  1889. return([self objectWithUTF8String:string length:length error:NULL]);
  1890. }
  1891. - (id)objectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
  1892. {
  1893. if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
  1894. if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
  1895. return(_JKParseUTF8String(parseState, NO, string, (size_t)length, error));
  1896. }
  1897. - (id)objectWithData:(NSData *)jsonData
  1898. {
  1899. return([self objectWithData:jsonData error:NULL]);
  1900. }
  1901. - (id)objectWithData:(NSData *)jsonData error:(NSError **)error
  1902. {
  1903. if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
  1904. return([self objectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
  1905. }
  1906. ////////////
  1907. #pragma mark Methods that return mutable collection objects
  1908. ////////////
  1909. - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length
  1910. {
  1911. return([self mutableObjectWithUTF8String:string length:length error:NULL]);
  1912. }
  1913. - (id)mutableObjectWithUTF8String:(const unsigned char *)string length:(NSUInteger)length error:(NSError **)error
  1914. {
  1915. if(parseState == NULL) { [NSException raise:NSInternalInconsistencyException format:@"parseState is NULL."]; }
  1916. if(string == NULL) { [NSException raise:NSInvalidArgumentException format:@"The string argument is NULL."]; }
  1917. return(_JKParseUTF8String(parseState, YES, string, (size_t)length, error));
  1918. }
  1919. - (id)mutableObjectWithData:(NSData *)jsonData
  1920. {
  1921. return([self mutableObjectWithData:jsonData error:NULL]);
  1922. }
  1923. - (id)mutableObjectWithData:(NSData *)jsonData error:(NSError **)error
  1924. {
  1925. if(jsonData == NULL) { [NSException raise:NSInvalidArgumentException format:@"The jsonData argument is NULL."]; }
  1926. return([self mutableObjectWithUTF8String:(const unsigned char *)[jsonData bytes] length:[jsonData length] error:error]);
  1927. }
  1928. @end
  1929. /*
  1930. The NSString and NSData convenience methods need a little bit of explanation.
  1931. Prior to JSONKit v1.4, the NSString -objectFromJSONStringWithParseOptions:error: method looked like
  1932. const unsigned char *utf8String = (const unsigned char *)[self UTF8String];
  1933. if(utf8String == NULL) { return(NULL); }
  1934. size_t utf8Length = strlen((const char *)utf8String);
  1935. return([[JSONDecoder decoderWithParseOptions:parseOptionFlags] parseUTF8String:utf8String length:utf8Length error:error]);
  1936. This changed with v1.4 to a more complicated method. The reason for this is to keep the amount of memory that is
  1937. allocated, but not yet freed because it is dependent on the autorelease pool to pop before it can be reclaimed.
  1938. In the simpler v1.3 code, this included all the bytes used to store the -UTF8String along with the JSONDecoder and all its overhead.
  1939. 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
  1940. conversion of said string.
  1941. Once parsed, the CFMutableData has its length set to 0. This should, hopefully, allow the CFMutableData to realloc and/or free
  1942. the buffer.
  1943. Another change made was a slight modification to JSONDecoder so that most of the cleanup work that was done in -dealloc was moved
  1944. to a private, internal function. These convenience routines keep the pointer to the autoreleased JSONDecoder and calls
  1945. _JSONDecoderCleanup() to early release the decoders resources since we already know that particular decoder is not going to be used
  1946. again.
  1947. If everything goes smoothly, this will most likely result in perhaps a few hundred bytes that are allocated but waiting for the
  1948. autorelease pool to pop. This is compared to the thousands and easily hundreds of thousands of bytes that would have been in
  1949. autorelease limbo. It's more complicated for us, but a win for the user.
  1950. Autorelease objects are used in case things don't go smoothly. By having them autoreleased, we effectively guarantee that our
  1951. requirement to -release the object is always met, not matter what goes wrong. The downside is having a an object or two in
  1952. autorelease limbo, but we've done our best to minimize that impact, so it all balances out.
  1953. */
  1954. @implementation NSString (JSONKitDeserializing)
  1955. static id _NSStringObjectFromJSONString(NSString *jsonString, JKParseOptionFlags parseOptionFlags, NSError **error, BOOL mutableCollection) {
  1956. id returnObject = NULL;
  1957. CFMutableDataRef mutableData = NULL;
  1958. JSONDecoder *decoder = NULL;
  1959. CFIndex stringLength = CFStringGetLength((CFStringRef)jsonString);
  1960. NSUInteger stringUTF8Length = [jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  1961. if((mutableData = (CFMutableDataRef)[(id)CFDataCreateMutable(NULL, (NSUInteger)stringUTF8Length) autorelease]) != NULL) {
  1962. UInt8 *utf8String = CFDataGetMutableBytePtr(mutableData);
  1963. CFIndex usedBytes = 0L, convertedCount = 0L;
  1964. convertedCount = CFStringGetBytes((CFStringRef)jsonString, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, utf8String, (NSUInteger)stringUTF8Length, &usedBytes);
  1965. 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; }
  1966. if(mutableCollection == NO) { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
  1967. else { returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithUTF8String:(const unsigned char *)utf8String length:(size_t)usedBytes error:error]; }
  1968. }
  1969. exitNow:
  1970. if(mutableData != NULL) { CFDataSetLength(mutableData, 0L); }
  1971. if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
  1972. return(returnObject);
  1973. }
  1974. - (id)objectFromJSONString
  1975. {
  1976. return([self objectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
  1977. }
  1978. - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  1979. {
  1980. return([self objectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
  1981. }
  1982. - (id)objectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
  1983. {
  1984. return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, NO));
  1985. }
  1986. - (id)mutableObjectFromJSONString
  1987. {
  1988. return([self mutableObjectFromJSONStringWithParseOptions:JKParseOptionStrict error:NULL]);
  1989. }
  1990. - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  1991. {
  1992. return([self mutableObjectFromJSONStringWithParseOptions:parseOptionFlags error:NULL]);
  1993. }
  1994. - (id)mutableObjectFromJSONStringWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
  1995. {
  1996. return(_NSStringObjectFromJSONString(self, parseOptionFlags, error, YES));
  1997. }
  1998. @end
  1999. @implementation NSData (JSONKitDeserializing)
  2000. - (id)objectFromJSONData
  2001. {
  2002. return([self objectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
  2003. }
  2004. - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  2005. {
  2006. return([self objectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
  2007. }
  2008. - (id)objectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
  2009. {
  2010. JSONDecoder *decoder = NULL;
  2011. id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) objectWithData:self error:error];
  2012. if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
  2013. return(returnObject);
  2014. }
  2015. - (id)mutableObjectFromJSONData
  2016. {
  2017. return([self mutableObjectFromJSONDataWithParseOptions:JKParseOptionStrict error:NULL]);
  2018. }
  2019. - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags
  2020. {
  2021. return([self mutableObjectFromJSONDataWithParseOptions:parseOptionFlags error:NULL]);
  2022. }
  2023. - (id)mutableObjectFromJSONDataWithParseOptions:(JKParseOptionFlags)parseOptionFlags error:(NSError **)error
  2024. {
  2025. JSONDecoder *decoder = NULL;
  2026. id returnObject = [(decoder = [JSONDecoder decoderWithParseOptions:parseOptionFlags]) mutableObjectWithData:self error:error];
  2027. if(decoder != NULL) { _JSONDecoderCleanup(decoder); }
  2028. return(returnObject);
  2029. }
  2030. @end
  2031. ////////////
  2032. #pragma mark -
  2033. #pragma mark Encoding / deserializing functions
  2034. static void jk_encode_error(JKEncodeState *encodeState, NSString *format, ...) {
  2035. NSCParameterAssert((encodeState != NULL) && (format != NULL));
  2036. va_list varArgsList;
  2037. va_start(varArgsList, format);
  2038. NSString *formatString = [[[NSString alloc] initWithFormat:format arguments:varArgsList] autorelease];
  2039. va_end(varArgsList);
  2040. if(encodeState->error == NULL) {
  2041. encodeState->error = [NSError errorWithDomain:@"JKErrorDomain" code:-1L userInfo:
  2042. [NSDictionary dictionaryWithObjectsAndKeys:
  2043. formatString, NSLocalizedDescriptionKey,
  2044. NULL]];
  2045. }
  2046. }
  2047. JK_STATIC_INLINE void jk_encode_updateCache(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object) {
  2048. NSCParameterAssert(encodeState != NULL);
  2049. if(JK_EXPECT_T(cacheSlot != NULL)) {
  2050. NSCParameterAssert((object != NULL) && (startingAtIndex <= encodeState->atIndex));
  2051. cacheSlot->object = object;
  2052. cacheSlot->offset = startingAtIndex;
  2053. cacheSlot->length = (size_t)(encodeState->atIndex - startingAtIndex);
  2054. }
  2055. }
  2056. static int jk_encode_printf(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, ...) {
  2057. va_list varArgsList, varArgsListCopy;
  2058. va_start(varArgsList, format);
  2059. va_copy(varArgsListCopy, varArgsList);
  2060. NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
  2061. ssize_t formattedStringLength = 0L;
  2062. int returnValue = 0;
  2063. 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))) {
  2064. NSCParameterAssert(((encodeState->atIndex + (formattedStringLength * 2UL) + 256UL) > encodeState->stringBuffer.bytes.length));
  2065. 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; }
  2066. 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; }
  2067. }
  2068. exitNow:
  2069. va_end(varArgsList);
  2070. va_end(varArgsListCopy);
  2071. if(JK_EXPECT_T(returnValue == 0)) { encodeState->atIndex += formattedStringLength; jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object); }
  2072. return(returnValue);
  2073. }
  2074. static int jk_encode_write(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format) {
  2075. NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex) && (format != NULL));
  2076. 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); }
  2077. size_t formatIdx = 0UL;
  2078. for(formatIdx = 0UL; format[formatIdx] != 0; formatIdx++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[formatIdx]; }
  2079. jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
  2080. return(0);
  2081. }
  2082. static int jk_encode_writePrettyPrintWhiteSpace(JKEncodeState *encodeState) {
  2083. NSCParameterAssert((encodeState != NULL) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) != 0UL));
  2084. 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); }
  2085. encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\n';
  2086. size_t depthWhiteSpace = 0UL;
  2087. for(depthWhiteSpace = 0UL; depthWhiteSpace < (encodeState->depth * 2UL); depthWhiteSpace++) { NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length); encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
  2088. return(0);
  2089. }
  2090. static int jk_encode_write1slow(JKEncodeState *encodeState, ssize_t depthChange, const char *format) {
  2091. 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));
  2092. 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); }
  2093. encodeState->depth += depthChange;
  2094. if(JK_EXPECT_T(format[0] == ':')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = ' '; }
  2095. else {
  2096. if(JK_EXPECT_F(depthChange == -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
  2097. encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0];
  2098. if(JK_EXPECT_T(depthChange != -1L)) { if(JK_EXPECT_F(jk_encode_writePrettyPrintWhiteSpace(encodeState))) { return(1); } }
  2099. }
  2100. NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
  2101. return(0);
  2102. }
  2103. static int jk_encode_write1fast(JKEncodeState *encodeState, ssize_t depthChange JK_UNUSED_ARG, const char *format) {
  2104. NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && ((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0UL));
  2105. if(JK_EXPECT_T((encodeState->atIndex + 4UL) < encodeState->stringBuffer.bytes.length)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = format[0]; }
  2106. else { return(jk_encode_write(encodeState, NULL, 0UL, NULL, format)); }
  2107. return(0);
  2108. }
  2109. static int jk_encode_writen(JKEncodeState *encodeState, JKEncodeCache *cacheSlot, size_t startingAtIndex, id object, const char *format, size_t length) {
  2110. NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (startingAtIndex <= encodeState->atIndex));
  2111. 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); } }
  2112. memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, format, length);
  2113. encodeState->atIndex += length;
  2114. jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
  2115. return(0);
  2116. }
  2117. JK_STATIC_INLINE JKHash jk_encode_object_hash(void *objectPtr) {
  2118. return( ( (((JKHash)objectPtr) >> 21) ^ (((JKHash)objectPtr) >> 9) ) + (((JKHash)objectPtr) >> 4) );
  2119. }
  2120. static int jk_encode_add_atom_to_buffer(JKEncodeState *encodeState, void *objectPtr) {
  2121. NSCParameterAssert((encodeState != NULL) && (encodeState->atIndex < encodeState->stringBuffer.bytes.length) && (objectPtr != NULL));
  2122. id object = (id)objectPtr;
  2123. int isClass = JKClassUnknown;
  2124. size_t startingAtIndex = encodeState->atIndex;
  2125. JKHash objectHash = jk_encode_object_hash(objectPtr);
  2126. JKEncodeCache *cacheSlot = &encodeState->cache[objectHash % JK_ENCODE_CACHE_SLOTS];
  2127. if(JK_EXPECT_T(cacheSlot->object == object)) {
  2128. NSCParameterAssert((cacheSlot->offset < encodeState->atIndex) && ((cacheSlot->offset + cacheSlot->length) < encodeState->atIndex) &&
  2129. (cacheSlot->offset < encodeState->stringBuffer.bytes.length) && ((cacheSlot->offset + cacheSlot->length) < encodeState->stringBuffer.bytes.length) &&
  2130. ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2131. ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2132. ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)));
  2133. 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); }
  2134. NSCParameterAssert(((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2135. ((encodeState->stringBuffer.bytes.ptr + encodeState->atIndex + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2136. ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2137. ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->stringBuffer.bytes.length)) &&
  2138. ((encodeState->stringBuffer.bytes.ptr + cacheSlot->offset + cacheSlot->length) < (encodeState->stringBuffer.bytes.ptr + encodeState->atIndex)));
  2139. memcpy(encodeState->stringBuffer.bytes.ptr + encodeState->atIndex, encodeState->stringBuffer.bytes.ptr + cacheSlot->offset, cacheSlot->length);
  2140. encodeState->atIndex += cacheSlot->length;
  2141. return(0);
  2142. }
  2143. if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.stringClass)) { isClass = JKClassString; }
  2144. else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.numberClass)) { isClass = JKClassNumber; }
  2145. else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.dictionaryClass)) { isClass = JKClassDictionary; }
  2146. else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.arrayClass)) { isClass = JKClassArray; }
  2147. else if(JK_EXPECT_T(object_getClass(object) == encodeState->fastClassLookup.nullClass)) { isClass = JKClassNull; }
  2148. else {
  2149. if(JK_EXPECT_T([object isKindOfClass:[NSString class]])) { encodeState->fastClassLookup.stringClass = object_getClass(object); isClass = JKClassString; }
  2150. else if(JK_EXPECT_T([object isKindOfClass:[NSNumber class]])) { encodeState->fastClassLookup.numberClass = object_getClass(object); isClass = JKClassNumber; }
  2151. else if(JK_EXPECT_T([object isKindOfClass:[NSDictionary class]])) { encodeState->fastClassLookup.dictionaryClass = object_getClass(object); isClass = JKClassDictionary; }
  2152. else if(JK_EXPECT_T([object isKindOfClass:[NSArray class]])) { encodeState->fastClassLookup.arrayClass = object_getClass(object); isClass = JKClassArray; }
  2153. else if(JK_EXPECT_T([object isKindOfClass:[NSNull class]])) { encodeState->fastClassLookup.nullClass = object_getClass(object); isClass = JKClassNull; }
  2154. else { jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); }
  2155. }
  2156. // This is here for the benefit of the optimizer. It allows the optimizer to do loop invariant code motion for the JKClassArray
  2157. // and JKClassDictionary cases when printing simple, single characters via jk_encode_write(), which is actually a macro:
  2158. // #define jk_encode_write1(es, dc, f) (_jk_encode_useWrite1Fast ? jk_encode_write1fast(es, dc, f) : jk_encode_write1slow(es, dc, f))
  2159. int _jk_encode_useWrite1Fast = JK_EXPECT_T((encodeState->serializeOptionFlags & JKSerializeOptionPretty) == 0) ? 1 : 0;
  2160. switch(isClass) {
  2161. case JKClassString:
  2162. {
  2163. {
  2164. const unsigned char *cStringPtr = (const unsigned char *)CFStringGetCStringPtr((CFStringRef)object, kCFStringEncodingMacRoman);
  2165. if(cStringPtr != NULL) {
  2166. const unsigned char *utf8String = cStringPtr;
  2167. size_t utf8Idx = 0UL;
  2168. CFIndex stringLength = CFStringGetLength((CFStringRef)object);
  2169. 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); }
  2170. if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
  2171. for(utf8Idx = 0UL; utf8String[utf8Idx] != 0U; utf8Idx++) {
  2172. NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
  2173. NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
  2174. if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U)) { encodeState->atIndex = startingAtIndex; goto slowUTF8Path; }
  2175. if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
  2176. switch(utf8String[utf8Idx]) {
  2177. case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
  2178. case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
  2179. case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
  2180. case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
  2181. case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
  2182. default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
  2183. }
  2184. } else {
  2185. if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; }
  2186. encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
  2187. }
  2188. }
  2189. NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
  2190. if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
  2191. jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
  2192. return(0);
  2193. }
  2194. }
  2195. slowUTF8Path:
  2196. {
  2197. CFIndex stringLength = CFStringGetLength((CFStringRef)object);
  2198. CFIndex maxStringUTF8Length = CFStringGetMaximumSizeForEncoding(stringLength, kCFStringEncodingUTF8) + 32L;
  2199. 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); }
  2200. CFIndex usedBytes = 0L, convertedCount = 0L;
  2201. convertedCount = CFStringGetBytes((CFStringRef)object, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', NO, encodeState->utf8ConversionBuffer.bytes.ptr, encodeState->utf8ConversionBuffer.bytes.length - 16L, &usedBytes);
  2202. 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); }
  2203. 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); }
  2204. const unsigned char *utf8String = encodeState->utf8ConversionBuffer.bytes.ptr;
  2205. size_t utf8Idx = 0UL;
  2206. if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
  2207. for(utf8Idx = 0UL; utf8Idx < (size_t)usedBytes; utf8Idx++) {
  2208. NSCParameterAssert(((&encodeState->stringBuffer.bytes.ptr[encodeState->atIndex]) - encodeState->stringBuffer.bytes.ptr) < (ssize_t)encodeState->stringBuffer.bytes.length);
  2209. NSCParameterAssert(encodeState->atIndex < encodeState->stringBuffer.bytes.length);
  2210. NSCParameterAssert((CFIndex)utf8Idx < usedBytes);
  2211. if(JK_EXPECT_F(utf8String[utf8Idx] < 0x20U)) {
  2212. switch(utf8String[utf8Idx]) {
  2213. case '\b': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'b'; break;
  2214. case '\f': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'f'; break;
  2215. case '\n': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'n'; break;
  2216. case '\r': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 'r'; break;
  2217. case '\t': encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = 't'; break;
  2218. default: if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", utf8String[utf8Idx]))) { return(1); } break;
  2219. }
  2220. } else {
  2221. if(JK_EXPECT_F(utf8String[utf8Idx] >= 0x80U) && (encodeState->serializeOptionFlags & JKSerializeOptionEscapeUnicode)) {
  2222. const unsigned char *nextValidCharacter = NULL;
  2223. UTF32 u32ch = 0U;
  2224. ConversionResult result;
  2225. if(JK_EXPECT_F((result = ConvertSingleCodePointInUTF8(&utf8String[utf8Idx], &utf8String[usedBytes], (UTF8 const **)&nextValidCharacter, &u32ch)) != conversionOK)) { jk_encode_error(encodeState, @"Error converting UTF8."); return(1); }
  2226. else {
  2227. utf8Idx = (nextValidCharacter - utf8String) - 1UL;
  2228. if(JK_EXPECT_T(u32ch <= 0xffffU)) { if(JK_EXPECT_F(jk_encode_printf(encodeState, NULL, 0UL, NULL, "\\u%4.4x", u32ch))) { return(1); } }
  2229. 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); } }
  2230. }
  2231. } else {
  2232. if(JK_EXPECT_F(utf8String[utf8Idx] == '\"') || JK_EXPECT_F(utf8String[utf8Idx] == '\\')) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\\'; }
  2233. encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = utf8String[utf8Idx];
  2234. }
  2235. }
  2236. }
  2237. NSCParameterAssert((encodeState->atIndex + 1UL) < encodeState->stringBuffer.bytes.length);
  2238. if(JK_EXPECT_T((encodeState->encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) { encodeState->stringBuffer.bytes.ptr[encodeState->atIndex++] = '\"'; }
  2239. jk_encode_updateCache(encodeState, cacheSlot, startingAtIndex, object);
  2240. return(0);
  2241. }
  2242. }
  2243. break;
  2244. case JKClassNumber:
  2245. {
  2246. if(object == (id)kCFBooleanTrue) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "true", 4UL)); }
  2247. else if(object == (id)kCFBooleanFalse) { return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "false", 5UL)); }
  2248. const char *objCType = [object objCType];
  2249. char anum[256], *aptr = &anum[255];
  2250. int isNegative = 0;
  2251. unsigned long long ullv;
  2252. long long llv;
  2253. 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); }
  2254. switch(objCType[0]) {
  2255. case 'c': case 'i': case 's': case 'l': case 'q':
  2256. if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &llv))) {
  2257. if(llv < 0LL) { ullv = -llv; isNegative = 1; } else { ullv = llv; isNegative = 0; }
  2258. goto convertNumber;
  2259. } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
  2260. break;
  2261. case 'C': case 'I': case 'S': case 'L': case 'Q': case 'B':
  2262. if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberLongLongType, &ullv))) {
  2263. convertNumber:
  2264. 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); } }
  2265. if(isNegative) { *--aptr = '-'; }
  2266. NSCParameterAssert(aptr > anum);
  2267. return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, aptr, &anum[255] - aptr));
  2268. } else { jk_encode_error(encodeState, @"Unable to get scalar value from number object."); return(1); }
  2269. break;
  2270. case 'f': case 'd':
  2271. {
  2272. double dv;
  2273. if(JK_EXPECT_T(CFNumberGetValue((CFNumberRef)object, kCFNumberDoubleType, &dv))) {
  2274. 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); }
  2275. return(jk_encode_printf(encodeState, cacheSlot, startingAtIndex, object, "%.17g", dv));
  2276. } else { jk_encode_error(encodeState, @"Unable to get floating point value from number object."); return(1); }
  2277. }
  2278. break;
  2279. default: jk_encode_error(encodeState, @"NSNumber conversion error, unknown type. Type: '%c' / 0x%2.2x", objCType[0], objCType[0]); return(1); break;
  2280. }
  2281. }
  2282. break;
  2283. case JKClassArray:
  2284. {
  2285. int printComma = 0;
  2286. CFIndex arrayCount = CFArrayGetCount((CFArrayRef)object), idx = 0L;
  2287. if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "["))) { return(1); }
  2288. if(JK_EXPECT_F(arrayCount > 1020L)) {
  2289. 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); } }
  2290. } else {
  2291. void *objects[1024];
  2292. CFArrayGetValues((CFArrayRef)object, CFRangeMake(0L, arrayCount), (const void **)objects);
  2293. 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); } }
  2294. }
  2295. return(jk_encode_write1(encodeState, -1L, "]"));
  2296. }
  2297. break;
  2298. case JKClassDictionary:
  2299. {
  2300. int printComma = 0;
  2301. CFIndex dictionaryCount = CFDictionaryGetCount((CFDictionaryRef)object), idx = 0L;
  2302. if(JK_EXPECT_F(jk_encode_write1(encodeState, 1L, "{"))) { return(1); }
  2303. if(JK_EXPECT_F(dictionaryCount > 1020L)) {
  2304. for(id keyObject in object) {
  2305. if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
  2306. printComma = 1;
  2307. if(JK_EXPECT_F((object_getClass(keyObject) != encodeState->fastClassLookup.stringClass)) && JK_EXPECT_F(([keyObject isKindOfClass:[NSString class]] == NO))) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); }
  2308. if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keyObject))) { return(1); }
  2309. if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
  2310. if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, (void *)CFDictionaryGetValue((CFDictionaryRef)object, keyObject)))) { return(1); }
  2311. }
  2312. } else {
  2313. void *keys[1024], *objects[1024];
  2314. CFDictionaryGetKeysAndValues((CFDictionaryRef)object, (const void **)keys, (const void **)objects);
  2315. for(idx = 0L; idx < dictionaryCount; idx++) {
  2316. if(JK_EXPECT_T(printComma)) { if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ","))) { return(1); } }
  2317. printComma = 1;
  2318. if(JK_EXPECT_F(object_getClass((id)keys[idx]) != encodeState->fastClassLookup.stringClass) && JK_EXPECT_F([(id)keys[idx] isKindOfClass:[NSString class]] == NO)) { jk_encode_error(encodeState, @"Key must be a string object."); return(1); }
  2319. if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, keys[idx]))) { return(1); }
  2320. if(JK_EXPECT_F(jk_encode_write1(encodeState, 0L, ":"))) { return(1); }
  2321. if(JK_EXPECT_F(jk_encode_add_atom_to_buffer(encodeState, objects[idx]))) { return(1); }
  2322. }
  2323. }
  2324. return(jk_encode_write1(encodeState, -1L, "}"));
  2325. }
  2326. break;
  2327. case JKClassNull: return(jk_encode_writen(encodeState, cacheSlot, startingAtIndex, object, "null", 4UL)); break;
  2328. default: jk_encode_error(encodeState, @"Unable to serialize object class %@.", NSStringFromClass([object class])); return(1); break;
  2329. }
  2330. return(0);
  2331. }
  2332. @implementation JKSerializer
  2333. + (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption error:(NSError **)error
  2334. {
  2335. return([[[[self alloc] init] autorelease] serializeObject:object options:optionFlags encodeOption:encodeOption error:error]);
  2336. }
  2337. - (id)serializeObject:(id)object options:(JKSerializeOptionFlags)optionFlags encodeOption:(JKEncodeOptionType)encodeOption error:(NSError **)error
  2338. {
  2339. NSParameterAssert((object != NULL) && (encodeState == NULL) &&
  2340. (((encodeOption & JKEncodeOptionCollectionObj) != 0UL) ? (((encodeOption & JKEncodeOptionStringObj) == 0UL) && ((encodeOption & JKEncodeOptionStringObjTrimQuotes) == 0UL)) : 1) &&
  2341. (((encodeOption & JKEncodeOptionStringObj) != 0UL) ? ((encodeOption & JKEncodeOptionCollectionObj) == 0UL) : 1));
  2342. id returnObject = NULL;
  2343. if(encodeState != NULL) { [self releaseState]; }
  2344. if((encodeState = (struct JKEncodeState *)calloc(1UL, sizeof(JKEncodeState))) == NULL) { [NSException exceptionWithName:NSMallocException reason:@"Unable to allocate state structure." userInfo:NULL]; }
  2345. if((error != NULL) && (*error != NULL)) { *error = NULL; }
  2346. encodeState->serializeOptionFlags = optionFlags;
  2347. encodeState->encodeOption = encodeOption;
  2348. encodeState->stringBuffer.roundSizeUpToMultipleOf = (1024UL * 32UL);
  2349. encodeState->utf8ConversionBuffer.roundSizeUpToMultipleOf = 4096UL;
  2350. unsigned char stackJSONBuffer[JK_JSONBUFFER_SIZE] JK_ALIGNED(64);
  2351. jk_managedBuffer_setToStackBuffer(&encodeState->stringBuffer, stackJSONBuffer, sizeof(stackJSONBuffer));
  2352. unsigned char stackUTF8Buffer[JK_UTF8BUFFER_SIZE] JK_ALIGNED(64);
  2353. jk_managedBuffer_setToStackBuffer(&encodeState->utf8ConversionBuffer, stackUTF8Buffer, sizeof(stackUTF8Buffer));
  2354. 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; }
  2355. 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; }
  2356. if(jk_encode_add_atom_to_buffer(encodeState, object) == 0) {
  2357. BOOL stackBuffer = ((encodeState->stringBuffer.flags & JKManagedBufferMustFree) == 0UL) ? YES : NO;
  2358. if((encodeState->atIndex < 2UL))
  2359. 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; }
  2360. switch((encodeOption & JKEncodeOptionAsTypeMask)) {
  2361. case JKEncodeOptionAsData:
  2362. 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"); } }
  2363. 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"); } }
  2364. break;
  2365. case JKEncodeOptionAsString:
  2366. 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"); } }
  2367. 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"); } }
  2368. break;
  2369. default: jk_encode_error(encodeState, @"Unknown encode as type."); break;
  2370. }
  2371. if((returnObject != NULL) && (stackBuffer == NO)) { encodeState->stringBuffer.flags &= ~JKManagedBufferMustFree; encodeState->stringBuffer.bytes.ptr = NULL; encodeState->stringBuffer.bytes.length = 0UL; }
  2372. }
  2373. errorExit:
  2374. if((encodeState != NULL) && (error != NULL) && (encodeState->error != NULL)) { *error = encodeState->error; encodeState->error = NULL; }
  2375. [self releaseState];
  2376. return(returnObject);
  2377. }
  2378. - (void)releaseState
  2379. {
  2380. if(encodeState != NULL) {
  2381. jk_managedBuffer_release(&encodeState->stringBuffer);
  2382. jk_managedBuffer_release(&encodeState->utf8ConversionBuffer);
  2383. free(encodeState); encodeState = NULL;
  2384. }
  2385. }
  2386. - (void)dealloc
  2387. {
  2388. [self releaseState];
  2389. [super dealloc];
  2390. }
  2391. @end
  2392. @implementation NSString (JSONKitSerializing)
  2393. ////////////
  2394. #pragma mark Methods for serializing a single NSString.
  2395. ////////////
  2396. // 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.
  2397. - (NSData *)JSONData
  2398. {
  2399. return([self JSONDataWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
  2400. }
  2401. - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
  2402. {
  2403. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) error:error]);
  2404. }
  2405. - (NSString *)JSONString
  2406. {
  2407. return([self JSONStringWithOptions:JKSerializeOptionNone includeQuotes:YES error:NULL]);
  2408. }
  2409. - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions includeQuotes:(BOOL)includeQuotes error:(NSError **)error
  2410. {
  2411. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | ((includeQuotes == NO) ? JKEncodeOptionStringObjTrimQuotes : 0UL) | JKEncodeOptionStringObj) error:error]);
  2412. }
  2413. @end
  2414. @implementation NSArray (JSONKitSerializing)
  2415. - (NSData *)JSONData
  2416. {
  2417. return([self JSONDataWithOptions:JKSerializeOptionNone error:NULL]);
  2418. }
  2419. - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
  2420. {
  2421. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) error:error]);
  2422. }
  2423. - (NSString *)JSONString
  2424. {
  2425. return([self JSONStringWithOptions:JKSerializeOptionNone error:NULL]);
  2426. }
  2427. - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
  2428. {
  2429. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) error:error]);
  2430. }
  2431. @end
  2432. @implementation NSDictionary (JSONKitSerializing)
  2433. - (NSData *)JSONData
  2434. {
  2435. return([self JSONDataWithOptions:JKSerializeOptionNone error:NULL]);
  2436. }
  2437. - (NSData *)JSONDataWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
  2438. {
  2439. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsData | JKEncodeOptionCollectionObj) error:error]);
  2440. }
  2441. - (NSString *)JSONString
  2442. {
  2443. return([self JSONStringWithOptions:JKSerializeOptionNone error:NULL]);
  2444. }
  2445. - (NSString *)JSONStringWithOptions:(JKSerializeOptionFlags)serializeOptions error:(NSError **)error
  2446. {
  2447. return([JKSerializer serializeObject:self options:serializeOptions encodeOption:(JKEncodeOptionAsString | JKEncodeOptionCollectionObj) error:error]);
  2448. }
  2449. @end