jsoncpp.cpp 154 KB

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