jsoncpp.cpp 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953
  1. /// Json-cpp amalgated source (http://jsoncpp.sourceforge.net/).
  2. /// It is intended to be used with #include "json/json.h"
  3. // //////////////////////////////////////////////////////////////////////
  4. // Beginning of content of file: LICENSE
  5. // //////////////////////////////////////////////////////////////////////
  6. /*
  7. The JsonCpp library's source code, including accompanying documentation,
  8. tests and demonstration applications, are licensed under the following
  9. conditions...
  10. The author (Baptiste Lepilleur) explicitly disclaims copyright in all
  11. jurisdictions which recognize such a disclaimer. In such jurisdictions,
  12. this software is released into the Public Domain.
  13. In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
  14. 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
  15. released under the terms of the MIT License (see below).
  16. In jurisdictions which recognize Public Domain property, the user of this
  17. software may choose to accept it either as 1) Public Domain, 2) under the
  18. conditions of the MIT License (see below), or 3) under the terms of dual
  19. Public Domain/MIT License conditions described here, as they choose.
  20. The MIT License is about as close to Public Domain as a license can get, and is
  21. described in clear, concise terms at:
  22. http://en.wikipedia.org/wiki/MIT_License
  23. The full text of the MIT License follows:
  24. ========================================================================
  25. Copyright (c) 2007-2010 Baptiste Lepilleur
  26. Permission is hereby granted, free of charge, to any person
  27. obtaining a copy of this software and associated documentation
  28. files (the "Software"), to deal in the Software without
  29. restriction, including without limitation the rights to use, copy,
  30. modify, merge, publish, distribute, sublicense, and/or sell copies
  31. of the Software, and to permit persons to whom the Software is
  32. furnished to do so, subject to the following conditions:
  33. The above copyright notice and this permission notice shall be
  34. included in all copies or substantial portions of the Software.
  35. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  36. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  37. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  38. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  39. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  40. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  41. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  42. SOFTWARE.
  43. ========================================================================
  44. (END LICENSE TEXT)
  45. The MIT license is compatible with both the GPL and commercial
  46. software, affording one all of the rights of Public Domain with the
  47. minor nuisance of being required to keep the above copyright notice
  48. and license text in the source code. Note also that by accepting the
  49. Public Domain "license" you can re-license your copy using whatever
  50. license you like.
  51. */
  52. // //////////////////////////////////////////////////////////////////////
  53. // End of content of file: LICENSE
  54. // //////////////////////////////////////////////////////////////////////
  55. #include "json/json.h"
  56. #ifndef JSON_IS_AMALGAMATION
  57. #error "Compile with -I PATH_TO_JSON_DIRECTORY"
  58. #endif
  59. // //////////////////////////////////////////////////////////////////////
  60. // Beginning of content of file: src/lib_json/json_tool.h
  61. // //////////////////////////////////////////////////////////////////////
  62. // Copyright 2007-2010 Baptiste Lepilleur
  63. // Distributed under MIT license, or public domain if desired and
  64. // recognized in your jurisdiction.
  65. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  66. #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
  67. #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
  68. /* This header provides common string manipulation support, such as UTF-8,
  69. * portable conversion from/to string...
  70. *
  71. * It is an internal header that must not be exposed.
  72. */
  73. namespace Json {
  74. /// Converts a unicode code-point to UTF-8.
  75. static inline std::string codePointToUTF8(unsigned int cp) {
  76. std::string result;
  77. // based on description from http://en.wikipedia.org/wiki/UTF-8
  78. if (cp <= 0x7f) {
  79. result.resize(1);
  80. result[0] = static_cast<char>(cp);
  81. } else if (cp <= 0x7FF) {
  82. result.resize(2);
  83. result[1] = static_cast<char>(0x80 | (0x3f & cp));
  84. result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
  85. } else if (cp <= 0xFFFF) {
  86. result.resize(3);
  87. result[2] = static_cast<char>(0x80 | (0x3f & cp));
  88. result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
  89. result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12)));
  90. } else if (cp <= 0x10FFFF) {
  91. result.resize(4);
  92. result[3] = static_cast<char>(0x80 | (0x3f & cp));
  93. result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
  94. result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
  95. result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
  96. }
  97. return result;
  98. }
  99. /// Returns true if ch is a control character (in range [1,31]).
  100. static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
  101. enum {
  102. /// Constant that specify the size of the buffer that must be passed to
  103. /// uintToString.
  104. uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
  105. };
  106. // Defines a char buffer for use with uintToString().
  107. typedef char UIntToStringBuffer[uintToStringBufferSize];
  108. /** Converts an unsigned integer to string.
  109. * @param value Unsigned interger to convert to string
  110. * @param current Input/Output string buffer.
  111. * Must have at least uintToStringBufferSize chars free.
  112. */
  113. static inline void uintToString(LargestUInt value, char*& current) {
  114. *--current = 0;
  115. do {
  116. *--current = static_cast<signed char>(value % 10U + static_cast<unsigned>('0'));
  117. value /= 10;
  118. } while (value != 0);
  119. }
  120. /** Change ',' to '.' everywhere in buffer.
  121. *
  122. * We had a sophisticated way, but it did not work in WinCE.
  123. * @see https://github.com/open-source-parsers/jsoncpp/pull/9
  124. */
  125. static inline void fixNumericLocale(char* begin, char* end) {
  126. while (begin < end) {
  127. if (*begin == ',') {
  128. *begin = '.';
  129. }
  130. ++begin;
  131. }
  132. }
  133. } // namespace Json {
  134. #endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
  135. // //////////////////////////////////////////////////////////////////////
  136. // End of content of file: src/lib_json/json_tool.h
  137. // //////////////////////////////////////////////////////////////////////
  138. // //////////////////////////////////////////////////////////////////////
  139. // Beginning of content of file: src/lib_json/json_reader.cpp
  140. // //////////////////////////////////////////////////////////////////////
  141. // Copyright 2007-2011 Baptiste Lepilleur
  142. // Distributed under MIT license, or public domain if desired and
  143. // recognized in your jurisdiction.
  144. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  145. #if !defined(JSON_IS_AMALGAMATION)
  146. #include <json/assertions.h>
  147. #include <json/reader.h>
  148. #include <json/value.h>
  149. #include "json_tool.h"
  150. #endif // if !defined(JSON_IS_AMALGAMATION)
  151. #include <utility>
  152. #include <cstdio>
  153. #include <cassert>
  154. #include <cstring>
  155. #include <istream>
  156. #include <sstream>
  157. #include <memory>
  158. #include <set>
  159. #include <limits>
  160. #if defined(__BORLANDC__)
  161. #include <stdio.h>
  162. #endif
  163. #if defined(_MSC_VER)
  164. #if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
  165. #define snprintf sprintf_s
  166. #elif _MSC_VER >= 1900 // VC++ 14.0 and above
  167. #define snprintf std::snprintf
  168. #else
  169. #define snprintf _snprintf
  170. #endif
  171. #elif defined(__ANDROID__)
  172. #define snprintf snprintf
  173. #elif __cplusplus >= 201103L
  174. #define snprintf std::snprintf
  175. #endif
  176. #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
  177. // Disable warning about strdup being deprecated.
  178. #pragma warning(disable : 4996)
  179. #endif
  180. static int const stackLimit_g = 1000;
  181. static int stackDepth_g = 0; // see readValue()
  182. namespace Json {
  183. #if JSON_HAS_UNIQUE_PTR
  184. typedef std::unique_ptr<CharReader> const CharReaderPtr;
  185. #else
  186. typedef std::auto_ptr<CharReader> CharReaderPtr;
  187. #endif
  188. // Implementation of class Features
  189. // ////////////////////////////////
  190. Features::Features()
  191. : allowComments_(true), strictRoot_(false)
  192. {}
  193. Features Features::all() { return Features(); }
  194. Features Features::strictMode() {
  195. Features features;
  196. features.allowComments_ = false;
  197. features.strictRoot_ = true;
  198. return features;
  199. }
  200. // Implementation of class Reader
  201. // ////////////////////////////////
  202. static bool containsNewLine(Reader::Location begin, Reader::Location end) {
  203. for (; begin < end; ++begin)
  204. if (*begin == '\n' || *begin == '\r')
  205. return true;
  206. return false;
  207. }
  208. // Class Reader
  209. // //////////////////////////////////////////////////////////////////
  210. Reader::Reader()
  211. : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
  212. lastValue_(), commentsBefore_(), features_(Features::all()),
  213. collectComments_() {}
  214. Reader::Reader(const Features& features)
  215. : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
  216. lastValue_(), commentsBefore_(), features_(features), collectComments_() {
  217. }
  218. bool
  219. Reader::parse(const std::string& document, Value& root, bool collectComments) {
  220. document_ = document;
  221. const char* begin = document_.c_str();
  222. const char* end = begin + document_.length();
  223. return parse(begin, end, root, collectComments);
  224. }
  225. bool Reader::parse(std::istream& sin, Value& root, bool collectComments) {
  226. // std::istream_iterator<char> begin(sin);
  227. // std::istream_iterator<char> end;
  228. // Those would allow streamed input from a file, if parse() were a
  229. // template function.
  230. // Since std::string is reference-counted, this at least does not
  231. // create an extra copy.
  232. std::string doc;
  233. std::getline(sin, doc, (char)EOF);
  234. return parse(doc, root, collectComments);
  235. }
  236. bool Reader::parse(const char* beginDoc,
  237. const char* endDoc,
  238. Value& root,
  239. bool collectComments) {
  240. if (!features_.allowComments_) {
  241. collectComments = false;
  242. }
  243. begin_ = beginDoc;
  244. end_ = endDoc;
  245. collectComments_ = collectComments;
  246. current_ = begin_;
  247. lastValueEnd_ = 0;
  248. lastValue_ = 0;
  249. commentsBefore_ = "";
  250. errors_.clear();
  251. while (!nodes_.empty())
  252. nodes_.pop();
  253. nodes_.push(&root);
  254. stackDepth_g = 0; // Yes, this is bad coding, but options are limited.
  255. bool successful = readValue();
  256. Token token;
  257. skipCommentTokens(token);
  258. if (collectComments_ && !commentsBefore_.empty())
  259. root.setComment(commentsBefore_, commentAfter);
  260. if (features_.strictRoot_) {
  261. if (!root.isArray() && !root.isObject()) {
  262. // Set error location to start of doc, ideally should be first token found
  263. // in doc
  264. token.type_ = tokenError;
  265. token.start_ = beginDoc;
  266. token.end_ = endDoc;
  267. addError(
  268. "A valid JSON document must be either an array or an object value.",
  269. token);
  270. return false;
  271. }
  272. }
  273. return successful;
  274. }
  275. bool Reader::readValue() {
  276. // This is a non-reentrant way to support a stackLimit. Terrible!
  277. // But this deprecated class has a security problem: Bad input can
  278. // cause a seg-fault. This seems like a fair, binary-compatible way
  279. // to prevent the problem.
  280. if (stackDepth_g >= stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue().");
  281. ++stackDepth_g;
  282. Token token;
  283. skipCommentTokens(token);
  284. bool successful = true;
  285. if (collectComments_ && !commentsBefore_.empty()) {
  286. currentValue().setComment(commentsBefore_, commentBefore);
  287. commentsBefore_ = "";
  288. }
  289. switch (token.type_) {
  290. case tokenObjectBegin:
  291. successful = readObject(token);
  292. break;
  293. case tokenArrayBegin:
  294. successful = readArray(token);
  295. break;
  296. case tokenNumber:
  297. successful = decodeNumber(token);
  298. break;
  299. case tokenString:
  300. successful = decodeString(token);
  301. break;
  302. case tokenTrue:
  303. {
  304. Value v(true);
  305. currentValue().swapPayload(v);
  306. }
  307. break;
  308. case tokenFalse:
  309. {
  310. Value v(false);
  311. currentValue().swapPayload(v);
  312. }
  313. break;
  314. case tokenNull:
  315. {
  316. Value v;
  317. currentValue().swapPayload(v);
  318. }
  319. break;
  320. // Else, fall through...
  321. default:
  322. return addError("Syntax error: value, object or array expected.", token);
  323. }
  324. if (collectComments_) {
  325. lastValueEnd_ = current_;
  326. lastValue_ = &currentValue();
  327. }
  328. --stackDepth_g;
  329. return successful;
  330. }
  331. void Reader::skipCommentTokens(Token& token) {
  332. if (features_.allowComments_) {
  333. do {
  334. readToken(token);
  335. } while (token.type_ == tokenComment);
  336. } else {
  337. readToken(token);
  338. }
  339. }
  340. bool Reader::readToken(Token& token) {
  341. skipSpaces();
  342. token.start_ = current_;
  343. Char c = getNextChar();
  344. bool ok = true;
  345. switch (c) {
  346. case '{':
  347. token.type_ = tokenObjectBegin;
  348. break;
  349. case '}':
  350. token.type_ = tokenObjectEnd;
  351. break;
  352. case '[':
  353. token.type_ = tokenArrayBegin;
  354. break;
  355. case ']':
  356. token.type_ = tokenArrayEnd;
  357. break;
  358. case '"':
  359. token.type_ = tokenString;
  360. ok = readString();
  361. break;
  362. case '/':
  363. token.type_ = tokenComment;
  364. ok = readComment();
  365. break;
  366. case '0':
  367. case '1':
  368. case '2':
  369. case '3':
  370. case '4':
  371. case '5':
  372. case '6':
  373. case '7':
  374. case '8':
  375. case '9':
  376. case '-':
  377. token.type_ = tokenNumber;
  378. readNumber();
  379. break;
  380. case 't':
  381. token.type_ = tokenTrue;
  382. ok = match("rue", 3);
  383. break;
  384. case 'f':
  385. token.type_ = tokenFalse;
  386. ok = match("alse", 4);
  387. break;
  388. case 'n':
  389. token.type_ = tokenNull;
  390. ok = match("ull", 3);
  391. break;
  392. case ',':
  393. token.type_ = tokenArraySeparator;
  394. break;
  395. case ':':
  396. token.type_ = tokenMemberSeparator;
  397. break;
  398. case 0:
  399. token.type_ = tokenEndOfStream;
  400. break;
  401. default:
  402. ok = false;
  403. break;
  404. }
  405. if (!ok)
  406. token.type_ = tokenError;
  407. token.end_ = current_;
  408. return true;
  409. }
  410. void Reader::skipSpaces() {
  411. while (current_ != end_) {
  412. Char c = *current_;
  413. if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
  414. ++current_;
  415. else
  416. break;
  417. }
  418. }
  419. bool Reader::match(Location pattern, int patternLength) {
  420. if (end_ - current_ < patternLength)
  421. return false;
  422. int index = patternLength;
  423. while (index--)
  424. if (current_[index] != pattern[index])
  425. return false;
  426. current_ += patternLength;
  427. return true;
  428. }
  429. bool Reader::readComment() {
  430. Location commentBegin = current_ - 1;
  431. Char c = getNextChar();
  432. bool successful = false;
  433. if (c == '*')
  434. successful = readCStyleComment();
  435. else if (c == '/')
  436. successful = readCppStyleComment();
  437. if (!successful)
  438. return false;
  439. if (collectComments_) {
  440. CommentPlacement placement = commentBefore;
  441. if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
  442. if (c != '*' || !containsNewLine(commentBegin, current_))
  443. placement = commentAfterOnSameLine;
  444. }
  445. addComment(commentBegin, current_, placement);
  446. }
  447. return true;
  448. }
  449. static std::string normalizeEOL(Reader::Location begin, Reader::Location end) {
  450. std::string normalized;
  451. normalized.reserve(end - begin);
  452. Reader::Location current = begin;
  453. while (current != end) {
  454. char c = *current++;
  455. if (c == '\r') {
  456. if (current != end && *current == '\n')
  457. // convert dos EOL
  458. ++current;
  459. // convert Mac EOL
  460. normalized += '\n';
  461. } else {
  462. normalized += c;
  463. }
  464. }
  465. return normalized;
  466. }
  467. void
  468. Reader::addComment(Location begin, Location end, CommentPlacement placement) {
  469. assert(collectComments_);
  470. const std::string& normalized = normalizeEOL(begin, end);
  471. if (placement == commentAfterOnSameLine) {
  472. assert(lastValue_ != 0);
  473. lastValue_->setComment(normalized, placement);
  474. } else {
  475. commentsBefore_ += normalized;
  476. }
  477. }
  478. bool Reader::readCStyleComment() {
  479. while (current_ != end_) {
  480. Char c = getNextChar();
  481. if (c == '*' && *current_ == '/')
  482. break;
  483. }
  484. return getNextChar() == '/';
  485. }
  486. bool Reader::readCppStyleComment() {
  487. while (current_ != end_) {
  488. Char c = getNextChar();
  489. if (c == '\n')
  490. break;
  491. if (c == '\r') {
  492. // Consume DOS EOL. It will be normalized in addComment.
  493. if (current_ != end_ && *current_ == '\n')
  494. getNextChar();
  495. // Break on Moc OS 9 EOL.
  496. break;
  497. }
  498. }
  499. return true;
  500. }
  501. void Reader::readNumber() {
  502. const char *p = current_;
  503. char c = '0'; // stopgap for already consumed character
  504. // integral part
  505. while (c >= '0' && c <= '9')
  506. c = (current_ = p) < end_ ? *p++ : 0;
  507. // fractional part
  508. if (c == '.') {
  509. c = (current_ = p) < end_ ? *p++ : 0;
  510. while (c >= '0' && c <= '9')
  511. c = (current_ = p) < end_ ? *p++ : 0;
  512. }
  513. // exponential part
  514. if (c == 'e' || c == 'E') {
  515. c = (current_ = p) < end_ ? *p++ : 0;
  516. if (c == '+' || c == '-')
  517. c = (current_ = p) < end_ ? *p++ : 0;
  518. while (c >= '0' && c <= '9')
  519. c = (current_ = p) < end_ ? *p++ : 0;
  520. }
  521. }
  522. bool Reader::readString() {
  523. Char c = 0;
  524. while (current_ != end_) {
  525. c = getNextChar();
  526. if (c == '\\')
  527. getNextChar();
  528. else if (c == '"')
  529. break;
  530. }
  531. return c == '"';
  532. }
  533. bool Reader::readObject(Token& /*tokenStart*/) {
  534. Token tokenName;
  535. std::string name;
  536. Value init(objectValue);
  537. currentValue().swapPayload(init);
  538. while (readToken(tokenName)) {
  539. bool initialTokenOk = true;
  540. while (tokenName.type_ == tokenComment && initialTokenOk)
  541. initialTokenOk = readToken(tokenName);
  542. if (!initialTokenOk)
  543. break;
  544. if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
  545. return true;
  546. name = "";
  547. if (tokenName.type_ == tokenString) {
  548. if (!decodeString(tokenName, name))
  549. return recoverFromError(tokenObjectEnd);
  550. } else {
  551. break;
  552. }
  553. Token colon;
  554. if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
  555. return addErrorAndRecover(
  556. "Missing ':' after object member name", colon, tokenObjectEnd);
  557. }
  558. Value& value = currentValue()[name];
  559. nodes_.push(&value);
  560. bool ok = readValue();
  561. nodes_.pop();
  562. if (!ok) // error already set
  563. return recoverFromError(tokenObjectEnd);
  564. Token comma;
  565. if (!readToken(comma) ||
  566. (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
  567. comma.type_ != tokenComment)) {
  568. return addErrorAndRecover(
  569. "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
  570. }
  571. bool finalizeTokenOk = true;
  572. while (comma.type_ == tokenComment && finalizeTokenOk)
  573. finalizeTokenOk = readToken(comma);
  574. if (comma.type_ == tokenObjectEnd)
  575. return true;
  576. }
  577. return addErrorAndRecover(
  578. "Missing '}' or object member name", tokenName, tokenObjectEnd);
  579. }
  580. bool Reader::readArray(Token& /*tokenStart*/) {
  581. Value init(arrayValue);
  582. currentValue().swapPayload(init);
  583. skipSpaces();
  584. if (*current_ == ']') // empty array
  585. {
  586. Token endArray;
  587. readToken(endArray);
  588. return true;
  589. }
  590. int index = 0;
  591. for (;;) {
  592. Value& value = currentValue()[index++];
  593. nodes_.push(&value);
  594. bool ok = readValue();
  595. nodes_.pop();
  596. if (!ok) // error already set
  597. return recoverFromError(tokenArrayEnd);
  598. Token token;
  599. // Accept Comment after last item in the array.
  600. ok = readToken(token);
  601. while (token.type_ == tokenComment && ok) {
  602. ok = readToken(token);
  603. }
  604. bool badTokenType =
  605. (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
  606. if (!ok || badTokenType) {
  607. return addErrorAndRecover(
  608. "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
  609. }
  610. if (token.type_ == tokenArrayEnd)
  611. break;
  612. }
  613. return true;
  614. }
  615. bool Reader::decodeNumber(Token& token) {
  616. Value decoded;
  617. if (!decodeNumber(token, decoded))
  618. return false;
  619. currentValue().swapPayload(decoded);
  620. return true;
  621. }
  622. bool Reader::decodeNumber(Token& token, Value& decoded) {
  623. // Attempts to parse the number as an integer. If the number is
  624. // larger than the maximum supported value of an integer then
  625. // we decode the number as a double.
  626. Location current = token.start_;
  627. bool isNegative = *current == '-';
  628. if (isNegative)
  629. ++current;
  630. // TODO: Help the compiler do the div and mod at compile time or get rid of them.
  631. Value::LargestUInt maxIntegerValue =
  632. isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1
  633. : Value::maxLargestUInt;
  634. Value::LargestUInt threshold = maxIntegerValue / 10;
  635. Value::LargestUInt value = 0;
  636. while (current < token.end_) {
  637. Char c = *current++;
  638. if (c < '0' || c > '9')
  639. return decodeDouble(token, decoded);
  640. Value::UInt digit(c - '0');
  641. if (value >= threshold) {
  642. // We've hit or exceeded the max value divided by 10 (rounded down). If
  643. // a) we've only just touched the limit, b) this is the last digit, and
  644. // c) it's small enough to fit in that rounding delta, we're okay.
  645. // Otherwise treat this number as a double to avoid overflow.
  646. if (value > threshold || current != token.end_ ||
  647. digit > maxIntegerValue % 10) {
  648. return decodeDouble(token, decoded);
  649. }
  650. }
  651. value = value * 10 + digit;
  652. }
  653. if (isNegative && value == maxIntegerValue)
  654. decoded = Value::minLargestInt;
  655. else if (isNegative)
  656. decoded = -Value::LargestInt(value);
  657. else if (value <= Value::LargestUInt(Value::maxInt))
  658. decoded = Value::LargestInt(value);
  659. else
  660. decoded = value;
  661. return true;
  662. }
  663. bool Reader::decodeDouble(Token& token) {
  664. Value decoded;
  665. if (!decodeDouble(token, decoded))
  666. return false;
  667. currentValue().swapPayload(decoded);
  668. return true;
  669. }
  670. bool Reader::decodeDouble(Token& token, Value& decoded) {
  671. double value = 0;
  672. std::string buffer(token.start_, token.end_);
  673. std::istringstream is(buffer);
  674. if (!(is >> value))
  675. return addError("'" + std::string(token.start_, token.end_) +
  676. "' is not a number.",
  677. token);
  678. decoded = value;
  679. return true;
  680. }
  681. bool Reader::decodeString(Token& token) {
  682. std::string decoded_string;
  683. if (!decodeString(token, decoded_string))
  684. return false;
  685. Value decoded(decoded_string);
  686. currentValue().swapPayload(decoded);
  687. return true;
  688. }
  689. bool Reader::decodeString(Token& token, std::string& decoded) {
  690. decoded.reserve(token.end_ - token.start_ - 2);
  691. Location current = token.start_ + 1; // skip '"'
  692. Location end = token.end_ - 1; // do not include '"'
  693. while (current != end) {
  694. Char c = *current++;
  695. if (c == '"')
  696. break;
  697. else if (c == '\\') {
  698. if (current == end)
  699. return addError("Empty escape sequence in string", token, current);
  700. Char escape = *current++;
  701. switch (escape) {
  702. case '"':
  703. decoded += '"';
  704. break;
  705. case '/':
  706. decoded += '/';
  707. break;
  708. case '\\':
  709. decoded += '\\';
  710. break;
  711. case 'b':
  712. decoded += '\b';
  713. break;
  714. case 'f':
  715. decoded += '\f';
  716. break;
  717. case 'n':
  718. decoded += '\n';
  719. break;
  720. case 'r':
  721. decoded += '\r';
  722. break;
  723. case 't':
  724. decoded += '\t';
  725. break;
  726. case 'u': {
  727. unsigned int unicode;
  728. if (!decodeUnicodeCodePoint(token, current, end, unicode))
  729. return false;
  730. decoded += codePointToUTF8(unicode);
  731. } break;
  732. default:
  733. return addError("Bad escape sequence in string", token, current);
  734. }
  735. } else {
  736. decoded += c;
  737. }
  738. }
  739. return true;
  740. }
  741. bool Reader::decodeUnicodeCodePoint(Token& token,
  742. Location& current,
  743. Location end,
  744. unsigned int& unicode) {
  745. if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
  746. return false;
  747. if (unicode >= 0xD800 && unicode <= 0xDBFF) {
  748. // surrogate pairs
  749. if (end - current < 6)
  750. return addError(
  751. "additional six characters expected to parse unicode surrogate pair.",
  752. token,
  753. current);
  754. unsigned int surrogatePair;
  755. if (*(current++) == '\\' && *(current++) == 'u') {
  756. if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
  757. unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
  758. } else
  759. return false;
  760. } else
  761. return addError("expecting another \\u token to begin the second half of "
  762. "a unicode surrogate pair",
  763. token,
  764. current);
  765. }
  766. return true;
  767. }
  768. bool Reader::decodeUnicodeEscapeSequence(Token& token,
  769. Location& current,
  770. Location end,
  771. unsigned int& unicode) {
  772. if (end - current < 4)
  773. return addError(
  774. "Bad unicode escape sequence in string: four digits expected.",
  775. token,
  776. current);
  777. unicode = 0;
  778. for (int index = 0; index < 4; ++index) {
  779. Char c = *current++;
  780. unicode *= 16;
  781. if (c >= '0' && c <= '9')
  782. unicode += c - '0';
  783. else if (c >= 'a' && c <= 'f')
  784. unicode += c - 'a' + 10;
  785. else if (c >= 'A' && c <= 'F')
  786. unicode += c - 'A' + 10;
  787. else
  788. return addError(
  789. "Bad unicode escape sequence in string: hexadecimal digit expected.",
  790. token,
  791. current);
  792. }
  793. return true;
  794. }
  795. bool
  796. Reader::addError(const std::string& message, Token& token, Location extra) {
  797. ErrorInfo info;
  798. info.token_ = token;
  799. info.message_ = message;
  800. info.extra_ = extra;
  801. errors_.push_back(info);
  802. return false;
  803. }
  804. bool Reader::recoverFromError(TokenType skipUntilToken) {
  805. int errorCount = int(errors_.size());
  806. Token skip;
  807. for (;;) {
  808. if (!readToken(skip))
  809. errors_.resize(errorCount); // discard errors caused by recovery
  810. if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
  811. break;
  812. }
  813. errors_.resize(errorCount);
  814. return false;
  815. }
  816. bool Reader::addErrorAndRecover(const std::string& message,
  817. Token& token,
  818. TokenType skipUntilToken) {
  819. addError(message, token);
  820. return recoverFromError(skipUntilToken);
  821. }
  822. Value& Reader::currentValue() { return *(nodes_.top()); }
  823. Reader::Char Reader::getNextChar() {
  824. if (current_ == end_)
  825. return 0;
  826. return *current_++;
  827. }
  828. void Reader::getLocationLineAndColumn(Location location,
  829. int& line,
  830. int& column) const {
  831. Location current = begin_;
  832. Location lastLineStart = current;
  833. line = 0;
  834. while (current < location && current != end_) {
  835. Char c = *current++;
  836. if (c == '\r') {
  837. if (*current == '\n')
  838. ++current;
  839. lastLineStart = current;
  840. ++line;
  841. } else if (c == '\n') {
  842. lastLineStart = current;
  843. ++line;
  844. }
  845. }
  846. // column & line start at 1
  847. column = int(location - lastLineStart) + 1;
  848. ++line;
  849. }
  850. std::string Reader::getLocationLineAndColumn(Location location) const {
  851. int line, column;
  852. getLocationLineAndColumn(location, line, column);
  853. char buffer[18 + 16 + 16 + 1];
  854. snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
  855. return buffer;
  856. }
  857. // Deprecated. Preserved for backward compatibility
  858. std::string Reader::getFormatedErrorMessages() const {
  859. return getFormattedErrorMessages();
  860. }
  861. std::string Reader::getFormattedErrorMessages() const {
  862. std::string formattedMessage;
  863. for (Errors::const_iterator itError = errors_.begin();
  864. itError != errors_.end();
  865. ++itError) {
  866. const ErrorInfo& error = *itError;
  867. formattedMessage +=
  868. "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
  869. formattedMessage += " " + error.message_ + "\n";
  870. if (error.extra_)
  871. formattedMessage +=
  872. "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
  873. }
  874. return formattedMessage;
  875. }
  876. // Reader
  877. /////////////////////////
  878. // exact copy of Features
  879. class OurFeatures {
  880. public:
  881. static OurFeatures all();
  882. OurFeatures();
  883. bool allowComments_;
  884. bool strictRoot_;
  885. bool allowDroppedNullPlaceholders_;
  886. bool allowNumericKeys_;
  887. bool allowSingleQuotes_;
  888. bool failIfExtra_;
  889. bool rejectDupKeys_;
  890. bool allowSpecialFloats_;
  891. int stackLimit_;
  892. }; // OurFeatures
  893. // exact copy of Implementation of class Features
  894. // ////////////////////////////////
  895. OurFeatures::OurFeatures()
  896. : allowComments_(true), strictRoot_(false)
  897. , allowDroppedNullPlaceholders_(false), allowNumericKeys_(false)
  898. , allowSingleQuotes_(false)
  899. , failIfExtra_(false)
  900. , allowSpecialFloats_(false)
  901. {
  902. }
  903. OurFeatures OurFeatures::all() { return OurFeatures(); }
  904. // Implementation of class Reader
  905. // ////////////////////////////////
  906. // exact copy of Reader, renamed to OurReader
  907. class OurReader {
  908. public:
  909. typedef char Char;
  910. typedef const Char* Location;
  911. struct StructuredError {
  912. size_t offset_start;
  913. size_t offset_limit;
  914. std::string message;
  915. };
  916. OurReader(OurFeatures const& features);
  917. bool parse(const char* beginDoc,
  918. const char* endDoc,
  919. Value& root,
  920. bool collectComments = true);
  921. std::string getFormattedErrorMessages() const;
  922. private:
  923. OurReader(OurReader const&); // no impl
  924. void operator=(OurReader const&); // no impl
  925. enum TokenType {
  926. tokenEndOfStream = 0,
  927. tokenObjectBegin,
  928. tokenObjectEnd,
  929. tokenArrayBegin,
  930. tokenArrayEnd,
  931. tokenString,
  932. tokenNumber,
  933. tokenTrue,
  934. tokenFalse,
  935. tokenNull,
  936. tokenNaN,
  937. tokenPosInf,
  938. tokenNegInf,
  939. tokenArraySeparator,
  940. tokenMemberSeparator,
  941. tokenComment,
  942. tokenError
  943. };
  944. class Token {
  945. public:
  946. TokenType type_;
  947. Location start_;
  948. Location end_;
  949. };
  950. class ErrorInfo {
  951. public:
  952. Token token_;
  953. std::string message_;
  954. Location extra_;
  955. };
  956. typedef std::deque<ErrorInfo> Errors;
  957. bool readToken(Token& token);
  958. void skipSpaces();
  959. bool match(Location pattern, int patternLength);
  960. bool readComment();
  961. bool readCStyleComment();
  962. bool readCppStyleComment();
  963. bool readString();
  964. bool readStringSingleQuote();
  965. bool readNumber(bool checkInf);
  966. bool readValue();
  967. bool readObject(Token& token);
  968. bool readArray(Token& token);
  969. bool decodeNumber(Token& token);
  970. bool decodeNumber(Token& token, Value& decoded);
  971. bool decodeString(Token& token);
  972. bool decodeString(Token& token, std::string& decoded);
  973. bool decodeDouble(Token& token);
  974. bool decodeDouble(Token& token, Value& decoded);
  975. bool decodeUnicodeCodePoint(Token& token,
  976. Location& current,
  977. Location end,
  978. unsigned int& unicode);
  979. bool decodeUnicodeEscapeSequence(Token& token,
  980. Location& current,
  981. Location end,
  982. unsigned int& unicode);
  983. bool addError(const std::string& message, Token& token, Location extra = 0);
  984. bool recoverFromError(TokenType skipUntilToken);
  985. bool addErrorAndRecover(const std::string& message,
  986. Token& token,
  987. TokenType skipUntilToken);
  988. void skipUntilSpace();
  989. Value& currentValue();
  990. Char getNextChar();
  991. void
  992. getLocationLineAndColumn(Location location, int& line, int& column) const;
  993. std::string getLocationLineAndColumn(Location location) const;
  994. void addComment(Location begin, Location end, CommentPlacement placement);
  995. void skipCommentTokens(Token& token);
  996. typedef std::stack<Value*> Nodes;
  997. Nodes nodes_;
  998. Errors errors_;
  999. std::string document_;
  1000. Location begin_;
  1001. Location end_;
  1002. Location current_;
  1003. Location lastValueEnd_;
  1004. Value* lastValue_;
  1005. std::string commentsBefore_;
  1006. int stackDepth_;
  1007. OurFeatures const features_;
  1008. bool collectComments_;
  1009. }; // OurReader
  1010. // complete copy of Read impl, for OurReader
  1011. OurReader::OurReader(OurFeatures const& features)
  1012. : errors_(), document_(), begin_(), end_(), current_(), lastValueEnd_(),
  1013. lastValue_(), commentsBefore_(), features_(features), collectComments_() {
  1014. }
  1015. bool OurReader::parse(const char* beginDoc,
  1016. const char* endDoc,
  1017. Value& root,
  1018. bool collectComments) {
  1019. if (!features_.allowComments_) {
  1020. collectComments = false;
  1021. }
  1022. begin_ = beginDoc;
  1023. end_ = endDoc;
  1024. collectComments_ = collectComments;
  1025. current_ = begin_;
  1026. lastValueEnd_ = 0;
  1027. lastValue_ = 0;
  1028. commentsBefore_ = "";
  1029. errors_.clear();
  1030. while (!nodes_.empty())
  1031. nodes_.pop();
  1032. nodes_.push(&root);
  1033. stackDepth_ = 0;
  1034. bool successful = readValue();
  1035. Token token;
  1036. skipCommentTokens(token);
  1037. if (features_.failIfExtra_) {
  1038. if (token.type_ != tokenError && token.type_ != tokenEndOfStream) {
  1039. addError("Extra non-whitespace after JSON value.", token);
  1040. return false;
  1041. }
  1042. }
  1043. if (collectComments_ && !commentsBefore_.empty())
  1044. root.setComment(commentsBefore_, commentAfter);
  1045. if (features_.strictRoot_) {
  1046. if (!root.isArray() && !root.isObject()) {
  1047. // Set error location to start of doc, ideally should be first token found
  1048. // in doc
  1049. token.type_ = tokenError;
  1050. token.start_ = beginDoc;
  1051. token.end_ = endDoc;
  1052. addError(
  1053. "A valid JSON document must be either an array or an object value.",
  1054. token);
  1055. return false;
  1056. }
  1057. }
  1058. return successful;
  1059. }
  1060. bool OurReader::readValue() {
  1061. if (stackDepth_ >= features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue().");
  1062. ++stackDepth_;
  1063. Token token;
  1064. skipCommentTokens(token);
  1065. bool successful = true;
  1066. if (collectComments_ && !commentsBefore_.empty()) {
  1067. currentValue().setComment(commentsBefore_, commentBefore);
  1068. commentsBefore_ = "";
  1069. }
  1070. switch (token.type_) {
  1071. case tokenObjectBegin:
  1072. successful = readObject(token);
  1073. break;
  1074. case tokenArrayBegin:
  1075. successful = readArray(token);
  1076. break;
  1077. case tokenNumber:
  1078. successful = decodeNumber(token);
  1079. break;
  1080. case tokenString:
  1081. successful = decodeString(token);
  1082. break;
  1083. case tokenTrue:
  1084. {
  1085. Value v(true);
  1086. currentValue().swapPayload(v);
  1087. }
  1088. break;
  1089. case tokenFalse:
  1090. {
  1091. Value v(false);
  1092. currentValue().swapPayload(v);
  1093. }
  1094. break;
  1095. case tokenNull:
  1096. {
  1097. Value v;
  1098. currentValue().swapPayload(v);
  1099. }
  1100. break;
  1101. case tokenNaN:
  1102. {
  1103. Value v(std::numeric_limits<double>::quiet_NaN());
  1104. currentValue().swapPayload(v);
  1105. }
  1106. break;
  1107. case tokenPosInf:
  1108. {
  1109. Value v(std::numeric_limits<double>::infinity());
  1110. currentValue().swapPayload(v);
  1111. }
  1112. break;
  1113. case tokenNegInf:
  1114. {
  1115. Value v(-std::numeric_limits<double>::infinity());
  1116. currentValue().swapPayload(v);
  1117. }
  1118. break;
  1119. case tokenArraySeparator:
  1120. case tokenObjectEnd:
  1121. case tokenArrayEnd:
  1122. if (features_.allowDroppedNullPlaceholders_) {
  1123. // "Un-read" the current token and mark the current value as a null
  1124. // token.
  1125. current_--;
  1126. Value v;
  1127. currentValue().swapPayload(v);
  1128. break;
  1129. } // else, fall through ...
  1130. default:
  1131. return addError("Syntax error: value, object or array expected.", token);
  1132. }
  1133. if (collectComments_) {
  1134. lastValueEnd_ = current_;
  1135. lastValue_ = &currentValue();
  1136. }
  1137. --stackDepth_;
  1138. return successful;
  1139. }
  1140. void OurReader::skipCommentTokens(Token& token) {
  1141. if (features_.allowComments_) {
  1142. do {
  1143. readToken(token);
  1144. } while (token.type_ == tokenComment);
  1145. } else {
  1146. readToken(token);
  1147. }
  1148. }
  1149. bool OurReader::readToken(Token& token) {
  1150. skipSpaces();
  1151. token.start_ = current_;
  1152. Char c = getNextChar();
  1153. bool ok = true;
  1154. switch (c) {
  1155. case '{':
  1156. token.type_ = tokenObjectBegin;
  1157. break;
  1158. case '}':
  1159. token.type_ = tokenObjectEnd;
  1160. break;
  1161. case '[':
  1162. token.type_ = tokenArrayBegin;
  1163. break;
  1164. case ']':
  1165. token.type_ = tokenArrayEnd;
  1166. break;
  1167. case '"':
  1168. token.type_ = tokenString;
  1169. ok = readString();
  1170. break;
  1171. case '\'':
  1172. if (features_.allowSingleQuotes_) {
  1173. token.type_ = tokenString;
  1174. ok = readStringSingleQuote();
  1175. break;
  1176. } // else continue
  1177. case '/':
  1178. token.type_ = tokenComment;
  1179. ok = readComment();
  1180. break;
  1181. case '0':
  1182. case '1':
  1183. case '2':
  1184. case '3':
  1185. case '4':
  1186. case '5':
  1187. case '6':
  1188. case '7':
  1189. case '8':
  1190. case '9':
  1191. token.type_ = tokenNumber;
  1192. readNumber(false);
  1193. break;
  1194. case '-':
  1195. if (readNumber(true)) {
  1196. token.type_ = tokenNumber;
  1197. } else {
  1198. token.type_ = tokenNegInf;
  1199. ok = features_.allowSpecialFloats_ && match("nfinity", 7);
  1200. }
  1201. break;
  1202. case 't':
  1203. token.type_ = tokenTrue;
  1204. ok = match("rue", 3);
  1205. break;
  1206. case 'f':
  1207. token.type_ = tokenFalse;
  1208. ok = match("alse", 4);
  1209. break;
  1210. case 'n':
  1211. token.type_ = tokenNull;
  1212. ok = match("ull", 3);
  1213. break;
  1214. case 'N':
  1215. if (features_.allowSpecialFloats_) {
  1216. token.type_ = tokenNaN;
  1217. ok = match("aN", 2);
  1218. } else {
  1219. ok = false;
  1220. }
  1221. break;
  1222. case 'I':
  1223. if (features_.allowSpecialFloats_) {
  1224. token.type_ = tokenPosInf;
  1225. ok = match("nfinity", 7);
  1226. } else {
  1227. ok = false;
  1228. }
  1229. break;
  1230. case ',':
  1231. token.type_ = tokenArraySeparator;
  1232. break;
  1233. case ':':
  1234. token.type_ = tokenMemberSeparator;
  1235. break;
  1236. case 0:
  1237. token.type_ = tokenEndOfStream;
  1238. break;
  1239. default:
  1240. ok = false;
  1241. break;
  1242. }
  1243. if (!ok)
  1244. token.type_ = tokenError;
  1245. token.end_ = current_;
  1246. return true;
  1247. }
  1248. void OurReader::skipSpaces() {
  1249. while (current_ != end_) {
  1250. Char c = *current_;
  1251. if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
  1252. ++current_;
  1253. else
  1254. break;
  1255. }
  1256. }
  1257. bool OurReader::match(Location pattern, int patternLength) {
  1258. if (end_ - current_ < patternLength)
  1259. return false;
  1260. int index = patternLength;
  1261. while (index--)
  1262. if (current_[index] != pattern[index])
  1263. return false;
  1264. current_ += patternLength;
  1265. return true;
  1266. }
  1267. bool OurReader::readComment() {
  1268. Location commentBegin = current_ - 1;
  1269. Char c = getNextChar();
  1270. bool successful = false;
  1271. if (c == '*')
  1272. successful = readCStyleComment();
  1273. else if (c == '/')
  1274. successful = readCppStyleComment();
  1275. if (!successful)
  1276. return false;
  1277. if (collectComments_) {
  1278. CommentPlacement placement = commentBefore;
  1279. if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) {
  1280. if (c != '*' || !containsNewLine(commentBegin, current_))
  1281. placement = commentAfterOnSameLine;
  1282. }
  1283. addComment(commentBegin, current_, placement);
  1284. }
  1285. return true;
  1286. }
  1287. void
  1288. OurReader::addComment(Location begin, Location end, CommentPlacement placement) {
  1289. assert(collectComments_);
  1290. const std::string& normalized = normalizeEOL(begin, end);
  1291. if (placement == commentAfterOnSameLine) {
  1292. assert(lastValue_ != 0);
  1293. lastValue_->setComment(normalized, placement);
  1294. } else {
  1295. commentsBefore_ += normalized;
  1296. }
  1297. }
  1298. bool OurReader::readCStyleComment() {
  1299. while (current_ != end_) {
  1300. Char c = getNextChar();
  1301. if (c == '*' && *current_ == '/')
  1302. break;
  1303. }
  1304. return getNextChar() == '/';
  1305. }
  1306. bool OurReader::readCppStyleComment() {
  1307. while (current_ != end_) {
  1308. Char c = getNextChar();
  1309. if (c == '\n')
  1310. break;
  1311. if (c == '\r') {
  1312. // Consume DOS EOL. It will be normalized in addComment.
  1313. if (current_ != end_ && *current_ == '\n')
  1314. getNextChar();
  1315. // Break on Moc OS 9 EOL.
  1316. break;
  1317. }
  1318. }
  1319. return true;
  1320. }
  1321. bool OurReader::readNumber(bool checkInf) {
  1322. const char *p = current_;
  1323. if (checkInf && p != end_ && *p == 'I') {
  1324. current_ = ++p;
  1325. return false;
  1326. }
  1327. char c = '0'; // stopgap for already consumed character
  1328. // integral part
  1329. while (c >= '0' && c <= '9')
  1330. c = (current_ = p) < end_ ? *p++ : 0;
  1331. // fractional part
  1332. if (c == '.') {
  1333. c = (current_ = p) < end_ ? *p++ : 0;
  1334. while (c >= '0' && c <= '9')
  1335. c = (current_ = p) < end_ ? *p++ : 0;
  1336. }
  1337. // exponential part
  1338. if (c == 'e' || c == 'E') {
  1339. c = (current_ = p) < end_ ? *p++ : 0;
  1340. if (c == '+' || c == '-')
  1341. c = (current_ = p) < end_ ? *p++ : 0;
  1342. while (c >= '0' && c <= '9')
  1343. c = (current_ = p) < end_ ? *p++ : 0;
  1344. }
  1345. return true;
  1346. }
  1347. bool OurReader::readString() {
  1348. Char c = 0;
  1349. while (current_ != end_) {
  1350. c = getNextChar();
  1351. if (c == '\\')
  1352. getNextChar();
  1353. else if (c == '"')
  1354. break;
  1355. }
  1356. return c == '"';
  1357. }
  1358. bool OurReader::readStringSingleQuote() {
  1359. Char c = 0;
  1360. while (current_ != end_) {
  1361. c = getNextChar();
  1362. if (c == '\\')
  1363. getNextChar();
  1364. else if (c == '\'')
  1365. break;
  1366. }
  1367. return c == '\'';
  1368. }
  1369. bool OurReader::readObject(Token& /*tokenStart*/) {
  1370. Token tokenName;
  1371. std::string name;
  1372. Value init(objectValue);
  1373. currentValue().swapPayload(init);
  1374. while (readToken(tokenName)) {
  1375. bool initialTokenOk = true;
  1376. while (tokenName.type_ == tokenComment && initialTokenOk)
  1377. initialTokenOk = readToken(tokenName);
  1378. if (!initialTokenOk)
  1379. break;
  1380. if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object
  1381. return true;
  1382. name = "";
  1383. if (tokenName.type_ == tokenString) {
  1384. if (!decodeString(tokenName, name))
  1385. return recoverFromError(tokenObjectEnd);
  1386. } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) {
  1387. Value numberName;
  1388. if (!decodeNumber(tokenName, numberName))
  1389. return recoverFromError(tokenObjectEnd);
  1390. name = numberName.asString();
  1391. } else {
  1392. break;
  1393. }
  1394. Token colon;
  1395. if (!readToken(colon) || colon.type_ != tokenMemberSeparator) {
  1396. return addErrorAndRecover(
  1397. "Missing ':' after object member name", colon, tokenObjectEnd);
  1398. }
  1399. if (name.length() >= (1U<<30)) throwRuntimeError("keylength >= 2^30");
  1400. if (features_.rejectDupKeys_ && currentValue().isMember(name)) {
  1401. std::string msg = "Duplicate key: '" + name + "'";
  1402. return addErrorAndRecover(
  1403. msg, tokenName, tokenObjectEnd);
  1404. }
  1405. Value& value = currentValue()[name];
  1406. nodes_.push(&value);
  1407. bool ok = readValue();
  1408. nodes_.pop();
  1409. if (!ok) // error already set
  1410. return recoverFromError(tokenObjectEnd);
  1411. Token comma;
  1412. if (!readToken(comma) ||
  1413. (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator &&
  1414. comma.type_ != tokenComment)) {
  1415. return addErrorAndRecover(
  1416. "Missing ',' or '}' in object declaration", comma, tokenObjectEnd);
  1417. }
  1418. bool finalizeTokenOk = true;
  1419. while (comma.type_ == tokenComment && finalizeTokenOk)
  1420. finalizeTokenOk = readToken(comma);
  1421. if (comma.type_ == tokenObjectEnd)
  1422. return true;
  1423. }
  1424. return addErrorAndRecover(
  1425. "Missing '}' or object member name", tokenName, tokenObjectEnd);
  1426. }
  1427. bool OurReader::readArray(Token& /*tokenStart*/) {
  1428. Value init(arrayValue);
  1429. currentValue().swapPayload(init);
  1430. skipSpaces();
  1431. if (*current_ == ']') // empty array
  1432. {
  1433. Token endArray;
  1434. readToken(endArray);
  1435. return true;
  1436. }
  1437. int index = 0;
  1438. for (;;) {
  1439. Value& value = currentValue()[index++];
  1440. nodes_.push(&value);
  1441. bool ok = readValue();
  1442. nodes_.pop();
  1443. if (!ok) // error already set
  1444. return recoverFromError(tokenArrayEnd);
  1445. Token token;
  1446. // Accept Comment after last item in the array.
  1447. ok = readToken(token);
  1448. while (token.type_ == tokenComment && ok) {
  1449. ok = readToken(token);
  1450. }
  1451. bool badTokenType =
  1452. (token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd);
  1453. if (!ok || badTokenType) {
  1454. return addErrorAndRecover(
  1455. "Missing ',' or ']' in array declaration", token, tokenArrayEnd);
  1456. }
  1457. if (token.type_ == tokenArrayEnd)
  1458. break;
  1459. }
  1460. return true;
  1461. }
  1462. bool OurReader::decodeNumber(Token& token) {
  1463. Value decoded;
  1464. if (!decodeNumber(token, decoded))
  1465. return false;
  1466. currentValue().swapPayload(decoded);
  1467. return true;
  1468. }
  1469. bool OurReader::decodeNumber(Token& token, Value& decoded) {
  1470. // Attempts to parse the number as an integer. If the number is
  1471. // larger than the maximum supported value of an integer then
  1472. // we decode the number as a double.
  1473. Location current = token.start_;
  1474. bool isNegative = *current == '-';
  1475. if (isNegative)
  1476. ++current;
  1477. // TODO: Help the compiler do the div and mod at compile time or get rid of them.
  1478. Value::LargestUInt maxIntegerValue =
  1479. isNegative ? Value::LargestUInt(-Value::minLargestInt)
  1480. : Value::maxLargestUInt;
  1481. Value::LargestUInt threshold = maxIntegerValue / 10;
  1482. Value::LargestUInt value = 0;
  1483. while (current < token.end_) {
  1484. Char c = *current++;
  1485. if (c < '0' || c > '9')
  1486. return decodeDouble(token, decoded);
  1487. Value::UInt digit(c - '0');
  1488. if (value >= threshold) {
  1489. // We've hit or exceeded the max value divided by 10 (rounded down). If
  1490. // a) we've only just touched the limit, b) this is the last digit, and
  1491. // c) it's small enough to fit in that rounding delta, we're okay.
  1492. // Otherwise treat this number as a double to avoid overflow.
  1493. if (value > threshold || current != token.end_ ||
  1494. digit > maxIntegerValue % 10) {
  1495. return decodeDouble(token, decoded);
  1496. }
  1497. }
  1498. value = value * 10 + digit;
  1499. }
  1500. if (isNegative)
  1501. decoded = -Value::LargestInt(value);
  1502. else if (value <= Value::LargestUInt(Value::maxInt))
  1503. decoded = Value::LargestInt(value);
  1504. else
  1505. decoded = value;
  1506. return true;
  1507. }
  1508. bool OurReader::decodeDouble(Token& token) {
  1509. Value decoded;
  1510. if (!decodeDouble(token, decoded))
  1511. return false;
  1512. currentValue().swapPayload(decoded);
  1513. return true;
  1514. }
  1515. bool OurReader::decodeDouble(Token& token, Value& decoded) {
  1516. double value = 0;
  1517. std::string buffer( token.start_, token.end_ );
  1518. std::istringstream is(buffer);
  1519. if (!(is >> value))
  1520. return addError("'" + std::string(token.start_, token.end_) +
  1521. "' is not a number.",
  1522. token);
  1523. decoded = value;
  1524. return true;
  1525. }
  1526. bool OurReader::decodeString(Token& token) {
  1527. std::string decoded_string;
  1528. if (!decodeString(token, decoded_string))
  1529. return false;
  1530. Value decoded(decoded_string);
  1531. currentValue().swapPayload(decoded);
  1532. return true;
  1533. }
  1534. bool OurReader::decodeString(Token& token, std::string& decoded) {
  1535. decoded.reserve(token.end_ - token.start_ - 2);
  1536. Location current = token.start_ + 1; // skip '"'
  1537. Location end = token.end_ - 1; // do not include '"'
  1538. while (current != end) {
  1539. Char c = *current++;
  1540. if (c == '"')
  1541. break;
  1542. else if (c == '\\') {
  1543. if (current == end)
  1544. return addError("Empty escape sequence in string", token, current);
  1545. Char escape = *current++;
  1546. switch (escape) {
  1547. case '"':
  1548. decoded += '"';
  1549. break;
  1550. case '/':
  1551. decoded += '/';
  1552. break;
  1553. case '\\':
  1554. decoded += '\\';
  1555. break;
  1556. case 'b':
  1557. decoded += '\b';
  1558. break;
  1559. case 'f':
  1560. decoded += '\f';
  1561. break;
  1562. case 'n':
  1563. decoded += '\n';
  1564. break;
  1565. case 'r':
  1566. decoded += '\r';
  1567. break;
  1568. case 't':
  1569. decoded += '\t';
  1570. break;
  1571. case 'u': {
  1572. unsigned int unicode;
  1573. if (!decodeUnicodeCodePoint(token, current, end, unicode))
  1574. return false;
  1575. decoded += codePointToUTF8(unicode);
  1576. } break;
  1577. default:
  1578. return addError("Bad escape sequence in string", token, current);
  1579. }
  1580. } else {
  1581. decoded += c;
  1582. }
  1583. }
  1584. return true;
  1585. }
  1586. bool OurReader::decodeUnicodeCodePoint(Token& token,
  1587. Location& current,
  1588. Location end,
  1589. unsigned int& unicode) {
  1590. if (!decodeUnicodeEscapeSequence(token, current, end, unicode))
  1591. return false;
  1592. if (unicode >= 0xD800 && unicode <= 0xDBFF) {
  1593. // surrogate pairs
  1594. if (end - current < 6)
  1595. return addError(
  1596. "additional six characters expected to parse unicode surrogate pair.",
  1597. token,
  1598. current);
  1599. unsigned int surrogatePair;
  1600. if (*(current++) == '\\' && *(current++) == 'u') {
  1601. if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) {
  1602. unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
  1603. } else
  1604. return false;
  1605. } else
  1606. return addError("expecting another \\u token to begin the second half of "
  1607. "a unicode surrogate pair",
  1608. token,
  1609. current);
  1610. }
  1611. return true;
  1612. }
  1613. bool OurReader::decodeUnicodeEscapeSequence(Token& token,
  1614. Location& current,
  1615. Location end,
  1616. unsigned int& unicode) {
  1617. if (end - current < 4)
  1618. return addError(
  1619. "Bad unicode escape sequence in string: four digits expected.",
  1620. token,
  1621. current);
  1622. unicode = 0;
  1623. for (int index = 0; index < 4; ++index) {
  1624. Char c = *current++;
  1625. unicode *= 16;
  1626. if (c >= '0' && c <= '9')
  1627. unicode += c - '0';
  1628. else if (c >= 'a' && c <= 'f')
  1629. unicode += c - 'a' + 10;
  1630. else if (c >= 'A' && c <= 'F')
  1631. unicode += c - 'A' + 10;
  1632. else
  1633. return addError(
  1634. "Bad unicode escape sequence in string: hexadecimal digit expected.",
  1635. token,
  1636. current);
  1637. }
  1638. return true;
  1639. }
  1640. bool
  1641. OurReader::addError(const std::string& message, Token& token, Location extra) {
  1642. ErrorInfo info;
  1643. info.token_ = token;
  1644. info.message_ = message;
  1645. info.extra_ = extra;
  1646. errors_.push_back(info);
  1647. return false;
  1648. }
  1649. bool OurReader::recoverFromError(TokenType skipUntilToken) {
  1650. int errorCount = int(errors_.size());
  1651. Token skip;
  1652. for (;;) {
  1653. if (!readToken(skip))
  1654. errors_.resize(errorCount); // discard errors caused by recovery
  1655. if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream)
  1656. break;
  1657. }
  1658. errors_.resize(errorCount);
  1659. return false;
  1660. }
  1661. bool OurReader::addErrorAndRecover(const std::string& message,
  1662. Token& token,
  1663. TokenType skipUntilToken) {
  1664. addError(message, token);
  1665. return recoverFromError(skipUntilToken);
  1666. }
  1667. Value& OurReader::currentValue() { return *(nodes_.top()); }
  1668. OurReader::Char OurReader::getNextChar() {
  1669. if (current_ == end_)
  1670. return 0;
  1671. return *current_++;
  1672. }
  1673. void OurReader::getLocationLineAndColumn(Location location,
  1674. int& line,
  1675. int& column) const {
  1676. Location current = begin_;
  1677. Location lastLineStart = current;
  1678. line = 0;
  1679. while (current < location && current != end_) {
  1680. Char c = *current++;
  1681. if (c == '\r') {
  1682. if (*current == '\n')
  1683. ++current;
  1684. lastLineStart = current;
  1685. ++line;
  1686. } else if (c == '\n') {
  1687. lastLineStart = current;
  1688. ++line;
  1689. }
  1690. }
  1691. // column & line start at 1
  1692. column = int(location - lastLineStart) + 1;
  1693. ++line;
  1694. }
  1695. std::string OurReader::getLocationLineAndColumn(Location location) const {
  1696. int line, column;
  1697. getLocationLineAndColumn(location, line, column);
  1698. char buffer[18 + 16 + 16 + 1];
  1699. snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
  1700. return buffer;
  1701. }
  1702. std::string OurReader::getFormattedErrorMessages() const {
  1703. std::string formattedMessage;
  1704. for (Errors::const_iterator itError = errors_.begin();
  1705. itError != errors_.end();
  1706. ++itError) {
  1707. const ErrorInfo& error = *itError;
  1708. formattedMessage +=
  1709. "* " + getLocationLineAndColumn(error.token_.start_) + "\n";
  1710. formattedMessage += " " + error.message_ + "\n";
  1711. if (error.extra_)
  1712. formattedMessage +=
  1713. "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n";
  1714. }
  1715. return formattedMessage;
  1716. }
  1717. class OurCharReader : public CharReader {
  1718. bool const collectComments_;
  1719. OurReader reader_;
  1720. public:
  1721. OurCharReader(
  1722. bool collectComments,
  1723. OurFeatures const& features)
  1724. : collectComments_(collectComments)
  1725. , reader_(features)
  1726. {}
  1727. virtual bool parse(
  1728. char const* beginDoc, char const* endDoc,
  1729. Value* root, std::string* errs) {
  1730. bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_);
  1731. if (errs) {
  1732. *errs = reader_.getFormattedErrorMessages();
  1733. }
  1734. return ok;
  1735. }
  1736. };
  1737. CharReaderBuilder::CharReaderBuilder()
  1738. {
  1739. setDefaults(&settings_);
  1740. }
  1741. CharReaderBuilder::~CharReaderBuilder()
  1742. {}
  1743. CharReader* CharReaderBuilder::newCharReader() const
  1744. {
  1745. bool collectComments = settings_["collectComments"].asBool();
  1746. OurFeatures features = OurFeatures::all();
  1747. features.allowComments_ = settings_["allowComments"].asBool();
  1748. features.strictRoot_ = settings_["strictRoot"].asBool();
  1749. features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool();
  1750. features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool();
  1751. features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool();
  1752. features.stackLimit_ = settings_["stackLimit"].asInt();
  1753. features.failIfExtra_ = settings_["failIfExtra"].asBool();
  1754. features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool();
  1755. features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool();
  1756. return new OurCharReader(collectComments, features);
  1757. }
  1758. static void getValidReaderKeys(std::set<std::string>* valid_keys)
  1759. {
  1760. valid_keys->clear();
  1761. valid_keys->insert("collectComments");
  1762. valid_keys->insert("allowComments");
  1763. valid_keys->insert("strictRoot");
  1764. valid_keys->insert("allowDroppedNullPlaceholders");
  1765. valid_keys->insert("allowNumericKeys");
  1766. valid_keys->insert("allowSingleQuotes");
  1767. valid_keys->insert("stackLimit");
  1768. valid_keys->insert("failIfExtra");
  1769. valid_keys->insert("rejectDupKeys");
  1770. valid_keys->insert("allowSpecialFloats");
  1771. }
  1772. bool CharReaderBuilder::validate(Json::Value* invalid) const
  1773. {
  1774. Json::Value my_invalid;
  1775. if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
  1776. Json::Value& inv = *invalid;
  1777. std::set<std::string> valid_keys;
  1778. getValidReaderKeys(&valid_keys);
  1779. Value::Members keys = settings_.getMemberNames();
  1780. size_t n = keys.size();
  1781. for (size_t i = 0; i < n; ++i) {
  1782. std::string const& key = keys[i];
  1783. if (valid_keys.find(key) == valid_keys.end()) {
  1784. inv[key] = settings_[key];
  1785. }
  1786. }
  1787. return 0u == inv.size();
  1788. }
  1789. Value& CharReaderBuilder::operator[](std::string key)
  1790. {
  1791. return settings_[key];
  1792. }
  1793. // static
  1794. void CharReaderBuilder::strictMode(Json::Value* settings)
  1795. {
  1796. //! [CharReaderBuilderStrictMode]
  1797. (*settings)["allowComments"] = false;
  1798. (*settings)["strictRoot"] = true;
  1799. (*settings)["allowDroppedNullPlaceholders"] = false;
  1800. (*settings)["allowNumericKeys"] = false;
  1801. (*settings)["allowSingleQuotes"] = false;
  1802. (*settings)["failIfExtra"] = true;
  1803. (*settings)["rejectDupKeys"] = true;
  1804. (*settings)["allowSpecialFloats"] = false;
  1805. //! [CharReaderBuilderStrictMode]
  1806. }
  1807. // static
  1808. void CharReaderBuilder::setDefaults(Json::Value* settings)
  1809. {
  1810. //! [CharReaderBuilderDefaults]
  1811. (*settings)["collectComments"] = true;
  1812. (*settings)["allowComments"] = true;
  1813. (*settings)["strictRoot"] = false;
  1814. (*settings)["allowDroppedNullPlaceholders"] = false;
  1815. (*settings)["allowNumericKeys"] = false;
  1816. (*settings)["allowSingleQuotes"] = false;
  1817. (*settings)["stackLimit"] = 1000;
  1818. (*settings)["failIfExtra"] = false;
  1819. (*settings)["rejectDupKeys"] = false;
  1820. (*settings)["allowSpecialFloats"] = false;
  1821. //! [CharReaderBuilderDefaults]
  1822. }
  1823. //////////////////////////////////
  1824. // global functions
  1825. bool parseFromStream(
  1826. CharReader::Factory const& fact, std::istream& sin,
  1827. Value* root, std::string* errs)
  1828. {
  1829. std::ostringstream ssin;
  1830. ssin << sin.rdbuf();
  1831. std::string doc = ssin.str();
  1832. char const* begin = doc.data();
  1833. char const* end = begin + doc.size();
  1834. // Note that we do not actually need a null-terminator.
  1835. CharReaderPtr const reader(fact.newCharReader());
  1836. return reader->parse(begin, end, root, errs);
  1837. }
  1838. std::istream& operator>>(std::istream& sin, Value& root) {
  1839. CharReaderBuilder b;
  1840. std::string errs;
  1841. bool ok = parseFromStream(b, sin, &root, &errs);
  1842. if (!ok) {
  1843. fprintf(stderr,
  1844. "Error from reader: %s",
  1845. errs.c_str());
  1846. throwRuntimeError("reader error");
  1847. }
  1848. return sin;
  1849. }
  1850. } // namespace Json
  1851. // //////////////////////////////////////////////////////////////////////
  1852. // End of content of file: src/lib_json/json_reader.cpp
  1853. // //////////////////////////////////////////////////////////////////////
  1854. // //////////////////////////////////////////////////////////////////////
  1855. // Beginning of content of file: src/lib_json/json_valueiterator.inl
  1856. // //////////////////////////////////////////////////////////////////////
  1857. // Copyright 2007-2010 Baptiste Lepilleur
  1858. // Distributed under MIT license, or public domain if desired and
  1859. // recognized in your jurisdiction.
  1860. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  1861. // included by json_value.cpp
  1862. namespace Json {
  1863. // //////////////////////////////////////////////////////////////////
  1864. // //////////////////////////////////////////////////////////////////
  1865. // //////////////////////////////////////////////////////////////////
  1866. // class ValueIteratorBase
  1867. // //////////////////////////////////////////////////////////////////
  1868. // //////////////////////////////////////////////////////////////////
  1869. // //////////////////////////////////////////////////////////////////
  1870. ValueIteratorBase::ValueIteratorBase()
  1871. : current_(), isNull_(true) {
  1872. }
  1873. ValueIteratorBase::ValueIteratorBase(
  1874. const Value::ObjectValues::iterator& current)
  1875. : current_(current), isNull_(false) {}
  1876. Value& ValueIteratorBase::deref() const {
  1877. return current_->second;
  1878. }
  1879. void ValueIteratorBase::increment() {
  1880. ++current_;
  1881. }
  1882. void ValueIteratorBase::decrement() {
  1883. --current_;
  1884. }
  1885. ValueIteratorBase::difference_type
  1886. ValueIteratorBase::computeDistance(const SelfType& other) const {
  1887. #ifdef JSON_USE_CPPTL_SMALLMAP
  1888. return other.current_ - current_;
  1889. #else
  1890. // Iterator for null value are initialized using the default
  1891. // constructor, which initialize current_ to the default
  1892. // std::map::iterator. As begin() and end() are two instance
  1893. // of the default std::map::iterator, they can not be compared.
  1894. // To allow this, we handle this comparison specifically.
  1895. if (isNull_ && other.isNull_) {
  1896. return 0;
  1897. }
  1898. // Usage of std::distance is not portable (does not compile with Sun Studio 12
  1899. // RogueWave STL,
  1900. // which is the one used by default).
  1901. // Using a portable hand-made version for non random iterator instead:
  1902. // return difference_type( std::distance( current_, other.current_ ) );
  1903. difference_type myDistance = 0;
  1904. for (Value::ObjectValues::iterator it = current_; it != other.current_;
  1905. ++it) {
  1906. ++myDistance;
  1907. }
  1908. return myDistance;
  1909. #endif
  1910. }
  1911. bool ValueIteratorBase::isEqual(const SelfType& other) const {
  1912. if (isNull_) {
  1913. return other.isNull_;
  1914. }
  1915. return current_ == other.current_;
  1916. }
  1917. void ValueIteratorBase::copy(const SelfType& other) {
  1918. current_ = other.current_;
  1919. isNull_ = other.isNull_;
  1920. }
  1921. Value ValueIteratorBase::key() const {
  1922. const Value::CZString czstring = (*current_).first;
  1923. if (czstring.data()) {
  1924. if (czstring.isStaticString())
  1925. return Value(StaticString(czstring.data()));
  1926. return Value(czstring.data(), czstring.data() + czstring.length());
  1927. }
  1928. return Value(czstring.index());
  1929. }
  1930. UInt ValueIteratorBase::index() const {
  1931. const Value::CZString czstring = (*current_).first;
  1932. if (!czstring.data())
  1933. return czstring.index();
  1934. return Value::UInt(-1);
  1935. }
  1936. std::string ValueIteratorBase::name() const {
  1937. char const* keey;
  1938. char const* end;
  1939. keey = memberName(&end);
  1940. if (!keey) return std::string();
  1941. return std::string(keey, end);
  1942. }
  1943. char const* ValueIteratorBase::memberName() const {
  1944. const char* cname = (*current_).first.data();
  1945. return cname ? cname : "";
  1946. }
  1947. char const* ValueIteratorBase::memberName(char const** end) const {
  1948. const char* cname = (*current_).first.data();
  1949. if (!cname) {
  1950. *end = NULL;
  1951. return NULL;
  1952. }
  1953. *end = cname + (*current_).first.length();
  1954. return cname;
  1955. }
  1956. // //////////////////////////////////////////////////////////////////
  1957. // //////////////////////////////////////////////////////////////////
  1958. // //////////////////////////////////////////////////////////////////
  1959. // class ValueConstIterator
  1960. // //////////////////////////////////////////////////////////////////
  1961. // //////////////////////////////////////////////////////////////////
  1962. // //////////////////////////////////////////////////////////////////
  1963. ValueConstIterator::ValueConstIterator() {}
  1964. ValueConstIterator::ValueConstIterator(
  1965. const Value::ObjectValues::iterator& current)
  1966. : ValueIteratorBase(current) {}
  1967. ValueConstIterator& ValueConstIterator::
  1968. operator=(const ValueIteratorBase& other) {
  1969. copy(other);
  1970. return *this;
  1971. }
  1972. // //////////////////////////////////////////////////////////////////
  1973. // //////////////////////////////////////////////////////////////////
  1974. // //////////////////////////////////////////////////////////////////
  1975. // class ValueIterator
  1976. // //////////////////////////////////////////////////////////////////
  1977. // //////////////////////////////////////////////////////////////////
  1978. // //////////////////////////////////////////////////////////////////
  1979. ValueIterator::ValueIterator() {}
  1980. ValueIterator::ValueIterator(const Value::ObjectValues::iterator& current)
  1981. : ValueIteratorBase(current) {}
  1982. ValueIterator::ValueIterator(const ValueConstIterator& other)
  1983. : ValueIteratorBase(other) {}
  1984. ValueIterator::ValueIterator(const ValueIterator& other)
  1985. : ValueIteratorBase(other) {}
  1986. ValueIterator& ValueIterator::operator=(const SelfType& other) {
  1987. copy(other);
  1988. return *this;
  1989. }
  1990. } // namespace Json
  1991. // //////////////////////////////////////////////////////////////////////
  1992. // End of content of file: src/lib_json/json_valueiterator.inl
  1993. // //////////////////////////////////////////////////////////////////////
  1994. // //////////////////////////////////////////////////////////////////////
  1995. // Beginning of content of file: src/lib_json/json_value.cpp
  1996. // //////////////////////////////////////////////////////////////////////
  1997. // Copyright 2011 Baptiste Lepilleur
  1998. // Distributed under MIT license, or public domain if desired and
  1999. // recognized in your jurisdiction.
  2000. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  2001. #if !defined(JSON_IS_AMALGAMATION)
  2002. #include <json/assertions.h>
  2003. #include <json/value.h>
  2004. #include <json/writer.h>
  2005. #endif // if !defined(JSON_IS_AMALGAMATION)
  2006. #include <math.h>
  2007. #include <sstream>
  2008. #include <utility>
  2009. #include <cstring>
  2010. #include <cassert>
  2011. #ifdef JSON_USE_CPPTL
  2012. #include <cpptl/conststring.h>
  2013. #endif
  2014. #include <cstddef> // size_t
  2015. #include <algorithm> // min()
  2016. #if defined(__BORLANDC__)
  2017. #include <mem.h>
  2018. #endif
  2019. #define JSON_ASSERT_UNREACHABLE assert(false)
  2020. namespace Json {
  2021. // This is a walkaround to avoid the static initialization of Value::null.
  2022. // kNull must be word-aligned to avoid crashing on ARM. We use an alignment of
  2023. // 8 (instead of 4) as a bit of future-proofing.
  2024. #if defined(__ARMEL__)
  2025. #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
  2026. #else
  2027. // This exists for binary compatibility only. Use nullRef.
  2028. const Value Value::null;
  2029. #define ALIGNAS(byte_alignment)
  2030. #endif
  2031. static const unsigned char ALIGNAS(8) kNull[sizeof(Value)] = { 0 };
  2032. const unsigned char& kNullRef = kNull[0];
  2033. const Value& Value::nullRef = reinterpret_cast<const Value&>(kNullRef);
  2034. const Int Value::minInt = Int(~(UInt(-1) / 2));
  2035. const Int Value::maxInt = Int(UInt(-1) / 2);
  2036. const UInt Value::maxUInt = UInt(-1);
  2037. #if defined(JSON_HAS_INT64)
  2038. const Int64 Value::minInt64 = Int64(~(UInt64(-1) / 2));
  2039. const Int64 Value::maxInt64 = Int64(UInt64(-1) / 2);
  2040. const UInt64 Value::maxUInt64 = UInt64(-1);
  2041. // The constant is hard-coded because some compiler have trouble
  2042. // converting Value::maxUInt64 to a double correctly (AIX/xlC).
  2043. // Assumes that UInt64 is a 64 bits integer.
  2044. static const double maxUInt64AsDouble = 18446744073709551615.0;
  2045. #endif // defined(JSON_HAS_INT64)
  2046. const LargestInt Value::minLargestInt = LargestInt(~(LargestUInt(-1) / 2));
  2047. const LargestInt Value::maxLargestInt = LargestInt(LargestUInt(-1) / 2);
  2048. const LargestUInt Value::maxLargestUInt = LargestUInt(-1);
  2049. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2050. template <typename T, typename U>
  2051. static inline bool InRange(double d, T min, U max) {
  2052. return d >= min && d <= max;
  2053. }
  2054. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2055. static inline double integerToDouble(Json::UInt64 value) {
  2056. return static_cast<double>(Int64(value / 2)) * 2.0 + Int64(value & 1);
  2057. }
  2058. template <typename T> static inline double integerToDouble(T value) {
  2059. return static_cast<double>(value);
  2060. }
  2061. template <typename T, typename U>
  2062. static inline bool InRange(double d, T min, U max) {
  2063. return d >= integerToDouble(min) && d <= integerToDouble(max);
  2064. }
  2065. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2066. /** Duplicates the specified string value.
  2067. * @param value Pointer to the string to duplicate. Must be zero-terminated if
  2068. * length is "unknown".
  2069. * @param length Length of the value. if equals to unknown, then it will be
  2070. * computed using strlen(value).
  2071. * @return Pointer on the duplicate instance of string.
  2072. */
  2073. static inline char* duplicateStringValue(const char* value,
  2074. size_t length) {
  2075. // Avoid an integer overflow in the call to malloc below by limiting length
  2076. // to a sane value.
  2077. if (length >= (size_t)Value::maxInt)
  2078. length = Value::maxInt - 1;
  2079. char* newString = static_cast<char*>(malloc(length + 1));
  2080. if (newString == NULL) {
  2081. throwRuntimeError(
  2082. "in Json::Value::duplicateStringValue(): "
  2083. "Failed to allocate string value buffer");
  2084. }
  2085. memcpy(newString, value, length);
  2086. newString[length] = 0;
  2087. return newString;
  2088. }
  2089. /* Record the length as a prefix.
  2090. */
  2091. static inline char* duplicateAndPrefixStringValue(
  2092. const char* value,
  2093. unsigned int length)
  2094. {
  2095. // Avoid an integer overflow in the call to malloc below by limiting length
  2096. // to a sane value.
  2097. JSON_ASSERT_MESSAGE(length <= (unsigned)Value::maxInt - sizeof(unsigned) - 1U,
  2098. "in Json::Value::duplicateAndPrefixStringValue(): "
  2099. "length too big for prefixing");
  2100. unsigned actualLength = length + static_cast<unsigned>(sizeof(unsigned)) + 1U;
  2101. char* newString = static_cast<char*>(malloc(actualLength));
  2102. if (newString == 0) {
  2103. throwRuntimeError(
  2104. "in Json::Value::duplicateAndPrefixStringValue(): "
  2105. "Failed to allocate string value buffer");
  2106. }
  2107. *reinterpret_cast<unsigned*>(newString) = length;
  2108. memcpy(newString + sizeof(unsigned), value, length);
  2109. newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later
  2110. return newString;
  2111. }
  2112. inline static void decodePrefixedString(
  2113. bool isPrefixed, char const* prefixed,
  2114. unsigned* length, char const** value)
  2115. {
  2116. if (!isPrefixed) {
  2117. *length = static_cast<unsigned>(strlen(prefixed));
  2118. *value = prefixed;
  2119. } else {
  2120. *length = *reinterpret_cast<unsigned const*>(prefixed);
  2121. *value = prefixed + sizeof(unsigned);
  2122. }
  2123. }
  2124. /** Free the string duplicated by duplicateStringValue()/duplicateAndPrefixStringValue().
  2125. */
  2126. static inline void releaseStringValue(char* value) { free(value); }
  2127. } // namespace Json
  2128. // //////////////////////////////////////////////////////////////////
  2129. // //////////////////////////////////////////////////////////////////
  2130. // //////////////////////////////////////////////////////////////////
  2131. // ValueInternals...
  2132. // //////////////////////////////////////////////////////////////////
  2133. // //////////////////////////////////////////////////////////////////
  2134. // //////////////////////////////////////////////////////////////////
  2135. #if !defined(JSON_IS_AMALGAMATION)
  2136. #include "json_valueiterator.inl"
  2137. #endif // if !defined(JSON_IS_AMALGAMATION)
  2138. namespace Json {
  2139. Exception::Exception(std::string const& msg)
  2140. : msg_(msg)
  2141. {}
  2142. Exception::~Exception() throw()
  2143. {}
  2144. char const* Exception::what() const throw()
  2145. {
  2146. return msg_.c_str();
  2147. }
  2148. RuntimeError::RuntimeError(std::string const& msg)
  2149. : Exception(msg)
  2150. {}
  2151. LogicError::LogicError(std::string const& msg)
  2152. : Exception(msg)
  2153. {}
  2154. JSONCPP_NORETURN void throwRuntimeError(std::string const& msg)
  2155. {
  2156. throw RuntimeError(msg);
  2157. }
  2158. JSONCPP_NORETURN void throwLogicError(std::string const& msg)
  2159. {
  2160. throw LogicError(msg);
  2161. }
  2162. // //////////////////////////////////////////////////////////////////
  2163. // //////////////////////////////////////////////////////////////////
  2164. // //////////////////////////////////////////////////////////////////
  2165. // class Value::CommentInfo
  2166. // //////////////////////////////////////////////////////////////////
  2167. // //////////////////////////////////////////////////////////////////
  2168. // //////////////////////////////////////////////////////////////////
  2169. Value::CommentInfo::CommentInfo() : comment_(0) {}
  2170. Value::CommentInfo::~CommentInfo() {
  2171. if (comment_)
  2172. releaseStringValue(comment_);
  2173. }
  2174. void Value::CommentInfo::setComment(const char* text, size_t len) {
  2175. if (comment_) {
  2176. releaseStringValue(comment_);
  2177. comment_ = 0;
  2178. }
  2179. JSON_ASSERT(text != 0);
  2180. JSON_ASSERT_MESSAGE(
  2181. text[0] == '\0' || text[0] == '/',
  2182. "in Json::Value::setComment(): Comments must start with /");
  2183. // It seems that /**/ style comments are acceptable as well.
  2184. comment_ = duplicateStringValue(text, len);
  2185. }
  2186. // //////////////////////////////////////////////////////////////////
  2187. // //////////////////////////////////////////////////////////////////
  2188. // //////////////////////////////////////////////////////////////////
  2189. // class Value::CZString
  2190. // //////////////////////////////////////////////////////////////////
  2191. // //////////////////////////////////////////////////////////////////
  2192. // //////////////////////////////////////////////////////////////////
  2193. // Notes: policy_ indicates if the string was allocated when
  2194. // a string is stored.
  2195. Value::CZString::CZString(ArrayIndex aindex) : cstr_(0), index_(aindex) {}
  2196. Value::CZString::CZString(char const* str, unsigned ulength, DuplicationPolicy allocate)
  2197. : cstr_(str)
  2198. {
  2199. // allocate != duplicate
  2200. storage_.policy_ = allocate & 0x3;
  2201. storage_.length_ = ulength & 0x3FFFFFFF;
  2202. }
  2203. Value::CZString::CZString(const CZString& other)
  2204. : cstr_(other.storage_.policy_ != noDuplication && other.cstr_ != 0
  2205. ? duplicateStringValue(other.cstr_, other.storage_.length_)
  2206. : other.cstr_)
  2207. {
  2208. storage_.policy_ = (other.cstr_
  2209. ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication
  2210. ? noDuplication : duplicate)
  2211. : static_cast<DuplicationPolicy>(other.storage_.policy_));
  2212. storage_.length_ = other.storage_.length_;
  2213. }
  2214. Value::CZString::~CZString() {
  2215. if (cstr_ && storage_.policy_ == duplicate)
  2216. releaseStringValue(const_cast<char*>(cstr_));
  2217. }
  2218. void Value::CZString::swap(CZString& other) {
  2219. std::swap(cstr_, other.cstr_);
  2220. std::swap(index_, other.index_);
  2221. }
  2222. Value::CZString& Value::CZString::operator=(CZString other) {
  2223. swap(other);
  2224. return *this;
  2225. }
  2226. bool Value::CZString::operator<(const CZString& other) const {
  2227. if (!cstr_) return index_ < other.index_;
  2228. //return strcmp(cstr_, other.cstr_) < 0;
  2229. // Assume both are strings.
  2230. unsigned this_len = this->storage_.length_;
  2231. unsigned other_len = other.storage_.length_;
  2232. unsigned min_len = std::min(this_len, other_len);
  2233. int comp = memcmp(this->cstr_, other.cstr_, min_len);
  2234. if (comp < 0) return true;
  2235. if (comp > 0) return false;
  2236. return (this_len < other_len);
  2237. }
  2238. bool Value::CZString::operator==(const CZString& other) const {
  2239. if (!cstr_) return index_ == other.index_;
  2240. //return strcmp(cstr_, other.cstr_) == 0;
  2241. // Assume both are strings.
  2242. unsigned this_len = this->storage_.length_;
  2243. unsigned other_len = other.storage_.length_;
  2244. if (this_len != other_len) return false;
  2245. int comp = memcmp(this->cstr_, other.cstr_, this_len);
  2246. return comp == 0;
  2247. }
  2248. ArrayIndex Value::CZString::index() const { return index_; }
  2249. //const char* Value::CZString::c_str() const { return cstr_; }
  2250. const char* Value::CZString::data() const { return cstr_; }
  2251. unsigned Value::CZString::length() const { return storage_.length_; }
  2252. bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; }
  2253. // //////////////////////////////////////////////////////////////////
  2254. // //////////////////////////////////////////////////////////////////
  2255. // //////////////////////////////////////////////////////////////////
  2256. // class Value::Value
  2257. // //////////////////////////////////////////////////////////////////
  2258. // //////////////////////////////////////////////////////////////////
  2259. // //////////////////////////////////////////////////////////////////
  2260. /*! \internal Default constructor initialization must be equivalent to:
  2261. * memset( this, 0, sizeof(Value) )
  2262. * This optimization is used in ValueInternalMap fast allocator.
  2263. */
  2264. Value::Value(ValueType vtype) {
  2265. initBasic(vtype);
  2266. switch (vtype) {
  2267. case nullValue:
  2268. break;
  2269. case intValue:
  2270. case uintValue:
  2271. value_.int_ = 0;
  2272. break;
  2273. case realValue:
  2274. value_.real_ = 0.0;
  2275. break;
  2276. case stringValue:
  2277. value_.string_ = 0;
  2278. break;
  2279. case arrayValue:
  2280. case objectValue:
  2281. value_.map_ = new ObjectValues();
  2282. break;
  2283. case booleanValue:
  2284. value_.bool_ = false;
  2285. break;
  2286. default:
  2287. JSON_ASSERT_UNREACHABLE;
  2288. }
  2289. }
  2290. Value::Value(Int value) {
  2291. initBasic(intValue);
  2292. value_.int_ = value;
  2293. }
  2294. Value::Value(UInt value) {
  2295. initBasic(uintValue);
  2296. value_.uint_ = value;
  2297. }
  2298. #if defined(JSON_HAS_INT64)
  2299. Value::Value(Int64 value) {
  2300. initBasic(intValue);
  2301. value_.int_ = value;
  2302. }
  2303. Value::Value(UInt64 value) {
  2304. initBasic(uintValue);
  2305. value_.uint_ = value;
  2306. }
  2307. #endif // defined(JSON_HAS_INT64)
  2308. Value::Value(double value) {
  2309. initBasic(realValue);
  2310. value_.real_ = value;
  2311. }
  2312. Value::Value(const char* value) {
  2313. initBasic(stringValue, true);
  2314. value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(strlen(value)));
  2315. }
  2316. Value::Value(const char* beginValue, const char* endValue) {
  2317. initBasic(stringValue, true);
  2318. value_.string_ =
  2319. duplicateAndPrefixStringValue(beginValue, static_cast<unsigned>(endValue - beginValue));
  2320. }
  2321. Value::Value(const std::string& value) {
  2322. initBasic(stringValue, true);
  2323. value_.string_ =
  2324. duplicateAndPrefixStringValue(value.data(), static_cast<unsigned>(value.length()));
  2325. }
  2326. Value::Value(const StaticString& value) {
  2327. initBasic(stringValue);
  2328. value_.string_ = const_cast<char*>(value.c_str());
  2329. }
  2330. #ifdef JSON_USE_CPPTL
  2331. Value::Value(const CppTL::ConstString& value) {
  2332. initBasic(stringValue, true);
  2333. value_.string_ = duplicateAndPrefixStringValue(value, static_cast<unsigned>(value.length()));
  2334. }
  2335. #endif
  2336. Value::Value(bool value) {
  2337. initBasic(booleanValue);
  2338. value_.bool_ = value;
  2339. }
  2340. Value::Value(Value const& other)
  2341. : type_(other.type_), allocated_(false)
  2342. ,
  2343. comments_(0)
  2344. {
  2345. switch (type_) {
  2346. case nullValue:
  2347. case intValue:
  2348. case uintValue:
  2349. case realValue:
  2350. case booleanValue:
  2351. value_ = other.value_;
  2352. break;
  2353. case stringValue:
  2354. if (other.value_.string_ && other.allocated_) {
  2355. unsigned len;
  2356. char const* str;
  2357. decodePrefixedString(other.allocated_, other.value_.string_,
  2358. &len, &str);
  2359. value_.string_ = duplicateAndPrefixStringValue(str, len);
  2360. allocated_ = true;
  2361. } else {
  2362. value_.string_ = other.value_.string_;
  2363. allocated_ = false;
  2364. }
  2365. break;
  2366. case arrayValue:
  2367. case objectValue:
  2368. value_.map_ = new ObjectValues(*other.value_.map_);
  2369. break;
  2370. default:
  2371. JSON_ASSERT_UNREACHABLE;
  2372. }
  2373. if (other.comments_) {
  2374. comments_ = new CommentInfo[numberOfCommentPlacement];
  2375. for (int comment = 0; comment < numberOfCommentPlacement; ++comment) {
  2376. const CommentInfo& otherComment = other.comments_[comment];
  2377. if (otherComment.comment_)
  2378. comments_[comment].setComment(
  2379. otherComment.comment_, strlen(otherComment.comment_));
  2380. }
  2381. }
  2382. }
  2383. Value::~Value() {
  2384. switch (type_) {
  2385. case nullValue:
  2386. case intValue:
  2387. case uintValue:
  2388. case realValue:
  2389. case booleanValue:
  2390. break;
  2391. case stringValue:
  2392. if (allocated_)
  2393. releaseStringValue(value_.string_);
  2394. break;
  2395. case arrayValue:
  2396. case objectValue:
  2397. delete value_.map_;
  2398. break;
  2399. default:
  2400. JSON_ASSERT_UNREACHABLE;
  2401. }
  2402. if (comments_)
  2403. delete[] comments_;
  2404. }
  2405. Value &Value::operator=(const Value &other) {
  2406. Value temp(other);
  2407. swap(temp);
  2408. return *this;
  2409. }
  2410. void Value::swapPayload(Value& other) {
  2411. ValueType temp = type_;
  2412. type_ = other.type_;
  2413. other.type_ = temp;
  2414. std::swap(value_, other.value_);
  2415. int temp2 = allocated_;
  2416. allocated_ = other.allocated_;
  2417. other.allocated_ = temp2 & 0x1;
  2418. }
  2419. void Value::swap(Value& other) {
  2420. swapPayload(other);
  2421. std::swap(comments_, other.comments_);
  2422. }
  2423. ValueType Value::type() const { return type_; }
  2424. int Value::compare(const Value& other) const {
  2425. if (*this < other)
  2426. return -1;
  2427. if (*this > other)
  2428. return 1;
  2429. return 0;
  2430. }
  2431. bool Value::operator<(const Value& other) const {
  2432. int typeDelta = type_ - other.type_;
  2433. if (typeDelta)
  2434. return typeDelta < 0 ? true : false;
  2435. switch (type_) {
  2436. case nullValue:
  2437. return false;
  2438. case intValue:
  2439. return value_.int_ < other.value_.int_;
  2440. case uintValue:
  2441. return value_.uint_ < other.value_.uint_;
  2442. case realValue:
  2443. return value_.real_ < other.value_.real_;
  2444. case booleanValue:
  2445. return value_.bool_ < other.value_.bool_;
  2446. case stringValue:
  2447. {
  2448. if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
  2449. if (other.value_.string_) return true;
  2450. else return false;
  2451. }
  2452. unsigned this_len;
  2453. unsigned other_len;
  2454. char const* this_str;
  2455. char const* other_str;
  2456. decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
  2457. decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
  2458. unsigned min_len = std::min(this_len, other_len);
  2459. int comp = memcmp(this_str, other_str, min_len);
  2460. if (comp < 0) return true;
  2461. if (comp > 0) return false;
  2462. return (this_len < other_len);
  2463. }
  2464. case arrayValue:
  2465. case objectValue: {
  2466. int delta = int(value_.map_->size() - other.value_.map_->size());
  2467. if (delta)
  2468. return delta < 0;
  2469. return (*value_.map_) < (*other.value_.map_);
  2470. }
  2471. default:
  2472. JSON_ASSERT_UNREACHABLE;
  2473. }
  2474. return false; // unreachable
  2475. }
  2476. bool Value::operator<=(const Value& other) const { return !(other < *this); }
  2477. bool Value::operator>=(const Value& other) const { return !(*this < other); }
  2478. bool Value::operator>(const Value& other) const { return other < *this; }
  2479. bool Value::operator==(const Value& other) const {
  2480. // if ( type_ != other.type_ )
  2481. // GCC 2.95.3 says:
  2482. // attempt to take address of bit-field structure member `Json::Value::type_'
  2483. // Beats me, but a temp solves the problem.
  2484. int temp = other.type_;
  2485. if (type_ != temp)
  2486. return false;
  2487. switch (type_) {
  2488. case nullValue:
  2489. return true;
  2490. case intValue:
  2491. return value_.int_ == other.value_.int_;
  2492. case uintValue:
  2493. return value_.uint_ == other.value_.uint_;
  2494. case realValue:
  2495. return value_.real_ == other.value_.real_;
  2496. case booleanValue:
  2497. return value_.bool_ == other.value_.bool_;
  2498. case stringValue:
  2499. {
  2500. if ((value_.string_ == 0) || (other.value_.string_ == 0)) {
  2501. return (value_.string_ == other.value_.string_);
  2502. }
  2503. unsigned this_len;
  2504. unsigned other_len;
  2505. char const* this_str;
  2506. char const* other_str;
  2507. decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
  2508. decodePrefixedString(other.allocated_, other.value_.string_, &other_len, &other_str);
  2509. if (this_len != other_len) return false;
  2510. int comp = memcmp(this_str, other_str, this_len);
  2511. return comp == 0;
  2512. }
  2513. case arrayValue:
  2514. case objectValue:
  2515. return value_.map_->size() == other.value_.map_->size() &&
  2516. (*value_.map_) == (*other.value_.map_);
  2517. default:
  2518. JSON_ASSERT_UNREACHABLE;
  2519. }
  2520. return false; // unreachable
  2521. }
  2522. bool Value::operator!=(const Value& other) const { return !(*this == other); }
  2523. const char* Value::asCString() const {
  2524. JSON_ASSERT_MESSAGE(type_ == stringValue,
  2525. "in Json::Value::asCString(): requires stringValue");
  2526. if (value_.string_ == 0) return 0;
  2527. unsigned this_len;
  2528. char const* this_str;
  2529. decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
  2530. return this_str;
  2531. }
  2532. bool Value::getString(char const** str, char const** cend) const {
  2533. if (type_ != stringValue) return false;
  2534. if (value_.string_ == 0) return false;
  2535. unsigned length;
  2536. decodePrefixedString(this->allocated_, this->value_.string_, &length, str);
  2537. *cend = *str + length;
  2538. return true;
  2539. }
  2540. std::string Value::asString() const {
  2541. switch (type_) {
  2542. case nullValue:
  2543. return "";
  2544. case stringValue:
  2545. {
  2546. if (value_.string_ == 0) return "";
  2547. unsigned this_len;
  2548. char const* this_str;
  2549. decodePrefixedString(this->allocated_, this->value_.string_, &this_len, &this_str);
  2550. return std::string(this_str, this_len);
  2551. }
  2552. case booleanValue:
  2553. return value_.bool_ ? "true" : "false";
  2554. case intValue:
  2555. return valueToString(value_.int_);
  2556. case uintValue:
  2557. return valueToString(value_.uint_);
  2558. case realValue:
  2559. return valueToString(value_.real_);
  2560. default:
  2561. JSON_FAIL_MESSAGE("Type is not convertible to string");
  2562. }
  2563. }
  2564. #ifdef JSON_USE_CPPTL
  2565. CppTL::ConstString Value::asConstString() const {
  2566. unsigned len;
  2567. char const* str;
  2568. decodePrefixedString(allocated_, value_.string_,
  2569. &len, &str);
  2570. return CppTL::ConstString(str, len);
  2571. }
  2572. #endif
  2573. Value::Int Value::asInt() const {
  2574. switch (type_) {
  2575. case intValue:
  2576. JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range");
  2577. return Int(value_.int_);
  2578. case uintValue:
  2579. JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range");
  2580. return Int(value_.uint_);
  2581. case realValue:
  2582. JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt),
  2583. "double out of Int range");
  2584. return Int(value_.real_);
  2585. case nullValue:
  2586. return 0;
  2587. case booleanValue:
  2588. return value_.bool_ ? 1 : 0;
  2589. default:
  2590. break;
  2591. }
  2592. JSON_FAIL_MESSAGE("Value is not convertible to Int.");
  2593. }
  2594. Value::UInt Value::asUInt() const {
  2595. switch (type_) {
  2596. case intValue:
  2597. JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range");
  2598. return UInt(value_.int_);
  2599. case uintValue:
  2600. JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range");
  2601. return UInt(value_.uint_);
  2602. case realValue:
  2603. JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt),
  2604. "double out of UInt range");
  2605. return UInt(value_.real_);
  2606. case nullValue:
  2607. return 0;
  2608. case booleanValue:
  2609. return value_.bool_ ? 1 : 0;
  2610. default:
  2611. break;
  2612. }
  2613. JSON_FAIL_MESSAGE("Value is not convertible to UInt.");
  2614. }
  2615. #if defined(JSON_HAS_INT64)
  2616. Value::Int64 Value::asInt64() const {
  2617. switch (type_) {
  2618. case intValue:
  2619. return Int64(value_.int_);
  2620. case uintValue:
  2621. JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range");
  2622. return Int64(value_.uint_);
  2623. case realValue:
  2624. JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64),
  2625. "double out of Int64 range");
  2626. return Int64(value_.real_);
  2627. case nullValue:
  2628. return 0;
  2629. case booleanValue:
  2630. return value_.bool_ ? 1 : 0;
  2631. default:
  2632. break;
  2633. }
  2634. JSON_FAIL_MESSAGE("Value is not convertible to Int64.");
  2635. }
  2636. Value::UInt64 Value::asUInt64() const {
  2637. switch (type_) {
  2638. case intValue:
  2639. JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range");
  2640. return UInt64(value_.int_);
  2641. case uintValue:
  2642. return UInt64(value_.uint_);
  2643. case realValue:
  2644. JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64),
  2645. "double out of UInt64 range");
  2646. return UInt64(value_.real_);
  2647. case nullValue:
  2648. return 0;
  2649. case booleanValue:
  2650. return value_.bool_ ? 1 : 0;
  2651. default:
  2652. break;
  2653. }
  2654. JSON_FAIL_MESSAGE("Value is not convertible to UInt64.");
  2655. }
  2656. #endif // if defined(JSON_HAS_INT64)
  2657. LargestInt Value::asLargestInt() const {
  2658. #if defined(JSON_NO_INT64)
  2659. return asInt();
  2660. #else
  2661. return asInt64();
  2662. #endif
  2663. }
  2664. LargestUInt Value::asLargestUInt() const {
  2665. #if defined(JSON_NO_INT64)
  2666. return asUInt();
  2667. #else
  2668. return asUInt64();
  2669. #endif
  2670. }
  2671. double Value::asDouble() const {
  2672. switch (type_) {
  2673. case intValue:
  2674. return static_cast<double>(value_.int_);
  2675. case uintValue:
  2676. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2677. return static_cast<double>(value_.uint_);
  2678. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2679. return integerToDouble(value_.uint_);
  2680. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2681. case realValue:
  2682. return value_.real_;
  2683. case nullValue:
  2684. return 0.0;
  2685. case booleanValue:
  2686. return value_.bool_ ? 1.0 : 0.0;
  2687. default:
  2688. break;
  2689. }
  2690. JSON_FAIL_MESSAGE("Value is not convertible to double.");
  2691. }
  2692. float Value::asFloat() const {
  2693. switch (type_) {
  2694. case intValue:
  2695. return static_cast<float>(value_.int_);
  2696. case uintValue:
  2697. #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2698. return static_cast<float>(value_.uint_);
  2699. #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2700. return integerToDouble(value_.uint_);
  2701. #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION)
  2702. case realValue:
  2703. return static_cast<float>(value_.real_);
  2704. case nullValue:
  2705. return 0.0;
  2706. case booleanValue:
  2707. return value_.bool_ ? 1.0f : 0.0f;
  2708. default:
  2709. break;
  2710. }
  2711. JSON_FAIL_MESSAGE("Value is not convertible to float.");
  2712. }
  2713. bool Value::asBool() const {
  2714. switch (type_) {
  2715. case booleanValue:
  2716. return value_.bool_;
  2717. case nullValue:
  2718. return false;
  2719. case intValue:
  2720. return value_.int_ ? true : false;
  2721. case uintValue:
  2722. return value_.uint_ ? true : false;
  2723. case realValue:
  2724. // This is kind of strange. Not recommended.
  2725. return (value_.real_ != 0.0) ? true : false;
  2726. default:
  2727. break;
  2728. }
  2729. JSON_FAIL_MESSAGE("Value is not convertible to bool.");
  2730. }
  2731. bool Value::isConvertibleTo(ValueType other) const {
  2732. switch (other) {
  2733. case nullValue:
  2734. return (isNumeric() && asDouble() == 0.0) ||
  2735. (type_ == booleanValue && value_.bool_ == false) ||
  2736. (type_ == stringValue && asString() == "") ||
  2737. (type_ == arrayValue && value_.map_->size() == 0) ||
  2738. (type_ == objectValue && value_.map_->size() == 0) ||
  2739. type_ == nullValue;
  2740. case intValue:
  2741. return isInt() ||
  2742. (type_ == realValue && InRange(value_.real_, minInt, maxInt)) ||
  2743. type_ == booleanValue || type_ == nullValue;
  2744. case uintValue:
  2745. return isUInt() ||
  2746. (type_ == realValue && InRange(value_.real_, 0, maxUInt)) ||
  2747. type_ == booleanValue || type_ == nullValue;
  2748. case realValue:
  2749. return isNumeric() || type_ == booleanValue || type_ == nullValue;
  2750. case booleanValue:
  2751. return isNumeric() || type_ == booleanValue || type_ == nullValue;
  2752. case stringValue:
  2753. return isNumeric() || type_ == booleanValue || type_ == stringValue ||
  2754. type_ == nullValue;
  2755. case arrayValue:
  2756. return type_ == arrayValue || type_ == nullValue;
  2757. case objectValue:
  2758. return type_ == objectValue || type_ == nullValue;
  2759. }
  2760. JSON_ASSERT_UNREACHABLE;
  2761. return false;
  2762. }
  2763. /// Number of values in array or object
  2764. ArrayIndex Value::size() const {
  2765. switch (type_) {
  2766. case nullValue:
  2767. case intValue:
  2768. case uintValue:
  2769. case realValue:
  2770. case booleanValue:
  2771. case stringValue:
  2772. return 0;
  2773. case arrayValue: // size of the array is highest index + 1
  2774. if (!value_.map_->empty()) {
  2775. ObjectValues::const_iterator itLast = value_.map_->end();
  2776. --itLast;
  2777. return (*itLast).first.index() + 1;
  2778. }
  2779. return 0;
  2780. case objectValue:
  2781. return ArrayIndex(value_.map_->size());
  2782. }
  2783. JSON_ASSERT_UNREACHABLE;
  2784. return 0; // unreachable;
  2785. }
  2786. bool Value::empty() const {
  2787. if (isNull() || isArray() || isObject())
  2788. return size() == 0u;
  2789. else
  2790. return false;
  2791. }
  2792. bool Value::operator!() const { return isNull(); }
  2793. void Value::clear() {
  2794. JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue ||
  2795. type_ == objectValue,
  2796. "in Json::Value::clear(): requires complex value");
  2797. switch (type_) {
  2798. case arrayValue:
  2799. case objectValue:
  2800. value_.map_->clear();
  2801. break;
  2802. default:
  2803. break;
  2804. }
  2805. }
  2806. void Value::resize(ArrayIndex newSize) {
  2807. JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == arrayValue,
  2808. "in Json::Value::resize(): requires arrayValue");
  2809. if (type_ == nullValue)
  2810. *this = Value(arrayValue);
  2811. ArrayIndex oldSize = size();
  2812. if (newSize == 0)
  2813. clear();
  2814. else if (newSize > oldSize)
  2815. (*this)[newSize - 1];
  2816. else {
  2817. for (ArrayIndex index = newSize; index < oldSize; ++index) {
  2818. value_.map_->erase(index);
  2819. }
  2820. assert(size() == newSize);
  2821. }
  2822. }
  2823. Value& Value::operator[](ArrayIndex index) {
  2824. JSON_ASSERT_MESSAGE(
  2825. type_ == nullValue || type_ == arrayValue,
  2826. "in Json::Value::operator[](ArrayIndex): requires arrayValue");
  2827. if (type_ == nullValue)
  2828. *this = Value(arrayValue);
  2829. CZString key(index);
  2830. ObjectValues::iterator it = value_.map_->lower_bound(key);
  2831. if (it != value_.map_->end() && (*it).first == key)
  2832. return (*it).second;
  2833. ObjectValues::value_type defaultValue(key, nullRef);
  2834. it = value_.map_->insert(it, defaultValue);
  2835. return (*it).second;
  2836. }
  2837. Value& Value::operator[](int index) {
  2838. JSON_ASSERT_MESSAGE(
  2839. index >= 0,
  2840. "in Json::Value::operator[](int index): index cannot be negative");
  2841. return (*this)[ArrayIndex(index)];
  2842. }
  2843. const Value& Value::operator[](ArrayIndex index) const {
  2844. JSON_ASSERT_MESSAGE(
  2845. type_ == nullValue || type_ == arrayValue,
  2846. "in Json::Value::operator[](ArrayIndex)const: requires arrayValue");
  2847. if (type_ == nullValue)
  2848. return nullRef;
  2849. CZString key(index);
  2850. ObjectValues::const_iterator it = value_.map_->find(key);
  2851. if (it == value_.map_->end())
  2852. return nullRef;
  2853. return (*it).second;
  2854. }
  2855. const Value& Value::operator[](int index) const {
  2856. JSON_ASSERT_MESSAGE(
  2857. index >= 0,
  2858. "in Json::Value::operator[](int index) const: index cannot be negative");
  2859. return (*this)[ArrayIndex(index)];
  2860. }
  2861. void Value::initBasic(ValueType vtype, bool allocated) {
  2862. type_ = vtype;
  2863. allocated_ = allocated;
  2864. comments_ = 0;
  2865. }
  2866. // Access an object value by name, create a null member if it does not exist.
  2867. // @pre Type of '*this' is object or null.
  2868. // @param key is null-terminated.
  2869. Value& Value::resolveReference(const char* key) {
  2870. JSON_ASSERT_MESSAGE(
  2871. type_ == nullValue || type_ == objectValue,
  2872. "in Json::Value::resolveReference(): requires objectValue");
  2873. if (type_ == nullValue)
  2874. *this = Value(objectValue);
  2875. CZString actualKey(
  2876. key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE!
  2877. ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
  2878. if (it != value_.map_->end() && (*it).first == actualKey)
  2879. return (*it).second;
  2880. ObjectValues::value_type defaultValue(actualKey, nullRef);
  2881. it = value_.map_->insert(it, defaultValue);
  2882. Value& value = (*it).second;
  2883. return value;
  2884. }
  2885. // @param key is not null-terminated.
  2886. Value& Value::resolveReference(char const* key, char const* cend)
  2887. {
  2888. JSON_ASSERT_MESSAGE(
  2889. type_ == nullValue || type_ == objectValue,
  2890. "in Json::Value::resolveReference(key, end): requires objectValue");
  2891. if (type_ == nullValue)
  2892. *this = Value(objectValue);
  2893. CZString actualKey(
  2894. key, static_cast<unsigned>(cend-key), CZString::duplicateOnCopy);
  2895. ObjectValues::iterator it = value_.map_->lower_bound(actualKey);
  2896. if (it != value_.map_->end() && (*it).first == actualKey)
  2897. return (*it).second;
  2898. ObjectValues::value_type defaultValue(actualKey, nullRef);
  2899. it = value_.map_->insert(it, defaultValue);
  2900. Value& value = (*it).second;
  2901. return value;
  2902. }
  2903. Value Value::get(ArrayIndex index, const Value& defaultValue) const {
  2904. const Value* value = &((*this)[index]);
  2905. return value == &nullRef ? defaultValue : *value;
  2906. }
  2907. bool Value::isValidIndex(ArrayIndex index) const { return index < size(); }
  2908. Value const* Value::find(char const* key, char const* cend) const
  2909. {
  2910. JSON_ASSERT_MESSAGE(
  2911. type_ == nullValue || type_ == objectValue,
  2912. "in Json::Value::find(key, end, found): requires objectValue or nullValue");
  2913. if (type_ == nullValue) return NULL;
  2914. CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
  2915. ObjectValues::const_iterator it = value_.map_->find(actualKey);
  2916. if (it == value_.map_->end()) return NULL;
  2917. return &(*it).second;
  2918. }
  2919. const Value& Value::operator[](const char* key) const
  2920. {
  2921. Value const* found = find(key, key + strlen(key));
  2922. if (!found) return nullRef;
  2923. return *found;
  2924. }
  2925. Value const& Value::operator[](std::string const& key) const
  2926. {
  2927. Value const* found = find(key.data(), key.data() + key.length());
  2928. if (!found) return nullRef;
  2929. return *found;
  2930. }
  2931. Value& Value::operator[](const char* key) {
  2932. return resolveReference(key, key + strlen(key));
  2933. }
  2934. Value& Value::operator[](const std::string& key) {
  2935. return resolveReference(key.data(), key.data() + key.length());
  2936. }
  2937. Value& Value::operator[](const StaticString& key) {
  2938. return resolveReference(key.c_str());
  2939. }
  2940. #ifdef JSON_USE_CPPTL
  2941. Value& Value::operator[](const CppTL::ConstString& key) {
  2942. return resolveReference(key.c_str(), key.end_c_str());
  2943. }
  2944. Value const& Value::operator[](CppTL::ConstString const& key) const
  2945. {
  2946. Value const* found = find(key.c_str(), key.end_c_str());
  2947. if (!found) return nullRef;
  2948. return *found;
  2949. }
  2950. #endif
  2951. Value& Value::append(const Value& value) { return (*this)[size()] = value; }
  2952. Value Value::get(char const* key, char const* cend, Value const& defaultValue) const
  2953. {
  2954. Value const* found = find(key, cend);
  2955. return !found ? defaultValue : *found;
  2956. }
  2957. Value Value::get(char const* key, Value const& defaultValue) const
  2958. {
  2959. return get(key, key + strlen(key), defaultValue);
  2960. }
  2961. Value Value::get(std::string const& key, Value const& defaultValue) const
  2962. {
  2963. return get(key.data(), key.data() + key.length(), defaultValue);
  2964. }
  2965. bool Value::removeMember(const char* key, const char* cend, Value* removed)
  2966. {
  2967. if (type_ != objectValue) {
  2968. return false;
  2969. }
  2970. CZString actualKey(key, static_cast<unsigned>(cend-key), CZString::noDuplication);
  2971. ObjectValues::iterator it = value_.map_->find(actualKey);
  2972. if (it == value_.map_->end())
  2973. return false;
  2974. *removed = it->second;
  2975. value_.map_->erase(it);
  2976. return true;
  2977. }
  2978. bool Value::removeMember(const char* key, Value* removed)
  2979. {
  2980. return removeMember(key, key + strlen(key), removed);
  2981. }
  2982. bool Value::removeMember(std::string const& key, Value* removed)
  2983. {
  2984. return removeMember(key.data(), key.data() + key.length(), removed);
  2985. }
  2986. Value Value::removeMember(const char* key)
  2987. {
  2988. JSON_ASSERT_MESSAGE(type_ == nullValue || type_ == objectValue,
  2989. "in Json::Value::removeMember(): requires objectValue");
  2990. if (type_ == nullValue)
  2991. return nullRef;
  2992. Value removed; // null
  2993. removeMember(key, key + strlen(key), &removed);
  2994. return removed; // still null if removeMember() did nothing
  2995. }
  2996. Value Value::removeMember(const std::string& key)
  2997. {
  2998. return removeMember(key.c_str());
  2999. }
  3000. bool Value::removeIndex(ArrayIndex index, Value* removed) {
  3001. if (type_ != arrayValue) {
  3002. return false;
  3003. }
  3004. CZString key(index);
  3005. ObjectValues::iterator it = value_.map_->find(key);
  3006. if (it == value_.map_->end()) {
  3007. return false;
  3008. }
  3009. *removed = it->second;
  3010. ArrayIndex oldSize = size();
  3011. // shift left all items left, into the place of the "removed"
  3012. for (ArrayIndex i = index; i < (oldSize - 1); ++i){
  3013. CZString keey(i);
  3014. (*value_.map_)[keey] = (*this)[i + 1];
  3015. }
  3016. // erase the last one ("leftover")
  3017. CZString keyLast(oldSize - 1);
  3018. ObjectValues::iterator itLast = value_.map_->find(keyLast);
  3019. value_.map_->erase(itLast);
  3020. return true;
  3021. }
  3022. #ifdef JSON_USE_CPPTL
  3023. Value Value::get(const CppTL::ConstString& key,
  3024. const Value& defaultValue) const {
  3025. return get(key.c_str(), key.end_c_str(), defaultValue);
  3026. }
  3027. #endif
  3028. bool Value::isMember(char const* key, char const* cend) const
  3029. {
  3030. Value const* value = find(key, cend);
  3031. return NULL != value;
  3032. }
  3033. bool Value::isMember(char const* key) const
  3034. {
  3035. return isMember(key, key + strlen(key));
  3036. }
  3037. bool Value::isMember(std::string const& key) const
  3038. {
  3039. return isMember(key.data(), key.data() + key.length());
  3040. }
  3041. #ifdef JSON_USE_CPPTL
  3042. bool Value::isMember(const CppTL::ConstString& key) const {
  3043. return isMember(key.c_str(), key.end_c_str());
  3044. }
  3045. #endif
  3046. Value::Members Value::getMemberNames() const {
  3047. JSON_ASSERT_MESSAGE(
  3048. type_ == nullValue || type_ == objectValue,
  3049. "in Json::Value::getMemberNames(), value must be objectValue");
  3050. if (type_ == nullValue)
  3051. return Value::Members();
  3052. Members members;
  3053. members.reserve(value_.map_->size());
  3054. ObjectValues::const_iterator it = value_.map_->begin();
  3055. ObjectValues::const_iterator itEnd = value_.map_->end();
  3056. for (; it != itEnd; ++it) {
  3057. members.push_back(std::string((*it).first.data(),
  3058. (*it).first.length()));
  3059. }
  3060. return members;
  3061. }
  3062. //
  3063. //# ifdef JSON_USE_CPPTL
  3064. // EnumMemberNames
  3065. // Value::enumMemberNames() const
  3066. //{
  3067. // if ( type_ == objectValue )
  3068. // {
  3069. // return CppTL::Enum::any( CppTL::Enum::transform(
  3070. // CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
  3071. // MemberNamesTransform() ) );
  3072. // }
  3073. // return EnumMemberNames();
  3074. //}
  3075. //
  3076. //
  3077. // EnumValues
  3078. // Value::enumValues() const
  3079. //{
  3080. // if ( type_ == objectValue || type_ == arrayValue )
  3081. // return CppTL::Enum::anyValues( *(value_.map_),
  3082. // CppTL::Type<const Value &>() );
  3083. // return EnumValues();
  3084. //}
  3085. //
  3086. //# endif
  3087. static bool IsIntegral(double d) {
  3088. double integral_part;
  3089. return modf(d, &integral_part) == 0.0;
  3090. }
  3091. bool Value::isNull() const { return type_ == nullValue; }
  3092. bool Value::isBool() const { return type_ == booleanValue; }
  3093. bool Value::isInt() const {
  3094. switch (type_) {
  3095. case intValue:
  3096. return value_.int_ >= minInt && value_.int_ <= maxInt;
  3097. case uintValue:
  3098. return value_.uint_ <= UInt(maxInt);
  3099. case realValue:
  3100. return value_.real_ >= minInt && value_.real_ <= maxInt &&
  3101. IsIntegral(value_.real_);
  3102. default:
  3103. break;
  3104. }
  3105. return false;
  3106. }
  3107. bool Value::isUInt() const {
  3108. switch (type_) {
  3109. case intValue:
  3110. return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt);
  3111. case uintValue:
  3112. return value_.uint_ <= maxUInt;
  3113. case realValue:
  3114. return value_.real_ >= 0 && value_.real_ <= maxUInt &&
  3115. IsIntegral(value_.real_);
  3116. default:
  3117. break;
  3118. }
  3119. return false;
  3120. }
  3121. bool Value::isInt64() const {
  3122. #if defined(JSON_HAS_INT64)
  3123. switch (type_) {
  3124. case intValue:
  3125. return true;
  3126. case uintValue:
  3127. return value_.uint_ <= UInt64(maxInt64);
  3128. case realValue:
  3129. // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a
  3130. // double, so double(maxInt64) will be rounded up to 2^63. Therefore we
  3131. // require the value to be strictly less than the limit.
  3132. return value_.real_ >= double(minInt64) &&
  3133. value_.real_ < double(maxInt64) && IsIntegral(value_.real_);
  3134. default:
  3135. break;
  3136. }
  3137. #endif // JSON_HAS_INT64
  3138. return false;
  3139. }
  3140. bool Value::isUInt64() const {
  3141. #if defined(JSON_HAS_INT64)
  3142. switch (type_) {
  3143. case intValue:
  3144. return value_.int_ >= 0;
  3145. case uintValue:
  3146. return true;
  3147. case realValue:
  3148. // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a
  3149. // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we
  3150. // require the value to be strictly less than the limit.
  3151. return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble &&
  3152. IsIntegral(value_.real_);
  3153. default:
  3154. break;
  3155. }
  3156. #endif // JSON_HAS_INT64
  3157. return false;
  3158. }
  3159. bool Value::isIntegral() const {
  3160. #if defined(JSON_HAS_INT64)
  3161. return isInt64() || isUInt64();
  3162. #else
  3163. return isInt() || isUInt();
  3164. #endif
  3165. }
  3166. bool Value::isDouble() const { return type_ == realValue || isIntegral(); }
  3167. bool Value::isNumeric() const { return isIntegral() || isDouble(); }
  3168. bool Value::isString() const { return type_ == stringValue; }
  3169. bool Value::isArray() const { return type_ == arrayValue; }
  3170. bool Value::isObject() const { return type_ == objectValue; }
  3171. void Value::setComment(const char* comment, size_t len, CommentPlacement placement) {
  3172. if (!comments_)
  3173. comments_ = new CommentInfo[numberOfCommentPlacement];
  3174. if ((len > 0) && (comment[len-1] == '\n')) {
  3175. // Always discard trailing newline, to aid indentation.
  3176. len -= 1;
  3177. }
  3178. comments_[placement].setComment(comment, len);
  3179. }
  3180. void Value::setComment(const char* comment, CommentPlacement placement) {
  3181. setComment(comment, strlen(comment), placement);
  3182. }
  3183. void Value::setComment(const std::string& comment, CommentPlacement placement) {
  3184. setComment(comment.c_str(), comment.length(), placement);
  3185. }
  3186. bool Value::hasComment(CommentPlacement placement) const {
  3187. return comments_ != 0 && comments_[placement].comment_ != 0;
  3188. }
  3189. std::string Value::getComment(CommentPlacement placement) const {
  3190. if (hasComment(placement))
  3191. return comments_[placement].comment_;
  3192. return "";
  3193. }
  3194. std::string Value::toStyledString() const {
  3195. StyledWriter writer;
  3196. return writer.write(*this);
  3197. }
  3198. Value::const_iterator Value::begin() const {
  3199. switch (type_) {
  3200. case arrayValue:
  3201. case objectValue:
  3202. if (value_.map_)
  3203. return const_iterator(value_.map_->begin());
  3204. break;
  3205. default:
  3206. break;
  3207. }
  3208. return const_iterator();
  3209. }
  3210. Value::const_iterator Value::end() const {
  3211. switch (type_) {
  3212. case arrayValue:
  3213. case objectValue:
  3214. if (value_.map_)
  3215. return const_iterator(value_.map_->end());
  3216. break;
  3217. default:
  3218. break;
  3219. }
  3220. return const_iterator();
  3221. }
  3222. Value::iterator Value::begin() {
  3223. switch (type_) {
  3224. case arrayValue:
  3225. case objectValue:
  3226. if (value_.map_)
  3227. return iterator(value_.map_->begin());
  3228. break;
  3229. default:
  3230. break;
  3231. }
  3232. return iterator();
  3233. }
  3234. Value::iterator Value::end() {
  3235. switch (type_) {
  3236. case arrayValue:
  3237. case objectValue:
  3238. if (value_.map_)
  3239. return iterator(value_.map_->end());
  3240. break;
  3241. default:
  3242. break;
  3243. }
  3244. return iterator();
  3245. }
  3246. // class PathArgument
  3247. // //////////////////////////////////////////////////////////////////
  3248. PathArgument::PathArgument() : key_(), index_(), kind_(kindNone) {}
  3249. PathArgument::PathArgument(ArrayIndex index)
  3250. : key_(), index_(index), kind_(kindIndex) {}
  3251. PathArgument::PathArgument(const char* key)
  3252. : key_(key), index_(), kind_(kindKey) {}
  3253. PathArgument::PathArgument(const std::string& key)
  3254. : key_(key.c_str()), index_(), kind_(kindKey) {}
  3255. // class Path
  3256. // //////////////////////////////////////////////////////////////////
  3257. Path::Path(const std::string& path,
  3258. const PathArgument& a1,
  3259. const PathArgument& a2,
  3260. const PathArgument& a3,
  3261. const PathArgument& a4,
  3262. const PathArgument& a5) {
  3263. InArgs in;
  3264. in.push_back(&a1);
  3265. in.push_back(&a2);
  3266. in.push_back(&a3);
  3267. in.push_back(&a4);
  3268. in.push_back(&a5);
  3269. makePath(path, in);
  3270. }
  3271. void Path::makePath(const std::string& path, const InArgs& in) {
  3272. const char* current = path.c_str();
  3273. const char* end = current + path.length();
  3274. InArgs::const_iterator itInArg = in.begin();
  3275. while (current != end) {
  3276. if (*current == '[') {
  3277. ++current;
  3278. if (*current == '%')
  3279. addPathInArg(path, in, itInArg, PathArgument::kindIndex);
  3280. else {
  3281. ArrayIndex index = 0;
  3282. for (; current != end && *current >= '0' && *current <= '9'; ++current)
  3283. index = index * 10 + ArrayIndex(*current - '0');
  3284. args_.push_back(index);
  3285. }
  3286. if (current == end || *current++ != ']')
  3287. invalidPath(path, int(current - path.c_str()));
  3288. } else if (*current == '%') {
  3289. addPathInArg(path, in, itInArg, PathArgument::kindKey);
  3290. ++current;
  3291. } else if (*current == '.') {
  3292. ++current;
  3293. } else {
  3294. const char* beginName = current;
  3295. while (current != end && !strchr("[.", *current))
  3296. ++current;
  3297. args_.push_back(std::string(beginName, current));
  3298. }
  3299. }
  3300. }
  3301. void Path::addPathInArg(const std::string& /*path*/,
  3302. const InArgs& in,
  3303. InArgs::const_iterator& itInArg,
  3304. PathArgument::Kind kind) {
  3305. if (itInArg == in.end()) {
  3306. // Error: missing argument %d
  3307. } else if ((*itInArg)->kind_ != kind) {
  3308. // Error: bad argument type
  3309. } else {
  3310. args_.push_back(**itInArg);
  3311. }
  3312. }
  3313. void Path::invalidPath(const std::string& /*path*/, int /*location*/) {
  3314. // Error: invalid path.
  3315. }
  3316. const Value& Path::resolve(const Value& root) const {
  3317. const Value* node = &root;
  3318. for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
  3319. const PathArgument& arg = *it;
  3320. if (arg.kind_ == PathArgument::kindIndex) {
  3321. if (!node->isArray() || !node->isValidIndex(arg.index_)) {
  3322. // Error: unable to resolve path (array value expected at position...
  3323. }
  3324. node = &((*node)[arg.index_]);
  3325. } else if (arg.kind_ == PathArgument::kindKey) {
  3326. if (!node->isObject()) {
  3327. // Error: unable to resolve path (object value expected at position...)
  3328. }
  3329. node = &((*node)[arg.key_]);
  3330. if (node == &Value::nullRef) {
  3331. // Error: unable to resolve path (object has no member named '' at
  3332. // position...)
  3333. }
  3334. }
  3335. }
  3336. return *node;
  3337. }
  3338. Value Path::resolve(const Value& root, const Value& defaultValue) const {
  3339. const Value* node = &root;
  3340. for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
  3341. const PathArgument& arg = *it;
  3342. if (arg.kind_ == PathArgument::kindIndex) {
  3343. if (!node->isArray() || !node->isValidIndex(arg.index_))
  3344. return defaultValue;
  3345. node = &((*node)[arg.index_]);
  3346. } else if (arg.kind_ == PathArgument::kindKey) {
  3347. if (!node->isObject())
  3348. return defaultValue;
  3349. node = &((*node)[arg.key_]);
  3350. if (node == &Value::nullRef)
  3351. return defaultValue;
  3352. }
  3353. }
  3354. return *node;
  3355. }
  3356. Value& Path::make(Value& root) const {
  3357. Value* node = &root;
  3358. for (Args::const_iterator it = args_.begin(); it != args_.end(); ++it) {
  3359. const PathArgument& arg = *it;
  3360. if (arg.kind_ == PathArgument::kindIndex) {
  3361. if (!node->isArray()) {
  3362. // Error: node is not an array at position ...
  3363. }
  3364. node = &((*node)[arg.index_]);
  3365. } else if (arg.kind_ == PathArgument::kindKey) {
  3366. if (!node->isObject()) {
  3367. // Error: node is not an object at position...
  3368. }
  3369. node = &((*node)[arg.key_]);
  3370. }
  3371. }
  3372. return *node;
  3373. }
  3374. } // namespace Json
  3375. // //////////////////////////////////////////////////////////////////////
  3376. // End of content of file: src/lib_json/json_value.cpp
  3377. // //////////////////////////////////////////////////////////////////////
  3378. // //////////////////////////////////////////////////////////////////////
  3379. // Beginning of content of file: src/lib_json/json_writer.cpp
  3380. // //////////////////////////////////////////////////////////////////////
  3381. // Copyright 2011 Baptiste Lepilleur
  3382. // Distributed under MIT license, or public domain if desired and
  3383. // recognized in your jurisdiction.
  3384. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
  3385. #if !defined(JSON_IS_AMALGAMATION)
  3386. #include <json/writer.h>
  3387. #include "json_tool.h"
  3388. #endif // if !defined(JSON_IS_AMALGAMATION)
  3389. #include <iomanip>
  3390. #include <memory>
  3391. #include <sstream>
  3392. #include <utility>
  3393. #include <set>
  3394. #include <cassert>
  3395. #include <cstring>
  3396. #include <cstdio>
  3397. #if defined(__BORLANDC__)
  3398. #include <stdio.h>
  3399. #endif
  3400. #if defined(_MSC_VER) && _MSC_VER >= 1200 && _MSC_VER < 1800 // Between VC++ 6.0 and VC++ 11.0
  3401. #include <float.h>
  3402. #define isfinite _finite
  3403. #elif defined(__sun) && defined(__SVR4) //Solaris
  3404. #include <ieeefp.h>
  3405. #define isfinite finite
  3406. #else
  3407. #include <cmath>
  3408. #define isfinite std::isfinite
  3409. #endif
  3410. #if defined(_MSC_VER)
  3411. #if !defined(WINCE) && defined(__STDC_SECURE_LIB__) && _MSC_VER >= 1500 // VC++ 9.0 and above
  3412. #define snprintf sprintf_s
  3413. #elif _MSC_VER >= 1900 // VC++ 14.0 and above
  3414. #define snprintf std::snprintf
  3415. #else
  3416. #define snprintf _snprintf
  3417. #endif
  3418. #elif defined(__ANDROID__)
  3419. #define snprintf snprintf
  3420. #elif __cplusplus >= 201103L
  3421. #define snprintf std::snprintf
  3422. #endif
  3423. #if defined(__BORLANDC__)
  3424. #include <float.h>
  3425. #define isfinite _finite
  3426. #define snprintf _snprintf
  3427. #endif
  3428. #if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
  3429. // Disable warning about strdup being deprecated.
  3430. #pragma warning(disable : 4996)
  3431. #endif
  3432. namespace Json {
  3433. #if JSON_HAS_UNIQUE_PTR
  3434. typedef std::unique_ptr<StreamWriter> const StreamWriterPtr;
  3435. #else
  3436. typedef std::auto_ptr<StreamWriter> StreamWriterPtr;
  3437. #endif
  3438. static bool containsControlCharacter(const char* str) {
  3439. while (*str) {
  3440. if (isControlCharacter(*(str++)))
  3441. return true;
  3442. }
  3443. return false;
  3444. }
  3445. static bool containsControlCharacter0(const char* str, unsigned len) {
  3446. char const* end = str + len;
  3447. while (end != str) {
  3448. if (isControlCharacter(*str) || 0==*str)
  3449. return true;
  3450. ++str;
  3451. }
  3452. return false;
  3453. }
  3454. std::string valueToString(LargestInt value) {
  3455. UIntToStringBuffer buffer;
  3456. char* current = buffer + sizeof(buffer);
  3457. if (value == Value::minLargestInt) {
  3458. uintToString(LargestUInt(Value::maxLargestInt) + 1, current);
  3459. *--current = '-';
  3460. } else if (value < 0) {
  3461. uintToString(LargestUInt(-value), current);
  3462. *--current = '-';
  3463. } else {
  3464. uintToString(LargestUInt(value), current);
  3465. }
  3466. assert(current >= buffer);
  3467. return current;
  3468. }
  3469. std::string valueToString(LargestUInt value) {
  3470. UIntToStringBuffer buffer;
  3471. char* current = buffer + sizeof(buffer);
  3472. uintToString(value, current);
  3473. assert(current >= buffer);
  3474. return current;
  3475. }
  3476. #if defined(JSON_HAS_INT64)
  3477. std::string valueToString(Int value) {
  3478. return valueToString(LargestInt(value));
  3479. }
  3480. std::string valueToString(UInt value) {
  3481. return valueToString(LargestUInt(value));
  3482. }
  3483. #endif // # if defined(JSON_HAS_INT64)
  3484. std::string valueToString(double value, bool useSpecialFloats, unsigned int precision) {
  3485. // Allocate a buffer that is more than large enough to store the 16 digits of
  3486. // precision requested below.
  3487. char buffer[32];
  3488. int len = -1;
  3489. char formatString[6];
  3490. sprintf(formatString, "%%.%dg", precision);
  3491. // Print into the buffer. We need not request the alternative representation
  3492. // that always has a decimal point because JSON doesn't distingish the
  3493. // concepts of reals and integers.
  3494. if (isfinite(value)) {
  3495. len = snprintf(buffer, sizeof(buffer), formatString, value);
  3496. } else {
  3497. // IEEE standard states that NaN values will not compare to themselves
  3498. if (value != value) {
  3499. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "NaN" : "null");
  3500. } else if (value < 0) {
  3501. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "-Infinity" : "-1e+9999");
  3502. } else {
  3503. len = snprintf(buffer, sizeof(buffer), useSpecialFloats ? "Infinity" : "1e+9999");
  3504. }
  3505. // For those, we do not need to call fixNumLoc, but it is fast.
  3506. }
  3507. assert(len >= 0);
  3508. fixNumericLocale(buffer, buffer + len);
  3509. return buffer;
  3510. }
  3511. std::string valueToString(double value) { return valueToString(value, false, 17); }
  3512. std::string valueToString(bool value) { return value ? "true" : "false"; }
  3513. std::string valueToQuotedString(const char* value) {
  3514. if (value == NULL)
  3515. return "";
  3516. // Not sure how to handle unicode...
  3517. if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL &&
  3518. !containsControlCharacter(value))
  3519. return std::string("\"") + value + "\"";
  3520. // We have to walk value and escape any special characters.
  3521. // Appending to std::string is not efficient, but this should be rare.
  3522. // (Note: forward slashes are *not* rare, but I am not escaping them.)
  3523. std::string::size_type maxsize =
  3524. strlen(value) * 2 + 3; // allescaped+quotes+NULL
  3525. std::string result;
  3526. result.reserve(maxsize); // to avoid lots of mallocs
  3527. result += "\"";
  3528. for (const char* c = value; *c != 0; ++c) {
  3529. switch (*c) {
  3530. case '\"':
  3531. result += "\\\"";
  3532. break;
  3533. case '\\':
  3534. result += "\\\\";
  3535. break;
  3536. case '\b':
  3537. result += "\\b";
  3538. break;
  3539. case '\f':
  3540. result += "\\f";
  3541. break;
  3542. case '\n':
  3543. result += "\\n";
  3544. break;
  3545. case '\r':
  3546. result += "\\r";
  3547. break;
  3548. case '\t':
  3549. result += "\\t";
  3550. break;
  3551. // case '/':
  3552. // Even though \/ is considered a legal escape in JSON, a bare
  3553. // slash is also legal, so I see no reason to escape it.
  3554. // (I hope I am not misunderstanding something.
  3555. // blep notes: actually escaping \/ may be useful in javascript to avoid </
  3556. // sequence.
  3557. // Should add a flag to allow this compatibility mode and prevent this
  3558. // sequence from occurring.
  3559. default:
  3560. if (isControlCharacter(*c)) {
  3561. std::ostringstream oss;
  3562. oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
  3563. << std::setw(4) << static_cast<int>(*c);
  3564. result += oss.str();
  3565. } else {
  3566. result += *c;
  3567. }
  3568. break;
  3569. }
  3570. }
  3571. result += "\"";
  3572. return result;
  3573. }
  3574. // https://github.com/upcaste/upcaste/blob/master/src/upcore/src/cstring/strnpbrk.cpp
  3575. static char const* strnpbrk(char const* s, char const* accept, size_t n) {
  3576. assert((s || !n) && accept);
  3577. char const* const end = s + n;
  3578. for (char const* cur = s; cur < end; ++cur) {
  3579. int const c = *cur;
  3580. for (char const* a = accept; *a; ++a) {
  3581. if (*a == c) {
  3582. return cur;
  3583. }
  3584. }
  3585. }
  3586. return NULL;
  3587. }
  3588. static std::string valueToQuotedStringN(const char* value, unsigned length) {
  3589. if (value == NULL)
  3590. return "";
  3591. // Not sure how to handle unicode...
  3592. if (strnpbrk(value, "\"\\\b\f\n\r\t", length) == NULL &&
  3593. !containsControlCharacter0(value, length))
  3594. return std::string("\"") + value + "\"";
  3595. // We have to walk value and escape any special characters.
  3596. // Appending to std::string is not efficient, but this should be rare.
  3597. // (Note: forward slashes are *not* rare, but I am not escaping them.)
  3598. std::string::size_type maxsize =
  3599. length * 2 + 3; // allescaped+quotes+NULL
  3600. std::string result;
  3601. result.reserve(maxsize); // to avoid lots of mallocs
  3602. result += "\"";
  3603. char const* end = value + length;
  3604. for (const char* c = value; c != end; ++c) {
  3605. switch (*c) {
  3606. case '\"':
  3607. result += "\\\"";
  3608. break;
  3609. case '\\':
  3610. result += "\\\\";
  3611. break;
  3612. case '\b':
  3613. result += "\\b";
  3614. break;
  3615. case '\f':
  3616. result += "\\f";
  3617. break;
  3618. case '\n':
  3619. result += "\\n";
  3620. break;
  3621. case '\r':
  3622. result += "\\r";
  3623. break;
  3624. case '\t':
  3625. result += "\\t";
  3626. break;
  3627. // case '/':
  3628. // Even though \/ is considered a legal escape in JSON, a bare
  3629. // slash is also legal, so I see no reason to escape it.
  3630. // (I hope I am not misunderstanding something.)
  3631. // blep notes: actually escaping \/ may be useful in javascript to avoid </
  3632. // sequence.
  3633. // Should add a flag to allow this compatibility mode and prevent this
  3634. // sequence from occurring.
  3635. default:
  3636. if ((isControlCharacter(*c)) || (*c == 0)) {
  3637. std::ostringstream oss;
  3638. oss << "\\u" << std::hex << std::uppercase << std::setfill('0')
  3639. << std::setw(4) << static_cast<int>(*c);
  3640. result += oss.str();
  3641. } else {
  3642. result += *c;
  3643. }
  3644. break;
  3645. }
  3646. }
  3647. result += "\"";
  3648. return result;
  3649. }
  3650. // Class Writer
  3651. // //////////////////////////////////////////////////////////////////
  3652. Writer::~Writer() {}
  3653. // Class FastWriter
  3654. // //////////////////////////////////////////////////////////////////
  3655. FastWriter::FastWriter()
  3656. : yamlCompatiblityEnabled_(false) {}
  3657. void FastWriter::enableYAMLCompatibility() { yamlCompatiblityEnabled_ = true; }
  3658. std::string FastWriter::write(const Value& root) {
  3659. document_ = "";
  3660. writeValue(root);
  3661. document_ += "\n";
  3662. return document_;
  3663. }
  3664. void FastWriter::writeValue(const Value& value) {
  3665. switch (value.type()) {
  3666. case nullValue:
  3667. document_ += "null";
  3668. break;
  3669. case intValue:
  3670. document_ += valueToString(value.asLargestInt());
  3671. break;
  3672. case uintValue:
  3673. document_ += valueToString(value.asLargestUInt());
  3674. break;
  3675. case realValue:
  3676. document_ += valueToString(value.asDouble());
  3677. break;
  3678. case stringValue:
  3679. {
  3680. // Is NULL possible for value.string_?
  3681. char const* str;
  3682. char const* end;
  3683. bool ok = value.getString(&str, &end);
  3684. if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end-str));
  3685. break;
  3686. }
  3687. case booleanValue:
  3688. document_ += valueToString(value.asBool());
  3689. break;
  3690. case arrayValue: {
  3691. document_ += '[';
  3692. int size = value.size();
  3693. for (int index = 0; index < size; ++index) {
  3694. if (index > 0)
  3695. document_ += ',';
  3696. writeValue(value[index]);
  3697. }
  3698. document_ += ']';
  3699. } break;
  3700. case objectValue: {
  3701. Value::Members members(value.getMemberNames());
  3702. document_ += '{';
  3703. for (Value::Members::iterator it = members.begin(); it != members.end();
  3704. ++it) {
  3705. const std::string& name = *it;
  3706. if (it != members.begin())
  3707. document_ += ',';
  3708. document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length()));
  3709. document_ += yamlCompatiblityEnabled_ ? ": " : ":";
  3710. writeValue(value[name]);
  3711. }
  3712. document_ += '}';
  3713. } break;
  3714. }
  3715. }
  3716. // Class StyledWriter
  3717. // //////////////////////////////////////////////////////////////////
  3718. StyledWriter::StyledWriter()
  3719. : rightMargin_(74), indentSize_(3), addChildValues_() {}
  3720. std::string StyledWriter::write(const Value& root) {
  3721. document_ = "";
  3722. addChildValues_ = false;
  3723. indentString_ = "";
  3724. writeCommentBeforeValue(root);
  3725. writeValue(root);
  3726. writeCommentAfterValueOnSameLine(root);
  3727. document_ += "\n";
  3728. return document_;
  3729. }
  3730. void StyledWriter::writeValue(const Value& value) {
  3731. switch (value.type()) {
  3732. case nullValue:
  3733. pushValue("null");
  3734. break;
  3735. case intValue:
  3736. pushValue(valueToString(value.asLargestInt()));
  3737. break;
  3738. case uintValue:
  3739. pushValue(valueToString(value.asLargestUInt()));
  3740. break;
  3741. case realValue:
  3742. pushValue(valueToString(value.asDouble()));
  3743. break;
  3744. case stringValue:
  3745. {
  3746. // Is NULL possible for value.string_?
  3747. char const* str;
  3748. char const* end;
  3749. bool ok = value.getString(&str, &end);
  3750. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  3751. else pushValue("");
  3752. break;
  3753. }
  3754. case booleanValue:
  3755. pushValue(valueToString(value.asBool()));
  3756. break;
  3757. case arrayValue:
  3758. writeArrayValue(value);
  3759. break;
  3760. case objectValue: {
  3761. Value::Members members(value.getMemberNames());
  3762. if (members.empty())
  3763. pushValue("{}");
  3764. else {
  3765. writeWithIndent("{");
  3766. indent();
  3767. Value::Members::iterator it = members.begin();
  3768. for (;;) {
  3769. const std::string& name = *it;
  3770. const Value& childValue = value[name];
  3771. writeCommentBeforeValue(childValue);
  3772. writeWithIndent(valueToQuotedString(name.c_str()));
  3773. document_ += " : ";
  3774. writeValue(childValue);
  3775. if (++it == members.end()) {
  3776. writeCommentAfterValueOnSameLine(childValue);
  3777. break;
  3778. }
  3779. document_ += ',';
  3780. writeCommentAfterValueOnSameLine(childValue);
  3781. }
  3782. unindent();
  3783. writeWithIndent("}");
  3784. }
  3785. } break;
  3786. }
  3787. }
  3788. void StyledWriter::writeArrayValue(const Value& value) {
  3789. unsigned size = value.size();
  3790. if (size == 0)
  3791. pushValue("[]");
  3792. else {
  3793. bool isArrayMultiLine = isMultineArray(value);
  3794. if (isArrayMultiLine) {
  3795. writeWithIndent("[");
  3796. indent();
  3797. bool hasChildValue = !childValues_.empty();
  3798. unsigned index = 0;
  3799. for (;;) {
  3800. const Value& childValue = value[index];
  3801. writeCommentBeforeValue(childValue);
  3802. if (hasChildValue)
  3803. writeWithIndent(childValues_[index]);
  3804. else {
  3805. writeIndent();
  3806. writeValue(childValue);
  3807. }
  3808. if (++index == size) {
  3809. writeCommentAfterValueOnSameLine(childValue);
  3810. break;
  3811. }
  3812. document_ += ',';
  3813. writeCommentAfterValueOnSameLine(childValue);
  3814. }
  3815. unindent();
  3816. writeWithIndent("]");
  3817. } else // output on a single line
  3818. {
  3819. assert(childValues_.size() == size);
  3820. document_ += "[ ";
  3821. for (unsigned index = 0; index < size; ++index) {
  3822. if (index > 0)
  3823. document_ += ", ";
  3824. document_ += childValues_[index];
  3825. }
  3826. document_ += " ]";
  3827. }
  3828. }
  3829. }
  3830. bool StyledWriter::isMultineArray(const Value& value) {
  3831. int size = value.size();
  3832. bool isMultiLine = size * 3 >= rightMargin_;
  3833. childValues_.clear();
  3834. for (int index = 0; index < size && !isMultiLine; ++index) {
  3835. const Value& childValue = value[index];
  3836. isMultiLine =
  3837. isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
  3838. childValue.size() > 0);
  3839. }
  3840. if (!isMultiLine) // check if line length > max line length
  3841. {
  3842. childValues_.reserve(size);
  3843. addChildValues_ = true;
  3844. int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  3845. for (int index = 0; index < size; ++index) {
  3846. if (hasCommentForValue(value[index])) {
  3847. isMultiLine = true;
  3848. }
  3849. writeValue(value[index]);
  3850. lineLength += int(childValues_[index].length());
  3851. }
  3852. addChildValues_ = false;
  3853. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  3854. }
  3855. return isMultiLine;
  3856. }
  3857. void StyledWriter::pushValue(const std::string& value) {
  3858. if (addChildValues_)
  3859. childValues_.push_back(value);
  3860. else
  3861. document_ += value;
  3862. }
  3863. void StyledWriter::writeIndent() {
  3864. if (!document_.empty()) {
  3865. char last = document_[document_.length() - 1];
  3866. if (last == ' ') // already indented
  3867. return;
  3868. if (last != '\n') // Comments may add new-line
  3869. document_ += '\n';
  3870. }
  3871. document_ += indentString_;
  3872. }
  3873. void StyledWriter::writeWithIndent(const std::string& value) {
  3874. writeIndent();
  3875. document_ += value;
  3876. }
  3877. void StyledWriter::indent() { indentString_ += std::string(indentSize_, ' '); }
  3878. void StyledWriter::unindent() {
  3879. assert(int(indentString_.size()) >= indentSize_);
  3880. indentString_.resize(indentString_.size() - indentSize_);
  3881. }
  3882. void StyledWriter::writeCommentBeforeValue(const Value& root) {
  3883. if (!root.hasComment(commentBefore))
  3884. return;
  3885. document_ += "\n";
  3886. writeIndent();
  3887. const std::string& comment = root.getComment(commentBefore);
  3888. std::string::const_iterator iter = comment.begin();
  3889. while (iter != comment.end()) {
  3890. document_ += *iter;
  3891. if (*iter == '\n' &&
  3892. (iter != comment.end() && *(iter + 1) == '/'))
  3893. writeIndent();
  3894. ++iter;
  3895. }
  3896. // Comments are stripped of trailing newlines, so add one here
  3897. document_ += "\n";
  3898. }
  3899. void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) {
  3900. if (root.hasComment(commentAfterOnSameLine))
  3901. document_ += " " + root.getComment(commentAfterOnSameLine);
  3902. if (root.hasComment(commentAfter)) {
  3903. document_ += "\n";
  3904. document_ += root.getComment(commentAfter);
  3905. document_ += "\n";
  3906. }
  3907. }
  3908. bool StyledWriter::hasCommentForValue(const Value& value) {
  3909. return value.hasComment(commentBefore) ||
  3910. value.hasComment(commentAfterOnSameLine) ||
  3911. value.hasComment(commentAfter);
  3912. }
  3913. // Class StyledStreamWriter
  3914. // //////////////////////////////////////////////////////////////////
  3915. StyledStreamWriter::StyledStreamWriter(std::string indentation)
  3916. : document_(NULL), rightMargin_(74), indentation_(indentation),
  3917. addChildValues_() {}
  3918. void StyledStreamWriter::write(std::ostream& out, const Value& root) {
  3919. document_ = &out;
  3920. addChildValues_ = false;
  3921. indentString_ = "";
  3922. indented_ = true;
  3923. writeCommentBeforeValue(root);
  3924. if (!indented_) writeIndent();
  3925. indented_ = true;
  3926. writeValue(root);
  3927. writeCommentAfterValueOnSameLine(root);
  3928. *document_ << "\n";
  3929. document_ = NULL; // Forget the stream, for safety.
  3930. }
  3931. void StyledStreamWriter::writeValue(const Value& value) {
  3932. switch (value.type()) {
  3933. case nullValue:
  3934. pushValue("null");
  3935. break;
  3936. case intValue:
  3937. pushValue(valueToString(value.asLargestInt()));
  3938. break;
  3939. case uintValue:
  3940. pushValue(valueToString(value.asLargestUInt()));
  3941. break;
  3942. case realValue:
  3943. pushValue(valueToString(value.asDouble()));
  3944. break;
  3945. case stringValue:
  3946. {
  3947. // Is NULL possible for value.string_?
  3948. char const* str;
  3949. char const* end;
  3950. bool ok = value.getString(&str, &end);
  3951. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  3952. else pushValue("");
  3953. break;
  3954. }
  3955. case booleanValue:
  3956. pushValue(valueToString(value.asBool()));
  3957. break;
  3958. case arrayValue:
  3959. writeArrayValue(value);
  3960. break;
  3961. case objectValue: {
  3962. Value::Members members(value.getMemberNames());
  3963. if (members.empty())
  3964. pushValue("{}");
  3965. else {
  3966. writeWithIndent("{");
  3967. indent();
  3968. Value::Members::iterator it = members.begin();
  3969. for (;;) {
  3970. const std::string& name = *it;
  3971. const Value& childValue = value[name];
  3972. writeCommentBeforeValue(childValue);
  3973. writeWithIndent(valueToQuotedString(name.c_str()));
  3974. *document_ << " : ";
  3975. writeValue(childValue);
  3976. if (++it == members.end()) {
  3977. writeCommentAfterValueOnSameLine(childValue);
  3978. break;
  3979. }
  3980. *document_ << ",";
  3981. writeCommentAfterValueOnSameLine(childValue);
  3982. }
  3983. unindent();
  3984. writeWithIndent("}");
  3985. }
  3986. } break;
  3987. }
  3988. }
  3989. void StyledStreamWriter::writeArrayValue(const Value& value) {
  3990. unsigned size = value.size();
  3991. if (size == 0)
  3992. pushValue("[]");
  3993. else {
  3994. bool isArrayMultiLine = isMultineArray(value);
  3995. if (isArrayMultiLine) {
  3996. writeWithIndent("[");
  3997. indent();
  3998. bool hasChildValue = !childValues_.empty();
  3999. unsigned index = 0;
  4000. for (;;) {
  4001. const Value& childValue = value[index];
  4002. writeCommentBeforeValue(childValue);
  4003. if (hasChildValue)
  4004. writeWithIndent(childValues_[index]);
  4005. else {
  4006. if (!indented_) writeIndent();
  4007. indented_ = true;
  4008. writeValue(childValue);
  4009. indented_ = false;
  4010. }
  4011. if (++index == size) {
  4012. writeCommentAfterValueOnSameLine(childValue);
  4013. break;
  4014. }
  4015. *document_ << ",";
  4016. writeCommentAfterValueOnSameLine(childValue);
  4017. }
  4018. unindent();
  4019. writeWithIndent("]");
  4020. } else // output on a single line
  4021. {
  4022. assert(childValues_.size() == size);
  4023. *document_ << "[ ";
  4024. for (unsigned index = 0; index < size; ++index) {
  4025. if (index > 0)
  4026. *document_ << ", ";
  4027. *document_ << childValues_[index];
  4028. }
  4029. *document_ << " ]";
  4030. }
  4031. }
  4032. }
  4033. bool StyledStreamWriter::isMultineArray(const Value& value) {
  4034. int size = value.size();
  4035. bool isMultiLine = size * 3 >= rightMargin_;
  4036. childValues_.clear();
  4037. for (int index = 0; index < size && !isMultiLine; ++index) {
  4038. const Value& childValue = value[index];
  4039. isMultiLine =
  4040. isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
  4041. childValue.size() > 0);
  4042. }
  4043. if (!isMultiLine) // check if line length > max line length
  4044. {
  4045. childValues_.reserve(size);
  4046. addChildValues_ = true;
  4047. int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  4048. for (int index = 0; index < size; ++index) {
  4049. if (hasCommentForValue(value[index])) {
  4050. isMultiLine = true;
  4051. }
  4052. writeValue(value[index]);
  4053. lineLength += int(childValues_[index].length());
  4054. }
  4055. addChildValues_ = false;
  4056. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  4057. }
  4058. return isMultiLine;
  4059. }
  4060. void StyledStreamWriter::pushValue(const std::string& value) {
  4061. if (addChildValues_)
  4062. childValues_.push_back(value);
  4063. else
  4064. *document_ << value;
  4065. }
  4066. void StyledStreamWriter::writeIndent() {
  4067. // blep intended this to look at the so-far-written string
  4068. // to determine whether we are already indented, but
  4069. // with a stream we cannot do that. So we rely on some saved state.
  4070. // The caller checks indented_.
  4071. *document_ << '\n' << indentString_;
  4072. }
  4073. void StyledStreamWriter::writeWithIndent(const std::string& value) {
  4074. if (!indented_) writeIndent();
  4075. *document_ << value;
  4076. indented_ = false;
  4077. }
  4078. void StyledStreamWriter::indent() { indentString_ += indentation_; }
  4079. void StyledStreamWriter::unindent() {
  4080. assert(indentString_.size() >= indentation_.size());
  4081. indentString_.resize(indentString_.size() - indentation_.size());
  4082. }
  4083. void StyledStreamWriter::writeCommentBeforeValue(const Value& root) {
  4084. if (!root.hasComment(commentBefore))
  4085. return;
  4086. if (!indented_) writeIndent();
  4087. const std::string& comment = root.getComment(commentBefore);
  4088. std::string::const_iterator iter = comment.begin();
  4089. while (iter != comment.end()) {
  4090. *document_ << *iter;
  4091. if (*iter == '\n' &&
  4092. (iter != comment.end() && *(iter + 1) == '/'))
  4093. // writeIndent(); // would include newline
  4094. *document_ << indentString_;
  4095. ++iter;
  4096. }
  4097. indented_ = false;
  4098. }
  4099. void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) {
  4100. if (root.hasComment(commentAfterOnSameLine))
  4101. *document_ << ' ' << root.getComment(commentAfterOnSameLine);
  4102. if (root.hasComment(commentAfter)) {
  4103. writeIndent();
  4104. *document_ << root.getComment(commentAfter);
  4105. }
  4106. indented_ = false;
  4107. }
  4108. bool StyledStreamWriter::hasCommentForValue(const Value& value) {
  4109. return value.hasComment(commentBefore) ||
  4110. value.hasComment(commentAfterOnSameLine) ||
  4111. value.hasComment(commentAfter);
  4112. }
  4113. //////////////////////////
  4114. // BuiltStyledStreamWriter
  4115. /// Scoped enums are not available until C++11.
  4116. struct CommentStyle {
  4117. /// Decide whether to write comments.
  4118. enum Enum {
  4119. None, ///< Drop all comments.
  4120. Most, ///< Recover odd behavior of previous versions (not implemented yet).
  4121. All ///< Keep all comments.
  4122. };
  4123. };
  4124. struct BuiltStyledStreamWriter : public StreamWriter
  4125. {
  4126. BuiltStyledStreamWriter(
  4127. std::string const& indentation,
  4128. CommentStyle::Enum cs,
  4129. std::string const& colonSymbol,
  4130. std::string const& nullSymbol,
  4131. std::string const& endingLineFeedSymbol,
  4132. bool useSpecialFloats,
  4133. unsigned int precision);
  4134. virtual int write(Value const& root, std::ostream* sout);
  4135. private:
  4136. void writeValue(Value const& value);
  4137. void writeArrayValue(Value const& value);
  4138. bool isMultineArray(Value const& value);
  4139. void pushValue(std::string const& value);
  4140. void writeIndent();
  4141. void writeWithIndent(std::string const& value);
  4142. void indent();
  4143. void unindent();
  4144. void writeCommentBeforeValue(Value const& root);
  4145. void writeCommentAfterValueOnSameLine(Value const& root);
  4146. static bool hasCommentForValue(const Value& value);
  4147. typedef std::vector<std::string> ChildValues;
  4148. ChildValues childValues_;
  4149. std::string indentString_;
  4150. int rightMargin_;
  4151. std::string indentation_;
  4152. CommentStyle::Enum cs_;
  4153. std::string colonSymbol_;
  4154. std::string nullSymbol_;
  4155. std::string endingLineFeedSymbol_;
  4156. bool addChildValues_ : 1;
  4157. bool indented_ : 1;
  4158. bool useSpecialFloats_ : 1;
  4159. unsigned int precision_;
  4160. };
  4161. BuiltStyledStreamWriter::BuiltStyledStreamWriter(
  4162. std::string const& indentation,
  4163. CommentStyle::Enum cs,
  4164. std::string const& colonSymbol,
  4165. std::string const& nullSymbol,
  4166. std::string const& endingLineFeedSymbol,
  4167. bool useSpecialFloats,
  4168. unsigned int precision)
  4169. : rightMargin_(74)
  4170. , indentation_(indentation)
  4171. , cs_(cs)
  4172. , colonSymbol_(colonSymbol)
  4173. , nullSymbol_(nullSymbol)
  4174. , endingLineFeedSymbol_(endingLineFeedSymbol)
  4175. , addChildValues_(false)
  4176. , indented_(false)
  4177. , useSpecialFloats_(useSpecialFloats)
  4178. , precision_(precision)
  4179. {
  4180. }
  4181. int BuiltStyledStreamWriter::write(Value const& root, std::ostream* sout)
  4182. {
  4183. sout_ = sout;
  4184. addChildValues_ = false;
  4185. indented_ = true;
  4186. indentString_ = "";
  4187. writeCommentBeforeValue(root);
  4188. if (!indented_) writeIndent();
  4189. indented_ = true;
  4190. writeValue(root);
  4191. writeCommentAfterValueOnSameLine(root);
  4192. *sout_ << endingLineFeedSymbol_;
  4193. sout_ = NULL;
  4194. return 0;
  4195. }
  4196. void BuiltStyledStreamWriter::writeValue(Value const& value) {
  4197. switch (value.type()) {
  4198. case nullValue:
  4199. pushValue(nullSymbol_);
  4200. break;
  4201. case intValue:
  4202. pushValue(valueToString(value.asLargestInt()));
  4203. break;
  4204. case uintValue:
  4205. pushValue(valueToString(value.asLargestUInt()));
  4206. break;
  4207. case realValue:
  4208. pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_));
  4209. break;
  4210. case stringValue:
  4211. {
  4212. // Is NULL is possible for value.string_?
  4213. char const* str;
  4214. char const* end;
  4215. bool ok = value.getString(&str, &end);
  4216. if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end-str)));
  4217. else pushValue("");
  4218. break;
  4219. }
  4220. case booleanValue:
  4221. pushValue(valueToString(value.asBool()));
  4222. break;
  4223. case arrayValue:
  4224. writeArrayValue(value);
  4225. break;
  4226. case objectValue: {
  4227. Value::Members members(value.getMemberNames());
  4228. if (members.empty())
  4229. pushValue("{}");
  4230. else {
  4231. writeWithIndent("{");
  4232. indent();
  4233. Value::Members::iterator it = members.begin();
  4234. for (;;) {
  4235. std::string const& name = *it;
  4236. Value const& childValue = value[name];
  4237. writeCommentBeforeValue(childValue);
  4238. writeWithIndent(valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())));
  4239. *sout_ << colonSymbol_;
  4240. writeValue(childValue);
  4241. if (++it == members.end()) {
  4242. writeCommentAfterValueOnSameLine(childValue);
  4243. break;
  4244. }
  4245. *sout_ << ",";
  4246. writeCommentAfterValueOnSameLine(childValue);
  4247. }
  4248. unindent();
  4249. writeWithIndent("}");
  4250. }
  4251. } break;
  4252. }
  4253. }
  4254. void BuiltStyledStreamWriter::writeArrayValue(Value const& value) {
  4255. unsigned size = value.size();
  4256. if (size == 0)
  4257. pushValue("[]");
  4258. else {
  4259. bool isMultiLine = (cs_ == CommentStyle::All) || isMultineArray(value);
  4260. if (isMultiLine) {
  4261. writeWithIndent("[");
  4262. indent();
  4263. bool hasChildValue = !childValues_.empty();
  4264. unsigned index = 0;
  4265. for (;;) {
  4266. Value const& childValue = value[index];
  4267. writeCommentBeforeValue(childValue);
  4268. if (hasChildValue)
  4269. writeWithIndent(childValues_[index]);
  4270. else {
  4271. if (!indented_) writeIndent();
  4272. indented_ = true;
  4273. writeValue(childValue);
  4274. indented_ = false;
  4275. }
  4276. if (++index == size) {
  4277. writeCommentAfterValueOnSameLine(childValue);
  4278. break;
  4279. }
  4280. *sout_ << ",";
  4281. writeCommentAfterValueOnSameLine(childValue);
  4282. }
  4283. unindent();
  4284. writeWithIndent("]");
  4285. } else // output on a single line
  4286. {
  4287. assert(childValues_.size() == size);
  4288. *sout_ << "[";
  4289. if (!indentation_.empty()) *sout_ << " ";
  4290. for (unsigned index = 0; index < size; ++index) {
  4291. if (index > 0)
  4292. *sout_ << ", ";
  4293. *sout_ << childValues_[index];
  4294. }
  4295. if (!indentation_.empty()) *sout_ << " ";
  4296. *sout_ << "]";
  4297. }
  4298. }
  4299. }
  4300. bool BuiltStyledStreamWriter::isMultineArray(Value const& value) {
  4301. int size = value.size();
  4302. bool isMultiLine = size * 3 >= rightMargin_;
  4303. childValues_.clear();
  4304. for (int index = 0; index < size && !isMultiLine; ++index) {
  4305. Value const& childValue = value[index];
  4306. isMultiLine =
  4307. isMultiLine || ((childValue.isArray() || childValue.isObject()) &&
  4308. childValue.size() > 0);
  4309. }
  4310. if (!isMultiLine) // check if line length > max line length
  4311. {
  4312. childValues_.reserve(size);
  4313. addChildValues_ = true;
  4314. int lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]'
  4315. for (int index = 0; index < size; ++index) {
  4316. if (hasCommentForValue(value[index])) {
  4317. isMultiLine = true;
  4318. }
  4319. writeValue(value[index]);
  4320. lineLength += int(childValues_[index].length());
  4321. }
  4322. addChildValues_ = false;
  4323. isMultiLine = isMultiLine || lineLength >= rightMargin_;
  4324. }
  4325. return isMultiLine;
  4326. }
  4327. void BuiltStyledStreamWriter::pushValue(std::string const& value) {
  4328. if (addChildValues_)
  4329. childValues_.push_back(value);
  4330. else
  4331. *sout_ << value;
  4332. }
  4333. void BuiltStyledStreamWriter::writeIndent() {
  4334. // blep intended this to look at the so-far-written string
  4335. // to determine whether we are already indented, but
  4336. // with a stream we cannot do that. So we rely on some saved state.
  4337. // The caller checks indented_.
  4338. if (!indentation_.empty()) {
  4339. // In this case, drop newlines too.
  4340. *sout_ << '\n' << indentString_;
  4341. }
  4342. }
  4343. void BuiltStyledStreamWriter::writeWithIndent(std::string const& value) {
  4344. if (!indented_) writeIndent();
  4345. *sout_ << value;
  4346. indented_ = false;
  4347. }
  4348. void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; }
  4349. void BuiltStyledStreamWriter::unindent() {
  4350. assert(indentString_.size() >= indentation_.size());
  4351. indentString_.resize(indentString_.size() - indentation_.size());
  4352. }
  4353. void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) {
  4354. if (cs_ == CommentStyle::None) return;
  4355. if (!root.hasComment(commentBefore))
  4356. return;
  4357. if (!indented_) writeIndent();
  4358. const std::string& comment = root.getComment(commentBefore);
  4359. std::string::const_iterator iter = comment.begin();
  4360. while (iter != comment.end()) {
  4361. *sout_ << *iter;
  4362. if (*iter == '\n' &&
  4363. (iter != comment.end() && *(iter + 1) == '/'))
  4364. // writeIndent(); // would write extra newline
  4365. *sout_ << indentString_;
  4366. ++iter;
  4367. }
  4368. indented_ = false;
  4369. }
  4370. void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine(Value const& root) {
  4371. if (cs_ == CommentStyle::None) return;
  4372. if (root.hasComment(commentAfterOnSameLine))
  4373. *sout_ << " " + root.getComment(commentAfterOnSameLine);
  4374. if (root.hasComment(commentAfter)) {
  4375. writeIndent();
  4376. *sout_ << root.getComment(commentAfter);
  4377. }
  4378. }
  4379. // static
  4380. bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) {
  4381. return value.hasComment(commentBefore) ||
  4382. value.hasComment(commentAfterOnSameLine) ||
  4383. value.hasComment(commentAfter);
  4384. }
  4385. ///////////////
  4386. // StreamWriter
  4387. StreamWriter::StreamWriter()
  4388. : sout_(NULL)
  4389. {
  4390. }
  4391. StreamWriter::~StreamWriter()
  4392. {
  4393. }
  4394. StreamWriter::Factory::~Factory()
  4395. {}
  4396. StreamWriterBuilder::StreamWriterBuilder()
  4397. {
  4398. setDefaults(&settings_);
  4399. }
  4400. StreamWriterBuilder::~StreamWriterBuilder()
  4401. {}
  4402. StreamWriter* StreamWriterBuilder::newStreamWriter() const
  4403. {
  4404. std::string indentation = settings_["indentation"].asString();
  4405. std::string cs_str = settings_["commentStyle"].asString();
  4406. bool eyc = settings_["enableYAMLCompatibility"].asBool();
  4407. bool dnp = settings_["dropNullPlaceholders"].asBool();
  4408. bool usf = settings_["useSpecialFloats"].asBool();
  4409. unsigned int pre = settings_["precision"].asUInt();
  4410. CommentStyle::Enum cs = CommentStyle::All;
  4411. if (cs_str == "All") {
  4412. cs = CommentStyle::All;
  4413. } else if (cs_str == "None") {
  4414. cs = CommentStyle::None;
  4415. } else {
  4416. throwRuntimeError("commentStyle must be 'All' or 'None'");
  4417. }
  4418. std::string colonSymbol = " : ";
  4419. if (eyc) {
  4420. colonSymbol = ": ";
  4421. } else if (indentation.empty()) {
  4422. colonSymbol = ":";
  4423. }
  4424. std::string nullSymbol = "null";
  4425. if (dnp) {
  4426. nullSymbol = "";
  4427. }
  4428. if (pre > 17) pre = 17;
  4429. std::string endingLineFeedSymbol = "";
  4430. return new BuiltStyledStreamWriter(
  4431. indentation, cs,
  4432. colonSymbol, nullSymbol, endingLineFeedSymbol, usf, pre);
  4433. }
  4434. static void getValidWriterKeys(std::set<std::string>* valid_keys)
  4435. {
  4436. valid_keys->clear();
  4437. valid_keys->insert("indentation");
  4438. valid_keys->insert("commentStyle");
  4439. valid_keys->insert("enableYAMLCompatibility");
  4440. valid_keys->insert("dropNullPlaceholders");
  4441. valid_keys->insert("useSpecialFloats");
  4442. valid_keys->insert("precision");
  4443. }
  4444. bool StreamWriterBuilder::validate(Json::Value* invalid) const
  4445. {
  4446. Json::Value my_invalid;
  4447. if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL
  4448. Json::Value& inv = *invalid;
  4449. std::set<std::string> valid_keys;
  4450. getValidWriterKeys(&valid_keys);
  4451. Value::Members keys = settings_.getMemberNames();
  4452. size_t n = keys.size();
  4453. for (size_t i = 0; i < n; ++i) {
  4454. std::string const& key = keys[i];
  4455. if (valid_keys.find(key) == valid_keys.end()) {
  4456. inv[key] = settings_[key];
  4457. }
  4458. }
  4459. return 0u == inv.size();
  4460. }
  4461. Value& StreamWriterBuilder::operator[](std::string key)
  4462. {
  4463. return settings_[key];
  4464. }
  4465. // static
  4466. void StreamWriterBuilder::setDefaults(Json::Value* settings)
  4467. {
  4468. //! [StreamWriterBuilderDefaults]
  4469. (*settings)["commentStyle"] = "All";
  4470. (*settings)["indentation"] = "\t";
  4471. (*settings)["enableYAMLCompatibility"] = false;
  4472. (*settings)["dropNullPlaceholders"] = false;
  4473. (*settings)["useSpecialFloats"] = false;
  4474. (*settings)["precision"] = 17;
  4475. //! [StreamWriterBuilderDefaults]
  4476. }
  4477. std::string writeString(StreamWriter::Factory const& builder, Value const& root) {
  4478. std::ostringstream sout;
  4479. StreamWriterPtr const writer(builder.newStreamWriter());
  4480. writer->write(root, &sout);
  4481. return sout.str();
  4482. }
  4483. std::ostream& operator<<(std::ostream& sout, Value const& root) {
  4484. StreamWriterBuilder builder;
  4485. StreamWriterPtr const writer(builder.newStreamWriter());
  4486. writer->write(root, &sout);
  4487. return sout;
  4488. }
  4489. } // namespace Json
  4490. // //////////////////////////////////////////////////////////////////////
  4491. // End of content of file: src/lib_json/json_writer.cpp
  4492. // //////////////////////////////////////////////////////////////////////