jsoncpp.cpp 154 KB

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