JSONKit.m 173 KB

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