jsoncpp.cpp 157 KB

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