jsoncpp.cpp 157 KB

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