jsoncpp.cpp 171 KB

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