json.hpp 502 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.0.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. SOFTWARE.
  23. */
  24. #ifndef NLOHMANN_JSON_HPP
  25. #define NLOHMANN_JSON_HPP
  26. #include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <ciso646> // and, not, or
  30. #include <clocale> // lconv, localeconv
  31. #include <cmath> // isfinite, labs, ldexp, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
  35. #include <cstring> // memcpy, strlen
  36. #include <forward_list> // forward_list
  37. #include <functional> // function, hash, less
  38. #include <initializer_list> // initializer_list
  39. #include <iomanip> // hex
  40. #include <iosfwd> // istream, ostream
  41. #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
  42. #include <limits> // numeric_limits
  43. #include <locale> // locale
  44. #include <map> // map
  45. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  46. #include <numeric> // accumulate
  47. #include <sstream> // stringstream
  48. #include <string> // getline, stoi, string, to_string
  49. #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
  50. #include <utility> // declval, forward, make_pair, move, pair, swap
  51. #include <valarray> // valarray
  52. #include <vector> // vector
  53. // exclude unsupported compilers
  54. #if defined(__clang__)
  55. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  56. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  57. #endif
  58. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  59. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  60. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  61. #endif
  62. #endif
  63. // disable float-equal warnings on GCC/clang
  64. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  65. #pragma GCC diagnostic push
  66. #pragma GCC diagnostic ignored "-Wfloat-equal"
  67. #endif
  68. // disable documentation warnings on clang
  69. #if defined(__clang__)
  70. #pragma GCC diagnostic push
  71. #pragma GCC diagnostic ignored "-Wdocumentation"
  72. #endif
  73. // allow for portable deprecation warnings
  74. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  75. #define JSON_DEPRECATED __attribute__((deprecated))
  76. #elif defined(_MSC_VER)
  77. #define JSON_DEPRECATED __declspec(deprecated)
  78. #else
  79. #define JSON_DEPRECATED
  80. #endif
  81. // allow to disable exceptions
  82. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
  83. #define JSON_THROW(exception) throw exception
  84. #define JSON_TRY try
  85. #define JSON_CATCH(exception) catch(exception)
  86. #else
  87. #define JSON_THROW(exception) std::abort()
  88. #define JSON_TRY if(true)
  89. #define JSON_CATCH(exception) if(false)
  90. #endif
  91. // manual branch prediction
  92. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  93. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  94. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  95. #else
  96. #define JSON_LIKELY(x) x
  97. #define JSON_UNLIKELY(x) x
  98. #endif
  99. // C++ language standard detection
  100. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  101. #define JSON_HAS_CPP_17
  102. #define JSON_HAS_CPP_14
  103. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  104. #define JSON_HAS_CPP_14
  105. #endif
  106. /*!
  107. @brief namespace for Niels Lohmann
  108. @see https://github.com/nlohmann
  109. @since version 1.0.0
  110. */
  111. namespace nlohmann
  112. {
  113. template<typename = void, typename = void>
  114. struct adl_serializer;
  115. // forward declaration of basic_json (required to split the class)
  116. template<template<typename, typename, typename...> class ObjectType = std::map,
  117. template<typename, typename...> class ArrayType = std::vector,
  118. class StringType = std::string, class BooleanType = bool,
  119. class NumberIntegerType = std::int64_t,
  120. class NumberUnsignedType = std::uint64_t,
  121. class NumberFloatType = double,
  122. template<typename> class AllocatorType = std::allocator,
  123. template<typename, typename = void> class JSONSerializer = adl_serializer>
  124. class basic_json;
  125. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  126. // may be removed in the future once the class is split.
  127. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  128. template<template<typename, typename, typename...> class ObjectType, \
  129. template<typename, typename...> class ArrayType, \
  130. class StringType, class BooleanType, class NumberIntegerType, \
  131. class NumberUnsignedType, class NumberFloatType, \
  132. template<typename> class AllocatorType, \
  133. template<typename, typename = void> class JSONSerializer>
  134. #define NLOHMANN_BASIC_JSON_TPL \
  135. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  136. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  137. AllocatorType, JSONSerializer>
  138. /*!
  139. @brief unnamed namespace with internal helper functions
  140. This namespace collects some functions that could not be defined inside the
  141. @ref basic_json class.
  142. @since version 2.1.0
  143. */
  144. namespace detail
  145. {
  146. ////////////////
  147. // exceptions //
  148. ////////////////
  149. /*!
  150. @brief general exception of the @ref basic_json class
  151. This class is an extension of `std::exception` objects with a member @a id for
  152. exception ids. It is used as the base class for all exceptions thrown by the
  153. @ref basic_json class. This class can hence be used as "wildcard" to catch
  154. exceptions.
  155. Subclasses:
  156. - @ref parse_error for exceptions indicating a parse error
  157. - @ref invalid_iterator for exceptions indicating errors with iterators
  158. - @ref type_error for exceptions indicating executing a member function with
  159. a wrong type
  160. - @ref out_of_range for exceptions indicating access out of the defined range
  161. - @ref other_error for exceptions indicating other library errors
  162. @internal
  163. @note To have nothrow-copy-constructible exceptions, we internally use
  164. `std::runtime_error` which can cope with arbitrary-length error messages.
  165. Intermediate strings are built with static functions and then passed to
  166. the actual constructor.
  167. @endinternal
  168. @liveexample{The following code shows how arbitrary library exceptions can be
  169. caught.,exception}
  170. @since version 3.0.0
  171. */
  172. class exception : public std::exception
  173. {
  174. public:
  175. /// returns the explanatory string
  176. const char* what() const noexcept override
  177. {
  178. return m.what();
  179. }
  180. /// the id of the exception
  181. const int id;
  182. protected:
  183. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  184. static std::string name(const std::string& ename, int id_)
  185. {
  186. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  187. }
  188. private:
  189. /// an exception object as storage for error messages
  190. std::runtime_error m;
  191. };
  192. /*!
  193. @brief exception indicating a parse error
  194. This exception is thrown by the library when a parse error occurs. Parse errors
  195. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  196. as when using JSON Patch.
  197. Member @a byte holds the byte index of the last read character in the input
  198. file.
  199. Exceptions have ids 1xx.
  200. name / id | example message | description
  201. ------------------------------ | --------------- | -------------------------
  202. json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
  203. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
  204. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
  205. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
  206. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
  207. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
  208. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
  209. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
  210. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  211. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
  212. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
  213. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
  214. @note For an input with n bytes, 1 is the index of the first character and n+1
  215. is the index of the terminating null byte or the end of file. This also
  216. holds true when reading a byte vector (CBOR or MessagePack).
  217. @liveexample{The following code shows how a `parse_error` exception can be
  218. caught.,parse_error}
  219. @sa @ref exception for the base class of the library exceptions
  220. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  221. @sa @ref type_error for exceptions indicating executing a member function with
  222. a wrong type
  223. @sa @ref out_of_range for exceptions indicating access out of the defined range
  224. @sa @ref other_error for exceptions indicating other library errors
  225. @since version 3.0.0
  226. */
  227. class parse_error : public exception
  228. {
  229. public:
  230. /*!
  231. @brief create a parse error exception
  232. @param[in] id_ the id of the exception
  233. @param[in] byte_ the byte index where the error occurred (or 0 if the
  234. position cannot be determined)
  235. @param[in] what_arg the explanatory string
  236. @return parse_error object
  237. */
  238. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  239. {
  240. std::string w = exception::name("parse_error", id_) + "parse error" +
  241. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  242. ": " + what_arg;
  243. return parse_error(id_, byte_, w.c_str());
  244. }
  245. /*!
  246. @brief byte index of the parse error
  247. The byte index of the last read character in the input file.
  248. @note For an input with n bytes, 1 is the index of the first character and
  249. n+1 is the index of the terminating null byte or the end of file.
  250. This also holds true when reading a byte vector (CBOR or MessagePack).
  251. */
  252. const std::size_t byte;
  253. private:
  254. parse_error(int id_, std::size_t byte_, const char* what_arg)
  255. : exception(id_, what_arg), byte(byte_) {}
  256. };
  257. /*!
  258. @brief exception indicating errors with iterators
  259. This exception is thrown if iterators passed to a library function do not match
  260. the expected semantics.
  261. Exceptions have ids 2xx.
  262. name / id | example message | description
  263. ----------------------------------- | --------------- | -------------------------
  264. json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  265. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
  266. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
  267. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
  268. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
  269. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
  270. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
  271. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  272. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  273. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  274. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
  275. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  276. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  277. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
  278. @liveexample{The following code shows how an `invalid_iterator` exception can be
  279. caught.,invalid_iterator}
  280. @sa @ref exception for the base class of the library exceptions
  281. @sa @ref parse_error for exceptions indicating a parse error
  282. @sa @ref type_error for exceptions indicating executing a member function with
  283. a wrong type
  284. @sa @ref out_of_range for exceptions indicating access out of the defined range
  285. @sa @ref other_error for exceptions indicating other library errors
  286. @since version 3.0.0
  287. */
  288. class invalid_iterator : public exception
  289. {
  290. public:
  291. static invalid_iterator create(int id_, const std::string& what_arg)
  292. {
  293. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  294. return invalid_iterator(id_, w.c_str());
  295. }
  296. private:
  297. invalid_iterator(int id_, const char* what_arg)
  298. : exception(id_, what_arg) {}
  299. };
  300. /*!
  301. @brief exception indicating executing a member function with a wrong type
  302. This exception is thrown in case of a type error; that is, a library function is
  303. executed on a JSON value whose type does not match the expected semantics.
  304. Exceptions have ids 3xx.
  305. name / id | example message | description
  306. ----------------------------- | --------------- | -------------------------
  307. json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
  308. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
  309. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
  310. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  311. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  312. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  313. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  314. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
  315. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  316. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  317. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
  318. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  319. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
  320. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  321. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
  322. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
  323. @liveexample{The following code shows how a `type_error` exception can be
  324. caught.,type_error}
  325. @sa @ref exception for the base class of the library exceptions
  326. @sa @ref parse_error for exceptions indicating a parse error
  327. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  328. @sa @ref out_of_range for exceptions indicating access out of the defined range
  329. @sa @ref other_error for exceptions indicating other library errors
  330. @since version 3.0.0
  331. */
  332. class type_error : public exception
  333. {
  334. public:
  335. static type_error create(int id_, const std::string& what_arg)
  336. {
  337. std::string w = exception::name("type_error", id_) + what_arg;
  338. return type_error(id_, w.c_str());
  339. }
  340. private:
  341. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  342. };
  343. /*!
  344. @brief exception indicating access out of the defined range
  345. This exception is thrown in case a library function is called on an input
  346. parameter that exceeds the expected range, for instance in case of array
  347. indices or nonexisting object keys.
  348. Exceptions have ids 4xx.
  349. name / id | example message | description
  350. ------------------------------- | --------------- | -------------------------
  351. json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
  352. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
  353. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  354. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  355. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
  356. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
  357. @liveexample{The following code shows how an `out_of_range` exception can be
  358. caught.,out_of_range}
  359. @sa @ref exception for the base class of the library exceptions
  360. @sa @ref parse_error for exceptions indicating a parse error
  361. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  362. @sa @ref type_error for exceptions indicating executing a member function with
  363. a wrong type
  364. @sa @ref other_error for exceptions indicating other library errors
  365. @since version 3.0.0
  366. */
  367. class out_of_range : public exception
  368. {
  369. public:
  370. static out_of_range create(int id_, const std::string& what_arg)
  371. {
  372. std::string w = exception::name("out_of_range", id_) + what_arg;
  373. return out_of_range(id_, w.c_str());
  374. }
  375. private:
  376. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  377. };
  378. /*!
  379. @brief exception indicating other library errors
  380. This exception is thrown in case of errors that cannot be classified with the
  381. other exception types.
  382. Exceptions have ids 5xx.
  383. name / id | example message | description
  384. ------------------------------ | --------------- | -------------------------
  385. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  386. @sa @ref exception for the base class of the library exceptions
  387. @sa @ref parse_error for exceptions indicating a parse error
  388. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  389. @sa @ref type_error for exceptions indicating executing a member function with
  390. a wrong type
  391. @sa @ref out_of_range for exceptions indicating access out of the defined range
  392. @liveexample{The following code shows how an `other_error` exception can be
  393. caught.,other_error}
  394. @since version 3.0.0
  395. */
  396. class other_error : public exception
  397. {
  398. public:
  399. static other_error create(int id_, const std::string& what_arg)
  400. {
  401. std::string w = exception::name("other_error", id_) + what_arg;
  402. return other_error(id_, w.c_str());
  403. }
  404. private:
  405. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  406. };
  407. ///////////////////////////
  408. // JSON type enumeration //
  409. ///////////////////////////
  410. /*!
  411. @brief the JSON type enumeration
  412. This enumeration collects the different JSON types. It is internally used to
  413. distinguish the stored values, and the functions @ref basic_json::is_null(),
  414. @ref basic_json::is_object(), @ref basic_json::is_array(),
  415. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  416. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  417. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  418. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  419. @ref basic_json::is_structured() rely on it.
  420. @note There are three enumeration entries (number_integer, number_unsigned, and
  421. number_float), because the library distinguishes these three types for numbers:
  422. @ref basic_json::number_unsigned_t is used for unsigned integers,
  423. @ref basic_json::number_integer_t is used for signed integers, and
  424. @ref basic_json::number_float_t is used for floating-point numbers or to
  425. approximate integers which do not fit in the limits of their respective type.
  426. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  427. value with the default value for a given type
  428. @since version 1.0.0
  429. */
  430. enum class value_t : uint8_t
  431. {
  432. null, ///< null value
  433. object, ///< object (unordered set of name/value pairs)
  434. array, ///< array (ordered collection of values)
  435. string, ///< string value
  436. boolean, ///< boolean value
  437. number_integer, ///< number value (signed integer)
  438. number_unsigned, ///< number value (unsigned integer)
  439. number_float, ///< number value (floating-point)
  440. discarded ///< discarded by the the parser callback function
  441. };
  442. /*!
  443. @brief comparison operator for JSON types
  444. Returns an ordering that is similar to Python:
  445. - order: null < boolean < number < object < array < string
  446. - furthermore, each type is not smaller than itself
  447. - discarded values are not comparable
  448. @since version 1.0.0
  449. */
  450. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  451. {
  452. static constexpr std::array<uint8_t, 8> order = {{
  453. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  454. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  455. }
  456. };
  457. const auto l_index = static_cast<std::size_t>(lhs);
  458. const auto r_index = static_cast<std::size_t>(rhs);
  459. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  460. }
  461. /////////////
  462. // helpers //
  463. /////////////
  464. template<typename> struct is_basic_json : std::false_type {};
  465. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  466. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  467. // alias templates to reduce boilerplate
  468. template<bool B, typename T = void>
  469. using enable_if_t = typename std::enable_if<B, T>::type;
  470. template<typename T>
  471. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  472. // implementation of C++14 index_sequence and affiliates
  473. // source: https://stackoverflow.com/a/32223343
  474. template<std::size_t... Ints>
  475. struct index_sequence
  476. {
  477. using type = index_sequence;
  478. using value_type = std::size_t;
  479. static constexpr std::size_t size() noexcept
  480. {
  481. return sizeof...(Ints);
  482. }
  483. };
  484. template<class Sequence1, class Sequence2>
  485. struct merge_and_renumber;
  486. template<std::size_t... I1, std::size_t... I2>
  487. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  488. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  489. template<std::size_t N>
  490. struct make_index_sequence
  491. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  492. typename make_index_sequence < N - N / 2 >::type > {};
  493. template<> struct make_index_sequence<0> : index_sequence<> {};
  494. template<> struct make_index_sequence<1> : index_sequence<0> {};
  495. template<typename... Ts>
  496. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  497. /*
  498. Implementation of two C++17 constructs: conjunction, negation. This is needed
  499. to avoid evaluating all the traits in a condition
  500. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  501. will not compile when T = void (on MSVC at least). Whereas
  502. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  503. stop evaluating if negation<...>::value == false
  504. Please note that those constructs must be used with caution, since symbols can
  505. become very long quickly (which can slow down compilation and cause MSVC
  506. internal compiler errors). Only use it when you have to (see example ahead).
  507. */
  508. template<class...> struct conjunction : std::true_type {};
  509. template<class B1> struct conjunction<B1> : B1 {};
  510. template<class B1, class... Bn>
  511. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  512. template<class B> struct negation : std::integral_constant<bool, not B::value> {};
  513. // dispatch utility (taken from ranges-v3)
  514. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  515. template<> struct priority_tag<0> {};
  516. //////////////////
  517. // constructors //
  518. //////////////////
  519. template<value_t> struct external_constructor;
  520. template<>
  521. struct external_constructor<value_t::boolean>
  522. {
  523. template<typename BasicJsonType>
  524. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  525. {
  526. j.m_type = value_t::boolean;
  527. j.m_value = b;
  528. j.assert_invariant();
  529. }
  530. };
  531. template<>
  532. struct external_constructor<value_t::string>
  533. {
  534. template<typename BasicJsonType>
  535. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  536. {
  537. j.m_type = value_t::string;
  538. j.m_value = s;
  539. j.assert_invariant();
  540. }
  541. template<typename BasicJsonType>
  542. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  543. {
  544. j.m_type = value_t::string;
  545. j.m_value = std::move(s);
  546. j.assert_invariant();
  547. }
  548. };
  549. template<>
  550. struct external_constructor<value_t::number_float>
  551. {
  552. template<typename BasicJsonType>
  553. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  554. {
  555. j.m_type = value_t::number_float;
  556. j.m_value = val;
  557. j.assert_invariant();
  558. }
  559. };
  560. template<>
  561. struct external_constructor<value_t::number_unsigned>
  562. {
  563. template<typename BasicJsonType>
  564. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  565. {
  566. j.m_type = value_t::number_unsigned;
  567. j.m_value = val;
  568. j.assert_invariant();
  569. }
  570. };
  571. template<>
  572. struct external_constructor<value_t::number_integer>
  573. {
  574. template<typename BasicJsonType>
  575. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  576. {
  577. j.m_type = value_t::number_integer;
  578. j.m_value = val;
  579. j.assert_invariant();
  580. }
  581. };
  582. template<>
  583. struct external_constructor<value_t::array>
  584. {
  585. template<typename BasicJsonType>
  586. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  587. {
  588. j.m_type = value_t::array;
  589. j.m_value = arr;
  590. j.assert_invariant();
  591. }
  592. template<typename BasicJsonType>
  593. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  594. {
  595. j.m_type = value_t::array;
  596. j.m_value = std::move(arr);
  597. j.assert_invariant();
  598. }
  599. template<typename BasicJsonType, typename CompatibleArrayType,
  600. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  601. int> = 0>
  602. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  603. {
  604. using std::begin;
  605. using std::end;
  606. j.m_type = value_t::array;
  607. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  608. j.assert_invariant();
  609. }
  610. template<typename BasicJsonType>
  611. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  612. {
  613. j.m_type = value_t::array;
  614. j.m_value = value_t::array;
  615. j.m_value.array->reserve(arr.size());
  616. for (const bool x : arr)
  617. {
  618. j.m_value.array->push_back(x);
  619. }
  620. j.assert_invariant();
  621. }
  622. template<typename BasicJsonType, typename T,
  623. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  624. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  625. {
  626. j.m_type = value_t::array;
  627. j.m_value = value_t::array;
  628. j.m_value.array->resize(arr.size());
  629. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  630. j.assert_invariant();
  631. }
  632. };
  633. template<>
  634. struct external_constructor<value_t::object>
  635. {
  636. template<typename BasicJsonType>
  637. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  638. {
  639. j.m_type = value_t::object;
  640. j.m_value = obj;
  641. j.assert_invariant();
  642. }
  643. template<typename BasicJsonType>
  644. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  645. {
  646. j.m_type = value_t::object;
  647. j.m_value = std::move(obj);
  648. j.assert_invariant();
  649. }
  650. template<typename BasicJsonType, typename CompatibleObjectType,
  651. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  652. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  653. {
  654. using std::begin;
  655. using std::end;
  656. j.m_type = value_t::object;
  657. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  658. j.assert_invariant();
  659. }
  660. };
  661. ////////////////////////
  662. // has_/is_ functions //
  663. ////////////////////////
  664. /*!
  665. @brief Helper to determine whether there's a key_type for T.
  666. This helper is used to tell associative containers apart from other containers
  667. such as sequence containers. For instance, `std::map` passes the test as it
  668. contains a `mapped_type`, whereas `std::vector` fails the test.
  669. @sa http://stackoverflow.com/a/7728728/266378
  670. @since version 1.0.0, overworked in version 2.0.6
  671. */
  672. #define NLOHMANN_JSON_HAS_HELPER(type) \
  673. template<typename T> struct has_##type { \
  674. private: \
  675. template<typename U, typename = typename U::type> \
  676. static int detect(U &&); \
  677. static void detect(...); \
  678. public: \
  679. static constexpr bool value = \
  680. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  681. }
  682. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  683. NLOHMANN_JSON_HAS_HELPER(key_type);
  684. NLOHMANN_JSON_HAS_HELPER(value_type);
  685. NLOHMANN_JSON_HAS_HELPER(iterator);
  686. #undef NLOHMANN_JSON_HAS_HELPER
  687. template<bool B, class RealType, class CompatibleObjectType>
  688. struct is_compatible_object_type_impl : std::false_type {};
  689. template<class RealType, class CompatibleObjectType>
  690. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  691. {
  692. static constexpr auto value =
  693. std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
  694. std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
  695. };
  696. template<class BasicJsonType, class CompatibleObjectType>
  697. struct is_compatible_object_type
  698. {
  699. static auto constexpr value = is_compatible_object_type_impl <
  700. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  701. has_mapped_type<CompatibleObjectType>,
  702. has_key_type<CompatibleObjectType>>::value,
  703. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  704. };
  705. template<typename BasicJsonType, typename T>
  706. struct is_basic_json_nested_type
  707. {
  708. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  709. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  710. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  711. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
  712. };
  713. template<class BasicJsonType, class CompatibleArrayType>
  714. struct is_compatible_array_type
  715. {
  716. static auto constexpr value =
  717. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  718. negation<is_compatible_object_type<
  719. BasicJsonType, CompatibleArrayType>>,
  720. negation<std::is_constructible<typename BasicJsonType::string_t,
  721. CompatibleArrayType>>,
  722. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  723. has_value_type<CompatibleArrayType>,
  724. has_iterator<CompatibleArrayType>>::value;
  725. };
  726. template<bool, typename, typename>
  727. struct is_compatible_integer_type_impl : std::false_type {};
  728. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  729. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  730. {
  731. // is there an assert somewhere on overflows?
  732. using RealLimits = std::numeric_limits<RealIntegerType>;
  733. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  734. static constexpr auto value =
  735. std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
  736. CompatibleLimits::is_integer and
  737. RealLimits::is_signed == CompatibleLimits::is_signed;
  738. };
  739. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  740. struct is_compatible_integer_type
  741. {
  742. static constexpr auto value =
  743. is_compatible_integer_type_impl <
  744. std::is_integral<CompatibleNumberIntegerType>::value and
  745. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  746. RealIntegerType, CompatibleNumberIntegerType >::value;
  747. };
  748. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  749. template<typename BasicJsonType, typename T>
  750. struct has_from_json
  751. {
  752. private:
  753. // also check the return type of from_json
  754. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  755. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  756. static int detect(U&&);
  757. static void detect(...);
  758. public:
  759. static constexpr bool value = std::is_integral<decltype(
  760. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  761. };
  762. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  763. // this overload is used for non-default-constructible user-defined-types
  764. template<typename BasicJsonType, typename T>
  765. struct has_non_default_from_json
  766. {
  767. private:
  768. template<typename U, typename =
  769. enable_if_t<std::is_same<T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value>>
  770. static int detect(U&&);
  771. static void detect(...);
  772. public:
  773. static constexpr bool value = std::is_integral<decltype(detect(
  774. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  775. };
  776. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  777. template<typename BasicJsonType, typename T>
  778. struct has_to_json
  779. {
  780. private:
  781. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  782. std::declval<BasicJsonType&>(), std::declval<T>()))>
  783. static int detect(U&&);
  784. static void detect(...);
  785. public:
  786. static constexpr bool value = std::is_integral<decltype(detect(
  787. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  788. };
  789. /////////////
  790. // to_json //
  791. /////////////
  792. template<typename BasicJsonType, typename T,
  793. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  794. void to_json(BasicJsonType& j, T b) noexcept
  795. {
  796. external_constructor<value_t::boolean>::construct(j, b);
  797. }
  798. template<typename BasicJsonType, typename CompatibleString,
  799. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  800. void to_json(BasicJsonType& j, const CompatibleString& s)
  801. {
  802. external_constructor<value_t::string>::construct(j, s);
  803. }
  804. template<typename BasicJsonType>
  805. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  806. {
  807. external_constructor<value_t::string>::construct(j, std::move(s));
  808. }
  809. template<typename BasicJsonType, typename FloatType,
  810. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  811. void to_json(BasicJsonType& j, FloatType val) noexcept
  812. {
  813. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  814. }
  815. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  816. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  817. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  818. {
  819. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  820. }
  821. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  822. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  823. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  824. {
  825. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  826. }
  827. template<typename BasicJsonType, typename EnumType,
  828. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  829. void to_json(BasicJsonType& j, EnumType e) noexcept
  830. {
  831. using underlying_type = typename std::underlying_type<EnumType>::type;
  832. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  833. }
  834. template<typename BasicJsonType>
  835. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  836. {
  837. external_constructor<value_t::array>::construct(j, e);
  838. }
  839. template<typename BasicJsonType, typename CompatibleArrayType,
  840. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  841. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  842. int> = 0>
  843. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  844. {
  845. external_constructor<value_t::array>::construct(j, arr);
  846. }
  847. template<typename BasicJsonType, typename T,
  848. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  849. void to_json(BasicJsonType& j, std::valarray<T> arr)
  850. {
  851. external_constructor<value_t::array>::construct(j, std::move(arr));
  852. }
  853. template<typename BasicJsonType>
  854. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  855. {
  856. external_constructor<value_t::array>::construct(j, std::move(arr));
  857. }
  858. template<typename BasicJsonType, typename CompatibleObjectType,
  859. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  860. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  861. {
  862. external_constructor<value_t::object>::construct(j, obj);
  863. }
  864. template<typename BasicJsonType>
  865. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  866. {
  867. external_constructor<value_t::object>::construct(j, std::move(obj));
  868. }
  869. template<typename BasicJsonType, typename T, std::size_t N,
  870. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
  871. void to_json(BasicJsonType& j, T (&arr)[N])
  872. {
  873. external_constructor<value_t::array>::construct(j, arr);
  874. }
  875. template<typename BasicJsonType, typename... Args>
  876. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  877. {
  878. j = {p.first, p.second};
  879. }
  880. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  881. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
  882. {
  883. j = {std::get<Idx>(t)...};
  884. }
  885. template<typename BasicJsonType, typename... Args>
  886. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  887. {
  888. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  889. }
  890. ///////////////
  891. // from_json //
  892. ///////////////
  893. // overloads for basic_json template parameters
  894. template<typename BasicJsonType, typename ArithmeticType,
  895. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  896. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  897. int> = 0>
  898. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  899. {
  900. switch (static_cast<value_t>(j))
  901. {
  902. case value_t::number_unsigned:
  903. {
  904. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  905. break;
  906. }
  907. case value_t::number_integer:
  908. {
  909. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  910. break;
  911. }
  912. case value_t::number_float:
  913. {
  914. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  915. break;
  916. }
  917. default:
  918. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  919. }
  920. }
  921. template<typename BasicJsonType>
  922. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  923. {
  924. if (JSON_UNLIKELY(not j.is_boolean()))
  925. {
  926. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  927. }
  928. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  929. }
  930. template<typename BasicJsonType>
  931. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  932. {
  933. if (JSON_UNLIKELY(not j.is_string()))
  934. {
  935. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  936. }
  937. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  938. }
  939. template<typename BasicJsonType>
  940. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  941. {
  942. get_arithmetic_value(j, val);
  943. }
  944. template<typename BasicJsonType>
  945. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  946. {
  947. get_arithmetic_value(j, val);
  948. }
  949. template<typename BasicJsonType>
  950. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  951. {
  952. get_arithmetic_value(j, val);
  953. }
  954. template<typename BasicJsonType, typename EnumType,
  955. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  956. void from_json(const BasicJsonType& j, EnumType& e)
  957. {
  958. typename std::underlying_type<EnumType>::type val;
  959. get_arithmetic_value(j, val);
  960. e = static_cast<EnumType>(val);
  961. }
  962. template<typename BasicJsonType>
  963. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  964. {
  965. if (JSON_UNLIKELY(not j.is_array()))
  966. {
  967. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  968. }
  969. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  970. }
  971. // forward_list doesn't have an insert method
  972. template<typename BasicJsonType, typename T, typename Allocator,
  973. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  974. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  975. {
  976. if (JSON_UNLIKELY(not j.is_array()))
  977. {
  978. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  979. }
  980. std::transform(j.rbegin(), j.rend(),
  981. std::front_inserter(l), [](const BasicJsonType & i)
  982. {
  983. return i.template get<T>();
  984. });
  985. }
  986. // valarray doesn't have an insert method
  987. template<typename BasicJsonType, typename T,
  988. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  989. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  990. {
  991. if (JSON_UNLIKELY(not j.is_array()))
  992. {
  993. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  994. }
  995. l.resize(j.size());
  996. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  997. }
  998. template<typename BasicJsonType, typename CompatibleArrayType>
  999. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
  1000. {
  1001. using std::end;
  1002. std::transform(j.begin(), j.end(),
  1003. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1004. {
  1005. // get<BasicJsonType>() returns *this, this won't call a from_json
  1006. // method when value_type is BasicJsonType
  1007. return i.template get<typename CompatibleArrayType::value_type>();
  1008. });
  1009. }
  1010. template<typename BasicJsonType, typename CompatibleArrayType>
  1011. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
  1012. -> decltype(
  1013. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  1014. void())
  1015. {
  1016. using std::end;
  1017. arr.reserve(j.size());
  1018. std::transform(j.begin(), j.end(),
  1019. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1020. {
  1021. // get<BasicJsonType>() returns *this, this won't call a from_json
  1022. // method when value_type is BasicJsonType
  1023. return i.template get<typename CompatibleArrayType::value_type>();
  1024. });
  1025. }
  1026. template<typename BasicJsonType, typename T, std::size_t N>
  1027. void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
  1028. {
  1029. for (std::size_t i = 0; i < N; ++i)
  1030. {
  1031. arr[i] = j.at(i).template get<T>();
  1032. }
  1033. }
  1034. template<typename BasicJsonType, typename CompatibleArrayType,
  1035. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  1036. std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
  1037. not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
  1038. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  1039. {
  1040. if (JSON_UNLIKELY(not j.is_array()))
  1041. {
  1042. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1043. }
  1044. from_json_array_impl(j, arr, priority_tag<2> {});
  1045. }
  1046. template<typename BasicJsonType, typename CompatibleObjectType,
  1047. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  1048. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  1049. {
  1050. if (JSON_UNLIKELY(not j.is_object()))
  1051. {
  1052. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  1053. }
  1054. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  1055. using value_type = typename CompatibleObjectType::value_type;
  1056. std::transform(
  1057. inner_object->begin(), inner_object->end(),
  1058. std::inserter(obj, obj.begin()),
  1059. [](typename BasicJsonType::object_t::value_type const & p)
  1060. {
  1061. return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
  1062. });
  1063. }
  1064. // overload for arithmetic types, not chosen for basic_json template arguments
  1065. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1066. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1067. // an arithmetic type?
  1068. template<typename BasicJsonType, typename ArithmeticType,
  1069. enable_if_t <
  1070. std::is_arithmetic<ArithmeticType>::value and
  1071. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1072. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1073. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1074. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1075. int> = 0>
  1076. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1077. {
  1078. switch (static_cast<value_t>(j))
  1079. {
  1080. case value_t::number_unsigned:
  1081. {
  1082. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1083. break;
  1084. }
  1085. case value_t::number_integer:
  1086. {
  1087. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1088. break;
  1089. }
  1090. case value_t::number_float:
  1091. {
  1092. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1093. break;
  1094. }
  1095. case value_t::boolean:
  1096. {
  1097. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1098. break;
  1099. }
  1100. default:
  1101. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1102. }
  1103. }
  1104. template<typename BasicJsonType, typename A1, typename A2>
  1105. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1106. {
  1107. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1108. }
  1109. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1110. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
  1111. {
  1112. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1113. }
  1114. template<typename BasicJsonType, typename... Args>
  1115. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1116. {
  1117. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1118. }
  1119. struct to_json_fn
  1120. {
  1121. private:
  1122. template<typename BasicJsonType, typename T>
  1123. auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1124. -> decltype(to_json(j, std::forward<T>(val)), void())
  1125. {
  1126. return to_json(j, std::forward<T>(val));
  1127. }
  1128. template<typename BasicJsonType, typename T>
  1129. void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1130. {
  1131. static_assert(sizeof(BasicJsonType) == 0,
  1132. "could not find to_json() method in T's namespace");
  1133. #ifdef _MSC_VER
  1134. // MSVC does not show a stacktrace for the above assert
  1135. using decayed = uncvref_t<T>;
  1136. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1137. "forcing MSVC stacktrace to show which T we're talking about.");
  1138. #endif
  1139. }
  1140. public:
  1141. template<typename BasicJsonType, typename T>
  1142. void operator()(BasicJsonType& j, T&& val) const
  1143. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  1144. {
  1145. return call(j, std::forward<T>(val), priority_tag<1> {});
  1146. }
  1147. };
  1148. struct from_json_fn
  1149. {
  1150. private:
  1151. template<typename BasicJsonType, typename T>
  1152. auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
  1153. noexcept(noexcept(from_json(j, val)))
  1154. -> decltype(from_json(j, val), void())
  1155. {
  1156. return from_json(j, val);
  1157. }
  1158. template<typename BasicJsonType, typename T>
  1159. void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1160. {
  1161. static_assert(sizeof(BasicJsonType) == 0,
  1162. "could not find from_json() method in T's namespace");
  1163. #ifdef _MSC_VER
  1164. // MSVC does not show a stacktrace for the above assert
  1165. using decayed = uncvref_t<T>;
  1166. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1167. "forcing MSVC stacktrace to show which T we're talking about.");
  1168. #endif
  1169. }
  1170. public:
  1171. template<typename BasicJsonType, typename T>
  1172. void operator()(const BasicJsonType& j, T& val) const
  1173. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  1174. {
  1175. return call(j, val, priority_tag<1> {});
  1176. }
  1177. };
  1178. // taken from ranges-v3
  1179. template<typename T>
  1180. struct static_const
  1181. {
  1182. static constexpr T value{};
  1183. };
  1184. template<typename T>
  1185. constexpr T static_const<T>::value;
  1186. ////////////////////
  1187. // input adapters //
  1188. ////////////////////
  1189. /*!
  1190. @brief abstract input adapter interface
  1191. Produces a stream of std::char_traits<char>::int_type characters from a
  1192. std::istream, a buffer, or some other input type. Accepts the return of exactly
  1193. one non-EOF character for future input. The int_type characters returned
  1194. consist of all valid char values as positive values (typically unsigned char),
  1195. plus an EOF value outside that range, specified by the value of the function
  1196. std::char_traits<char>::eof(). This value is typically -1, but could be any
  1197. arbitrary value which is not a valid char value.
  1198. */
  1199. struct input_adapter_protocol
  1200. {
  1201. /// get a character [0,255] or std::char_traits<char>::eof().
  1202. virtual std::char_traits<char>::int_type get_character() = 0;
  1203. /// restore the last non-eof() character to input
  1204. virtual void unget_character() = 0;
  1205. virtual ~input_adapter_protocol() = default;
  1206. };
  1207. /// a type to simplify interfaces
  1208. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1209. /*!
  1210. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1211. beginning of input. Does not support changing the underlying std::streambuf
  1212. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1213. subsequent use of standard std::istream operations to process any input
  1214. characters following those used in parsing the JSON input. Clears the
  1215. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1216. subsequent call for input from the std::istream.
  1217. */
  1218. class input_stream_adapter : public input_adapter_protocol
  1219. {
  1220. public:
  1221. ~input_stream_adapter() override
  1222. {
  1223. // clear stream flags; we use underlying streambuf I/O, do not
  1224. // maintain ifstream flags
  1225. is.clear();
  1226. }
  1227. explicit input_stream_adapter(std::istream& i)
  1228. : is(i), sb(*i.rdbuf())
  1229. {
  1230. // skip byte order mark
  1231. std::char_traits<char>::int_type c;
  1232. if ((c = get_character()) == 0xEF)
  1233. {
  1234. if ((c = get_character()) == 0xBB)
  1235. {
  1236. if ((c = get_character()) == 0xBF)
  1237. {
  1238. return; // Ignore BOM
  1239. }
  1240. else if (c != std::char_traits<char>::eof())
  1241. {
  1242. is.unget();
  1243. }
  1244. is.putback('\xBB');
  1245. }
  1246. else if (c != std::char_traits<char>::eof())
  1247. {
  1248. is.unget();
  1249. }
  1250. is.putback('\xEF');
  1251. }
  1252. else if (c != std::char_traits<char>::eof())
  1253. {
  1254. is.unget(); // no byte order mark; process as usual
  1255. }
  1256. }
  1257. // delete because of pointer members
  1258. input_stream_adapter(const input_stream_adapter&) = delete;
  1259. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  1260. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  1261. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  1262. // end up as the same value, eg. 0xFFFFFFFF.
  1263. std::char_traits<char>::int_type get_character() override
  1264. {
  1265. return sb.sbumpc();
  1266. }
  1267. void unget_character() override
  1268. {
  1269. sb.sungetc(); // is.unget() avoided for performance
  1270. }
  1271. private:
  1272. /// the associated input stream
  1273. std::istream& is;
  1274. std::streambuf& sb;
  1275. };
  1276. /// input adapter for buffer input
  1277. class input_buffer_adapter : public input_adapter_protocol
  1278. {
  1279. public:
  1280. input_buffer_adapter(const char* b, const std::size_t l)
  1281. : cursor(b), limit(b + l), start(b)
  1282. {
  1283. // skip byte order mark
  1284. if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
  1285. {
  1286. cursor += 3;
  1287. }
  1288. }
  1289. // delete because of pointer members
  1290. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1291. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1292. std::char_traits<char>::int_type get_character() noexcept override
  1293. {
  1294. if (JSON_LIKELY(cursor < limit))
  1295. {
  1296. return std::char_traits<char>::to_int_type(*(cursor++));
  1297. }
  1298. return std::char_traits<char>::eof();
  1299. }
  1300. void unget_character() noexcept override
  1301. {
  1302. if (JSON_LIKELY(cursor > start))
  1303. {
  1304. --cursor;
  1305. }
  1306. }
  1307. private:
  1308. /// pointer to the current character
  1309. const char* cursor;
  1310. /// pointer past the last character
  1311. const char* limit;
  1312. /// pointer to the first character
  1313. const char* start;
  1314. };
  1315. class input_adapter
  1316. {
  1317. public:
  1318. // native support
  1319. /// input adapter for input stream
  1320. input_adapter(std::istream& i)
  1321. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1322. /// input adapter for input stream
  1323. input_adapter(std::istream&& i)
  1324. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1325. /// input adapter for buffer
  1326. template<typename CharT,
  1327. typename std::enable_if<
  1328. std::is_pointer<CharT>::value and
  1329. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1330. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1331. int>::type = 0>
  1332. input_adapter(CharT b, std::size_t l)
  1333. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  1334. // derived support
  1335. /// input adapter for string literal
  1336. template<typename CharT,
  1337. typename std::enable_if<
  1338. std::is_pointer<CharT>::value and
  1339. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1340. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1341. int>::type = 0>
  1342. input_adapter(CharT b)
  1343. : input_adapter(reinterpret_cast<const char*>(b),
  1344. std::strlen(reinterpret_cast<const char*>(b))) {}
  1345. /// input adapter for iterator range with contiguous storage
  1346. template<class IteratorType,
  1347. typename std::enable_if<
  1348. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  1349. int>::type = 0>
  1350. input_adapter(IteratorType first, IteratorType last)
  1351. {
  1352. // assertion to check that the iterator range is indeed contiguous,
  1353. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  1354. assert(std::accumulate(
  1355. first, last, std::pair<bool, int>(true, 0),
  1356. [&first](std::pair<bool, int> res, decltype(*first) val)
  1357. {
  1358. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  1359. return res;
  1360. }).first);
  1361. // assertion to check that each element is 1 byte long
  1362. static_assert(
  1363. sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  1364. "each element in the iterator range must have the size of 1 byte");
  1365. const auto len = static_cast<size_t>(std::distance(first, last));
  1366. if (JSON_LIKELY(len > 0))
  1367. {
  1368. // there is at least one element: use the address of first
  1369. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  1370. }
  1371. else
  1372. {
  1373. // the address of first cannot be used: use nullptr
  1374. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  1375. }
  1376. }
  1377. /// input adapter for array
  1378. template<class T, std::size_t N>
  1379. input_adapter(T (&array)[N])
  1380. : input_adapter(std::begin(array), std::end(array)) {}
  1381. /// input adapter for contiguous container
  1382. template<class ContiguousContainer, typename
  1383. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  1384. std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  1385. int>::type = 0>
  1386. input_adapter(const ContiguousContainer& c)
  1387. : input_adapter(std::begin(c), std::end(c)) {}
  1388. operator input_adapter_t()
  1389. {
  1390. return ia;
  1391. }
  1392. private:
  1393. /// the actual adapter
  1394. input_adapter_t ia = nullptr;
  1395. };
  1396. //////////////////////
  1397. // lexer and parser //
  1398. //////////////////////
  1399. /*!
  1400. @brief lexical analysis
  1401. This class organizes the lexical analysis during JSON deserialization.
  1402. */
  1403. template<typename BasicJsonType>
  1404. class lexer
  1405. {
  1406. using number_integer_t = typename BasicJsonType::number_integer_t;
  1407. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  1408. using number_float_t = typename BasicJsonType::number_float_t;
  1409. public:
  1410. /// token types for the parser
  1411. enum class token_type
  1412. {
  1413. uninitialized, ///< indicating the scanner is uninitialized
  1414. literal_true, ///< the `true` literal
  1415. literal_false, ///< the `false` literal
  1416. literal_null, ///< the `null` literal
  1417. value_string, ///< a string -- use get_string() for actual value
  1418. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  1419. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  1420. value_float, ///< an floating point number -- use get_number_float() for actual value
  1421. begin_array, ///< the character for array begin `[`
  1422. begin_object, ///< the character for object begin `{`
  1423. end_array, ///< the character for array end `]`
  1424. end_object, ///< the character for object end `}`
  1425. name_separator, ///< the name separator `:`
  1426. value_separator, ///< the value separator `,`
  1427. parse_error, ///< indicating a parse error
  1428. end_of_input, ///< indicating the end of the input buffer
  1429. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  1430. };
  1431. /// return name of values of type token_type (only used for errors)
  1432. static const char* token_type_name(const token_type t) noexcept
  1433. {
  1434. switch (t)
  1435. {
  1436. case token_type::uninitialized:
  1437. return "<uninitialized>";
  1438. case token_type::literal_true:
  1439. return "true literal";
  1440. case token_type::literal_false:
  1441. return "false literal";
  1442. case token_type::literal_null:
  1443. return "null literal";
  1444. case token_type::value_string:
  1445. return "string literal";
  1446. case lexer::token_type::value_unsigned:
  1447. case lexer::token_type::value_integer:
  1448. case lexer::token_type::value_float:
  1449. return "number literal";
  1450. case token_type::begin_array:
  1451. return "'['";
  1452. case token_type::begin_object:
  1453. return "'{'";
  1454. case token_type::end_array:
  1455. return "']'";
  1456. case token_type::end_object:
  1457. return "'}'";
  1458. case token_type::name_separator:
  1459. return "':'";
  1460. case token_type::value_separator:
  1461. return "','";
  1462. case token_type::parse_error:
  1463. return "<parse error>";
  1464. case token_type::end_of_input:
  1465. return "end of input";
  1466. case token_type::literal_or_value:
  1467. return "'[', '{', or a literal";
  1468. default: // catch non-enum values
  1469. return "unknown token"; // LCOV_EXCL_LINE
  1470. }
  1471. }
  1472. explicit lexer(detail::input_adapter_t adapter)
  1473. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  1474. // delete because of pointer members
  1475. lexer(const lexer&) = delete;
  1476. lexer& operator=(lexer&) = delete;
  1477. private:
  1478. /////////////////////
  1479. // locales
  1480. /////////////////////
  1481. /// return the locale-dependent decimal point
  1482. static char get_decimal_point() noexcept
  1483. {
  1484. const auto loc = localeconv();
  1485. assert(loc != nullptr);
  1486. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  1487. }
  1488. /////////////////////
  1489. // scan functions
  1490. /////////////////////
  1491. /*!
  1492. @brief get codepoint from 4 hex characters following `\u`
  1493. For input "\u c1 c2 c3 c4" the codepoint is:
  1494. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  1495. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  1496. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  1497. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  1498. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  1499. between the ASCII value of the character and the desired integer value.
  1500. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  1501. non-hex character)
  1502. */
  1503. int get_codepoint()
  1504. {
  1505. // this function only makes sense after reading `\u`
  1506. assert(current == 'u');
  1507. int codepoint = 0;
  1508. const auto factors = { 12, 8, 4, 0 };
  1509. for (const auto factor : factors)
  1510. {
  1511. get();
  1512. if (current >= '0' and current <= '9')
  1513. {
  1514. codepoint += ((current - 0x30) << factor);
  1515. }
  1516. else if (current >= 'A' and current <= 'F')
  1517. {
  1518. codepoint += ((current - 0x37) << factor);
  1519. }
  1520. else if (current >= 'a' and current <= 'f')
  1521. {
  1522. codepoint += ((current - 0x57) << factor);
  1523. }
  1524. else
  1525. {
  1526. return -1;
  1527. }
  1528. }
  1529. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  1530. return codepoint;
  1531. }
  1532. /*!
  1533. @brief check if the next byte(s) are inside a given range
  1534. Adds the current byte and, for each passed range, reads a new byte and
  1535. checks if it is inside the range. If a violation was detected, set up an
  1536. error message and return false. Otherwise, return true.
  1537. @param[in] ranges list of integers; interpreted as list of pairs of
  1538. inclusive lower and upper bound, respectively
  1539. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  1540. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  1541. @return true if and only if no range violation was detected
  1542. */
  1543. bool next_byte_in_range(std::initializer_list<int> ranges)
  1544. {
  1545. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  1546. add(current);
  1547. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  1548. {
  1549. get();
  1550. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  1551. {
  1552. add(current);
  1553. }
  1554. else
  1555. {
  1556. error_message = "invalid string: ill-formed UTF-8 byte";
  1557. return false;
  1558. }
  1559. }
  1560. return true;
  1561. }
  1562. /*!
  1563. @brief scan a string literal
  1564. This function scans a string according to Sect. 7 of RFC 7159. While
  1565. scanning, bytes are escaped and copied into buffer yytext. Then the function
  1566. returns successfully, yytext is *not* null-terminated (as it may contain \0
  1567. bytes), and yytext.size() is the number of bytes in the string.
  1568. @return token_type::value_string if string could be successfully scanned,
  1569. token_type::parse_error otherwise
  1570. @note In case of errors, variable error_message contains a textual
  1571. description.
  1572. */
  1573. token_type scan_string()
  1574. {
  1575. // reset yytext (ignore opening quote)
  1576. reset();
  1577. // we entered the function by reading an open quote
  1578. assert(current == '\"');
  1579. while (true)
  1580. {
  1581. // get next character
  1582. switch (get())
  1583. {
  1584. // end of file while parsing string
  1585. case std::char_traits<char>::eof():
  1586. {
  1587. error_message = "invalid string: missing closing quote";
  1588. return token_type::parse_error;
  1589. }
  1590. // closing quote
  1591. case '\"':
  1592. {
  1593. return token_type::value_string;
  1594. }
  1595. // escapes
  1596. case '\\':
  1597. {
  1598. switch (get())
  1599. {
  1600. // quotation mark
  1601. case '\"':
  1602. add('\"');
  1603. break;
  1604. // reverse solidus
  1605. case '\\':
  1606. add('\\');
  1607. break;
  1608. // solidus
  1609. case '/':
  1610. add('/');
  1611. break;
  1612. // backspace
  1613. case 'b':
  1614. add('\b');
  1615. break;
  1616. // form feed
  1617. case 'f':
  1618. add('\f');
  1619. break;
  1620. // line feed
  1621. case 'n':
  1622. add('\n');
  1623. break;
  1624. // carriage return
  1625. case 'r':
  1626. add('\r');
  1627. break;
  1628. // tab
  1629. case 't':
  1630. add('\t');
  1631. break;
  1632. // unicode escapes
  1633. case 'u':
  1634. {
  1635. const int codepoint1 = get_codepoint();
  1636. int codepoint = codepoint1; // start with codepoint1
  1637. if (JSON_UNLIKELY(codepoint1 == -1))
  1638. {
  1639. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1640. return token_type::parse_error;
  1641. }
  1642. // check if code point is a high surrogate
  1643. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  1644. {
  1645. // expect next \uxxxx entry
  1646. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  1647. {
  1648. const int codepoint2 = get_codepoint();
  1649. if (JSON_UNLIKELY(codepoint2 == -1))
  1650. {
  1651. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1652. return token_type::parse_error;
  1653. }
  1654. // check if codepoint2 is a low surrogate
  1655. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  1656. {
  1657. // overwrite codepoint
  1658. codepoint =
  1659. // high surrogate occupies the most significant 22 bits
  1660. (codepoint1 << 10)
  1661. // low surrogate occupies the least significant 15 bits
  1662. + codepoint2
  1663. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  1664. // in the result so we have to subtract with:
  1665. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  1666. - 0x35FDC00;
  1667. }
  1668. else
  1669. {
  1670. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1671. return token_type::parse_error;
  1672. }
  1673. }
  1674. else
  1675. {
  1676. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1677. return token_type::parse_error;
  1678. }
  1679. }
  1680. else
  1681. {
  1682. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  1683. {
  1684. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  1685. return token_type::parse_error;
  1686. }
  1687. }
  1688. // result of the above calculation yields a proper codepoint
  1689. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  1690. // translate codepoint into bytes
  1691. if (codepoint < 0x80)
  1692. {
  1693. // 1-byte characters: 0xxxxxxx (ASCII)
  1694. add(codepoint);
  1695. }
  1696. else if (codepoint <= 0x7FF)
  1697. {
  1698. // 2-byte characters: 110xxxxx 10xxxxxx
  1699. add(0xC0 | (codepoint >> 6));
  1700. add(0x80 | (codepoint & 0x3F));
  1701. }
  1702. else if (codepoint <= 0xFFFF)
  1703. {
  1704. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  1705. add(0xE0 | (codepoint >> 12));
  1706. add(0x80 | ((codepoint >> 6) & 0x3F));
  1707. add(0x80 | (codepoint & 0x3F));
  1708. }
  1709. else
  1710. {
  1711. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1712. add(0xF0 | (codepoint >> 18));
  1713. add(0x80 | ((codepoint >> 12) & 0x3F));
  1714. add(0x80 | ((codepoint >> 6) & 0x3F));
  1715. add(0x80 | (codepoint & 0x3F));
  1716. }
  1717. break;
  1718. }
  1719. // other characters after escape
  1720. default:
  1721. error_message = "invalid string: forbidden character after backslash";
  1722. return token_type::parse_error;
  1723. }
  1724. break;
  1725. }
  1726. // invalid control characters
  1727. case 0x00:
  1728. case 0x01:
  1729. case 0x02:
  1730. case 0x03:
  1731. case 0x04:
  1732. case 0x05:
  1733. case 0x06:
  1734. case 0x07:
  1735. case 0x08:
  1736. case 0x09:
  1737. case 0x0A:
  1738. case 0x0B:
  1739. case 0x0C:
  1740. case 0x0D:
  1741. case 0x0E:
  1742. case 0x0F:
  1743. case 0x10:
  1744. case 0x11:
  1745. case 0x12:
  1746. case 0x13:
  1747. case 0x14:
  1748. case 0x15:
  1749. case 0x16:
  1750. case 0x17:
  1751. case 0x18:
  1752. case 0x19:
  1753. case 0x1A:
  1754. case 0x1B:
  1755. case 0x1C:
  1756. case 0x1D:
  1757. case 0x1E:
  1758. case 0x1F:
  1759. {
  1760. error_message = "invalid string: control character must be escaped";
  1761. return token_type::parse_error;
  1762. }
  1763. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  1764. case 0x20:
  1765. case 0x21:
  1766. case 0x23:
  1767. case 0x24:
  1768. case 0x25:
  1769. case 0x26:
  1770. case 0x27:
  1771. case 0x28:
  1772. case 0x29:
  1773. case 0x2A:
  1774. case 0x2B:
  1775. case 0x2C:
  1776. case 0x2D:
  1777. case 0x2E:
  1778. case 0x2F:
  1779. case 0x30:
  1780. case 0x31:
  1781. case 0x32:
  1782. case 0x33:
  1783. case 0x34:
  1784. case 0x35:
  1785. case 0x36:
  1786. case 0x37:
  1787. case 0x38:
  1788. case 0x39:
  1789. case 0x3A:
  1790. case 0x3B:
  1791. case 0x3C:
  1792. case 0x3D:
  1793. case 0x3E:
  1794. case 0x3F:
  1795. case 0x40:
  1796. case 0x41:
  1797. case 0x42:
  1798. case 0x43:
  1799. case 0x44:
  1800. case 0x45:
  1801. case 0x46:
  1802. case 0x47:
  1803. case 0x48:
  1804. case 0x49:
  1805. case 0x4A:
  1806. case 0x4B:
  1807. case 0x4C:
  1808. case 0x4D:
  1809. case 0x4E:
  1810. case 0x4F:
  1811. case 0x50:
  1812. case 0x51:
  1813. case 0x52:
  1814. case 0x53:
  1815. case 0x54:
  1816. case 0x55:
  1817. case 0x56:
  1818. case 0x57:
  1819. case 0x58:
  1820. case 0x59:
  1821. case 0x5A:
  1822. case 0x5B:
  1823. case 0x5D:
  1824. case 0x5E:
  1825. case 0x5F:
  1826. case 0x60:
  1827. case 0x61:
  1828. case 0x62:
  1829. case 0x63:
  1830. case 0x64:
  1831. case 0x65:
  1832. case 0x66:
  1833. case 0x67:
  1834. case 0x68:
  1835. case 0x69:
  1836. case 0x6A:
  1837. case 0x6B:
  1838. case 0x6C:
  1839. case 0x6D:
  1840. case 0x6E:
  1841. case 0x6F:
  1842. case 0x70:
  1843. case 0x71:
  1844. case 0x72:
  1845. case 0x73:
  1846. case 0x74:
  1847. case 0x75:
  1848. case 0x76:
  1849. case 0x77:
  1850. case 0x78:
  1851. case 0x79:
  1852. case 0x7A:
  1853. case 0x7B:
  1854. case 0x7C:
  1855. case 0x7D:
  1856. case 0x7E:
  1857. case 0x7F:
  1858. {
  1859. add(current);
  1860. break;
  1861. }
  1862. // U+0080..U+07FF: bytes C2..DF 80..BF
  1863. case 0xC2:
  1864. case 0xC3:
  1865. case 0xC4:
  1866. case 0xC5:
  1867. case 0xC6:
  1868. case 0xC7:
  1869. case 0xC8:
  1870. case 0xC9:
  1871. case 0xCA:
  1872. case 0xCB:
  1873. case 0xCC:
  1874. case 0xCD:
  1875. case 0xCE:
  1876. case 0xCF:
  1877. case 0xD0:
  1878. case 0xD1:
  1879. case 0xD2:
  1880. case 0xD3:
  1881. case 0xD4:
  1882. case 0xD5:
  1883. case 0xD6:
  1884. case 0xD7:
  1885. case 0xD8:
  1886. case 0xD9:
  1887. case 0xDA:
  1888. case 0xDB:
  1889. case 0xDC:
  1890. case 0xDD:
  1891. case 0xDE:
  1892. case 0xDF:
  1893. {
  1894. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  1895. {
  1896. return token_type::parse_error;
  1897. }
  1898. break;
  1899. }
  1900. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  1901. case 0xE0:
  1902. {
  1903. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  1904. {
  1905. return token_type::parse_error;
  1906. }
  1907. break;
  1908. }
  1909. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  1910. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  1911. case 0xE1:
  1912. case 0xE2:
  1913. case 0xE3:
  1914. case 0xE4:
  1915. case 0xE5:
  1916. case 0xE6:
  1917. case 0xE7:
  1918. case 0xE8:
  1919. case 0xE9:
  1920. case 0xEA:
  1921. case 0xEB:
  1922. case 0xEC:
  1923. case 0xEE:
  1924. case 0xEF:
  1925. {
  1926. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  1927. {
  1928. return token_type::parse_error;
  1929. }
  1930. break;
  1931. }
  1932. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  1933. case 0xED:
  1934. {
  1935. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  1936. {
  1937. return token_type::parse_error;
  1938. }
  1939. break;
  1940. }
  1941. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  1942. case 0xF0:
  1943. {
  1944. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  1945. {
  1946. return token_type::parse_error;
  1947. }
  1948. break;
  1949. }
  1950. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  1951. case 0xF1:
  1952. case 0xF2:
  1953. case 0xF3:
  1954. {
  1955. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  1956. {
  1957. return token_type::parse_error;
  1958. }
  1959. break;
  1960. }
  1961. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  1962. case 0xF4:
  1963. {
  1964. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  1965. {
  1966. return token_type::parse_error;
  1967. }
  1968. break;
  1969. }
  1970. // remaining bytes (80..C1 and F5..FF) are ill-formed
  1971. default:
  1972. {
  1973. error_message = "invalid string: ill-formed UTF-8 byte";
  1974. return token_type::parse_error;
  1975. }
  1976. }
  1977. }
  1978. }
  1979. static void strtof(float& f, const char* str, char** endptr) noexcept
  1980. {
  1981. f = std::strtof(str, endptr);
  1982. }
  1983. static void strtof(double& f, const char* str, char** endptr) noexcept
  1984. {
  1985. f = std::strtod(str, endptr);
  1986. }
  1987. static void strtof(long double& f, const char* str, char** endptr) noexcept
  1988. {
  1989. f = std::strtold(str, endptr);
  1990. }
  1991. /*!
  1992. @brief scan a number literal
  1993. This function scans a string according to Sect. 6 of RFC 7159.
  1994. The function is realized with a deterministic finite state machine derived
  1995. from the grammar described in RFC 7159. Starting in state "init", the
  1996. input is read and used to determined the next state. Only state "done"
  1997. accepts the number. State "error" is a trap state to model errors. In the
  1998. table below, "anything" means any character but the ones listed before.
  1999. state | 0 | 1-9 | e E | + | - | . | anything
  2000. ---------|----------|----------|----------|---------|---------|----------|-----------
  2001. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  2002. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  2003. zero | done | done | exponent | done | done | decimal1 | done
  2004. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  2005. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  2006. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  2007. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  2008. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  2009. any2 | any2 | any2 | done | done | done | done | done
  2010. The state machine is realized with one label per state (prefixed with
  2011. "scan_number_") and `goto` statements between them. The state machine
  2012. contains cycles, but any cycle can be left when EOF is read. Therefore,
  2013. the function is guaranteed to terminate.
  2014. During scanning, the read bytes are stored in yytext. This string is
  2015. then converted to a signed integer, an unsigned integer, or a
  2016. floating-point number.
  2017. @return token_type::value_unsigned, token_type::value_integer, or
  2018. token_type::value_float if number could be successfully scanned,
  2019. token_type::parse_error otherwise
  2020. @note The scanner is independent of the current locale. Internally, the
  2021. locale's decimal point is used instead of `.` to work with the
  2022. locale-dependent converters.
  2023. */
  2024. token_type scan_number()
  2025. {
  2026. // reset yytext to store the number's bytes
  2027. reset();
  2028. // the type of the parsed number; initially set to unsigned; will be
  2029. // changed if minus sign, decimal point or exponent is read
  2030. token_type number_type = token_type::value_unsigned;
  2031. // state (init): we just found out we need to scan a number
  2032. switch (current)
  2033. {
  2034. case '-':
  2035. {
  2036. add(current);
  2037. goto scan_number_minus;
  2038. }
  2039. case '0':
  2040. {
  2041. add(current);
  2042. goto scan_number_zero;
  2043. }
  2044. case '1':
  2045. case '2':
  2046. case '3':
  2047. case '4':
  2048. case '5':
  2049. case '6':
  2050. case '7':
  2051. case '8':
  2052. case '9':
  2053. {
  2054. add(current);
  2055. goto scan_number_any1;
  2056. }
  2057. default:
  2058. {
  2059. // all other characters are rejected outside scan_number()
  2060. assert(false); // LCOV_EXCL_LINE
  2061. }
  2062. }
  2063. scan_number_minus:
  2064. // state: we just parsed a leading minus sign
  2065. number_type = token_type::value_integer;
  2066. switch (get())
  2067. {
  2068. case '0':
  2069. {
  2070. add(current);
  2071. goto scan_number_zero;
  2072. }
  2073. case '1':
  2074. case '2':
  2075. case '3':
  2076. case '4':
  2077. case '5':
  2078. case '6':
  2079. case '7':
  2080. case '8':
  2081. case '9':
  2082. {
  2083. add(current);
  2084. goto scan_number_any1;
  2085. }
  2086. default:
  2087. {
  2088. error_message = "invalid number; expected digit after '-'";
  2089. return token_type::parse_error;
  2090. }
  2091. }
  2092. scan_number_zero:
  2093. // state: we just parse a zero (maybe with a leading minus sign)
  2094. switch (get())
  2095. {
  2096. case '.':
  2097. {
  2098. add(decimal_point_char);
  2099. goto scan_number_decimal1;
  2100. }
  2101. case 'e':
  2102. case 'E':
  2103. {
  2104. add(current);
  2105. goto scan_number_exponent;
  2106. }
  2107. default:
  2108. goto scan_number_done;
  2109. }
  2110. scan_number_any1:
  2111. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  2112. switch (get())
  2113. {
  2114. case '0':
  2115. case '1':
  2116. case '2':
  2117. case '3':
  2118. case '4':
  2119. case '5':
  2120. case '6':
  2121. case '7':
  2122. case '8':
  2123. case '9':
  2124. {
  2125. add(current);
  2126. goto scan_number_any1;
  2127. }
  2128. case '.':
  2129. {
  2130. add(decimal_point_char);
  2131. goto scan_number_decimal1;
  2132. }
  2133. case 'e':
  2134. case 'E':
  2135. {
  2136. add(current);
  2137. goto scan_number_exponent;
  2138. }
  2139. default:
  2140. goto scan_number_done;
  2141. }
  2142. scan_number_decimal1:
  2143. // state: we just parsed a decimal point
  2144. number_type = token_type::value_float;
  2145. switch (get())
  2146. {
  2147. case '0':
  2148. case '1':
  2149. case '2':
  2150. case '3':
  2151. case '4':
  2152. case '5':
  2153. case '6':
  2154. case '7':
  2155. case '8':
  2156. case '9':
  2157. {
  2158. add(current);
  2159. goto scan_number_decimal2;
  2160. }
  2161. default:
  2162. {
  2163. error_message = "invalid number; expected digit after '.'";
  2164. return token_type::parse_error;
  2165. }
  2166. }
  2167. scan_number_decimal2:
  2168. // we just parsed at least one number after a decimal point
  2169. switch (get())
  2170. {
  2171. case '0':
  2172. case '1':
  2173. case '2':
  2174. case '3':
  2175. case '4':
  2176. case '5':
  2177. case '6':
  2178. case '7':
  2179. case '8':
  2180. case '9':
  2181. {
  2182. add(current);
  2183. goto scan_number_decimal2;
  2184. }
  2185. case 'e':
  2186. case 'E':
  2187. {
  2188. add(current);
  2189. goto scan_number_exponent;
  2190. }
  2191. default:
  2192. goto scan_number_done;
  2193. }
  2194. scan_number_exponent:
  2195. // we just parsed an exponent
  2196. number_type = token_type::value_float;
  2197. switch (get())
  2198. {
  2199. case '+':
  2200. case '-':
  2201. {
  2202. add(current);
  2203. goto scan_number_sign;
  2204. }
  2205. case '0':
  2206. case '1':
  2207. case '2':
  2208. case '3':
  2209. case '4':
  2210. case '5':
  2211. case '6':
  2212. case '7':
  2213. case '8':
  2214. case '9':
  2215. {
  2216. add(current);
  2217. goto scan_number_any2;
  2218. }
  2219. default:
  2220. {
  2221. error_message =
  2222. "invalid number; expected '+', '-', or digit after exponent";
  2223. return token_type::parse_error;
  2224. }
  2225. }
  2226. scan_number_sign:
  2227. // we just parsed an exponent sign
  2228. switch (get())
  2229. {
  2230. case '0':
  2231. case '1':
  2232. case '2':
  2233. case '3':
  2234. case '4':
  2235. case '5':
  2236. case '6':
  2237. case '7':
  2238. case '8':
  2239. case '9':
  2240. {
  2241. add(current);
  2242. goto scan_number_any2;
  2243. }
  2244. default:
  2245. {
  2246. error_message = "invalid number; expected digit after exponent sign";
  2247. return token_type::parse_error;
  2248. }
  2249. }
  2250. scan_number_any2:
  2251. // we just parsed a number after the exponent or exponent sign
  2252. switch (get())
  2253. {
  2254. case '0':
  2255. case '1':
  2256. case '2':
  2257. case '3':
  2258. case '4':
  2259. case '5':
  2260. case '6':
  2261. case '7':
  2262. case '8':
  2263. case '9':
  2264. {
  2265. add(current);
  2266. goto scan_number_any2;
  2267. }
  2268. default:
  2269. goto scan_number_done;
  2270. }
  2271. scan_number_done:
  2272. // unget the character after the number (we only read it to know that
  2273. // we are done scanning a number)
  2274. unget();
  2275. char* endptr = nullptr;
  2276. errno = 0;
  2277. // try to parse integers first and fall back to floats
  2278. if (number_type == token_type::value_unsigned)
  2279. {
  2280. const auto x = std::strtoull(yytext.data(), &endptr, 10);
  2281. // we checked the number format before
  2282. assert(endptr == yytext.data() + yytext.size());
  2283. if (errno == 0)
  2284. {
  2285. value_unsigned = static_cast<number_unsigned_t>(x);
  2286. if (value_unsigned == x)
  2287. {
  2288. return token_type::value_unsigned;
  2289. }
  2290. }
  2291. }
  2292. else if (number_type == token_type::value_integer)
  2293. {
  2294. const auto x = std::strtoll(yytext.data(), &endptr, 10);
  2295. // we checked the number format before
  2296. assert(endptr == yytext.data() + yytext.size());
  2297. if (errno == 0)
  2298. {
  2299. value_integer = static_cast<number_integer_t>(x);
  2300. if (value_integer == x)
  2301. {
  2302. return token_type::value_integer;
  2303. }
  2304. }
  2305. }
  2306. // this code is reached if we parse a floating-point number or if an
  2307. // integer conversion above failed
  2308. strtof(value_float, yytext.data(), &endptr);
  2309. // we checked the number format before
  2310. assert(endptr == yytext.data() + yytext.size());
  2311. return token_type::value_float;
  2312. }
  2313. /*!
  2314. @param[in] literal_text the literal text to expect
  2315. @param[in] length the length of the passed literal text
  2316. @param[in] return_type the token type to return on success
  2317. */
  2318. token_type scan_literal(const char* literal_text, const std::size_t length,
  2319. token_type return_type)
  2320. {
  2321. assert(current == literal_text[0]);
  2322. for (std::size_t i = 1; i < length; ++i)
  2323. {
  2324. if (JSON_UNLIKELY(get() != literal_text[i]))
  2325. {
  2326. error_message = "invalid literal";
  2327. return token_type::parse_error;
  2328. }
  2329. }
  2330. return return_type;
  2331. }
  2332. /////////////////////
  2333. // input management
  2334. /////////////////////
  2335. /// reset yytext; current character is beginning of token
  2336. void reset() noexcept
  2337. {
  2338. yytext.clear();
  2339. token_string.clear();
  2340. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2341. }
  2342. /*
  2343. @brief get next character from the input
  2344. This function provides the interface to the used input adapter. It does
  2345. not throw in case the input reached EOF, but returns a
  2346. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  2347. for use in error messages.
  2348. @return character read from the input
  2349. */
  2350. std::char_traits<char>::int_type get()
  2351. {
  2352. ++chars_read;
  2353. current = ia->get_character();
  2354. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2355. {
  2356. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2357. }
  2358. return current;
  2359. }
  2360. /// unget current character (return it again on next get)
  2361. void unget()
  2362. {
  2363. --chars_read;
  2364. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2365. {
  2366. ia->unget_character();
  2367. assert(token_string.size() != 0);
  2368. token_string.pop_back();
  2369. }
  2370. }
  2371. /// add a character to yytext
  2372. void add(int c)
  2373. {
  2374. yytext.push_back(std::char_traits<char>::to_char_type(c));
  2375. }
  2376. public:
  2377. /////////////////////
  2378. // value getters
  2379. /////////////////////
  2380. /// return integer value
  2381. constexpr number_integer_t get_number_integer() const noexcept
  2382. {
  2383. return value_integer;
  2384. }
  2385. /// return unsigned integer value
  2386. constexpr number_unsigned_t get_number_unsigned() const noexcept
  2387. {
  2388. return value_unsigned;
  2389. }
  2390. /// return floating-point value
  2391. constexpr number_float_t get_number_float() const noexcept
  2392. {
  2393. return value_float;
  2394. }
  2395. /// return current string value (implicitly resets the token; useful only once)
  2396. std::string move_string()
  2397. {
  2398. return std::move(yytext);
  2399. }
  2400. /////////////////////
  2401. // diagnostics
  2402. /////////////////////
  2403. /// return position of last read token
  2404. constexpr std::size_t get_position() const noexcept
  2405. {
  2406. return chars_read;
  2407. }
  2408. /// return the last read token (for errors only). Will never contain EOF
  2409. /// (an arbitrary value that is not a valid char value, often -1), because
  2410. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  2411. std::string get_token_string() const
  2412. {
  2413. // escape control characters
  2414. std::string result;
  2415. for (const auto c : token_string)
  2416. {
  2417. if ('\x00' <= c and c <= '\x1F')
  2418. {
  2419. // escape control characters
  2420. std::stringstream ss;
  2421. ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
  2422. << std::hex << static_cast<int>(c) << ">";
  2423. result += ss.str();
  2424. }
  2425. else
  2426. {
  2427. // add character as is
  2428. result.push_back(c);
  2429. }
  2430. }
  2431. return result;
  2432. }
  2433. /// return syntax error message
  2434. constexpr const char* get_error_message() const noexcept
  2435. {
  2436. return error_message;
  2437. }
  2438. /////////////////////
  2439. // actual scanner
  2440. /////////////////////
  2441. token_type scan()
  2442. {
  2443. // read next character and ignore whitespace
  2444. do
  2445. {
  2446. get();
  2447. }
  2448. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  2449. switch (current)
  2450. {
  2451. // structural characters
  2452. case '[':
  2453. return token_type::begin_array;
  2454. case ']':
  2455. return token_type::end_array;
  2456. case '{':
  2457. return token_type::begin_object;
  2458. case '}':
  2459. return token_type::end_object;
  2460. case ':':
  2461. return token_type::name_separator;
  2462. case ',':
  2463. return token_type::value_separator;
  2464. // literals
  2465. case 't':
  2466. return scan_literal("true", 4, token_type::literal_true);
  2467. case 'f':
  2468. return scan_literal("false", 5, token_type::literal_false);
  2469. case 'n':
  2470. return scan_literal("null", 4, token_type::literal_null);
  2471. // string
  2472. case '\"':
  2473. return scan_string();
  2474. // number
  2475. case '-':
  2476. case '0':
  2477. case '1':
  2478. case '2':
  2479. case '3':
  2480. case '4':
  2481. case '5':
  2482. case '6':
  2483. case '7':
  2484. case '8':
  2485. case '9':
  2486. return scan_number();
  2487. // end of input (the null byte is needed when parsing from
  2488. // string literals)
  2489. case '\0':
  2490. case std::char_traits<char>::eof():
  2491. return token_type::end_of_input;
  2492. // error
  2493. default:
  2494. error_message = "invalid literal";
  2495. return token_type::parse_error;
  2496. }
  2497. }
  2498. private:
  2499. /// input adapter
  2500. detail::input_adapter_t ia = nullptr;
  2501. /// the current character
  2502. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  2503. /// the number of characters read
  2504. std::size_t chars_read = 0;
  2505. /// raw input token string (for error messages)
  2506. std::vector<char> token_string {};
  2507. /// buffer for variable-length tokens (numbers, strings)
  2508. std::string yytext {};
  2509. /// a description of occurred lexer errors
  2510. const char* error_message = "";
  2511. // number values
  2512. number_integer_t value_integer = 0;
  2513. number_unsigned_t value_unsigned = 0;
  2514. number_float_t value_float = 0;
  2515. /// the decimal point
  2516. const char decimal_point_char = '.';
  2517. };
  2518. /*!
  2519. @brief syntax analysis
  2520. This class implements a recursive decent parser.
  2521. */
  2522. template<typename BasicJsonType>
  2523. class parser
  2524. {
  2525. using number_integer_t = typename BasicJsonType::number_integer_t;
  2526. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2527. using number_float_t = typename BasicJsonType::number_float_t;
  2528. using lexer_t = lexer<BasicJsonType>;
  2529. using token_type = typename lexer_t::token_type;
  2530. public:
  2531. enum class parse_event_t : uint8_t
  2532. {
  2533. /// the parser read `{` and started to process a JSON object
  2534. object_start,
  2535. /// the parser read `}` and finished processing a JSON object
  2536. object_end,
  2537. /// the parser read `[` and started to process a JSON array
  2538. array_start,
  2539. /// the parser read `]` and finished processing a JSON array
  2540. array_end,
  2541. /// the parser read a key of a value in an object
  2542. key,
  2543. /// the parser finished reading a JSON value
  2544. value
  2545. };
  2546. using parser_callback_t =
  2547. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  2548. /// a parser reading from an input adapter
  2549. explicit parser(detail::input_adapter_t adapter,
  2550. const parser_callback_t cb = nullptr,
  2551. const bool allow_exceptions_ = true)
  2552. : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
  2553. {}
  2554. /*!
  2555. @brief public parser interface
  2556. @param[in] strict whether to expect the last token to be EOF
  2557. @param[in,out] result parsed JSON value
  2558. @throw parse_error.101 in case of an unexpected token
  2559. @throw parse_error.102 if to_unicode fails or surrogate error
  2560. @throw parse_error.103 if to_unicode fails
  2561. */
  2562. void parse(const bool strict, BasicJsonType& result)
  2563. {
  2564. // read first token
  2565. get_token();
  2566. parse_internal(true, result);
  2567. result.assert_invariant();
  2568. // in strict mode, input must be completely read
  2569. if (strict)
  2570. {
  2571. get_token();
  2572. expect(token_type::end_of_input);
  2573. }
  2574. // in case of an error, return discarded value
  2575. if (errored)
  2576. {
  2577. result = value_t::discarded;
  2578. return;
  2579. }
  2580. // set top-level value to null if it was discarded by the callback
  2581. // function
  2582. if (result.is_discarded())
  2583. {
  2584. result = nullptr;
  2585. }
  2586. }
  2587. /*!
  2588. @brief public accept interface
  2589. @param[in] strict whether to expect the last token to be EOF
  2590. @return whether the input is a proper JSON text
  2591. */
  2592. bool accept(const bool strict = true)
  2593. {
  2594. // read first token
  2595. get_token();
  2596. if (not accept_internal())
  2597. {
  2598. return false;
  2599. }
  2600. // strict => last token must be EOF
  2601. return not strict or (get_token() == token_type::end_of_input);
  2602. }
  2603. private:
  2604. /*!
  2605. @brief the actual parser
  2606. @throw parse_error.101 in case of an unexpected token
  2607. @throw parse_error.102 if to_unicode fails or surrogate error
  2608. @throw parse_error.103 if to_unicode fails
  2609. */
  2610. void parse_internal(bool keep, BasicJsonType& result)
  2611. {
  2612. // never parse after a parse error was detected
  2613. assert(not errored);
  2614. // start with a discarded value
  2615. if (not result.is_discarded())
  2616. {
  2617. result.m_value.destroy(result.m_type);
  2618. result.m_type = value_t::discarded;
  2619. }
  2620. switch (last_token)
  2621. {
  2622. case token_type::begin_object:
  2623. {
  2624. if (keep)
  2625. {
  2626. if (callback)
  2627. {
  2628. keep = callback(depth++, parse_event_t::object_start, result);
  2629. }
  2630. if (not callback or keep)
  2631. {
  2632. // explicitly set result to object to cope with {}
  2633. result.m_type = value_t::object;
  2634. result.m_value = value_t::object;
  2635. }
  2636. }
  2637. // read next token
  2638. get_token();
  2639. // closing } -> we are done
  2640. if (last_token == token_type::end_object)
  2641. {
  2642. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2643. {
  2644. result.m_value.destroy(result.m_type);
  2645. result.m_type = value_t::discarded;
  2646. }
  2647. break;
  2648. }
  2649. // parse values
  2650. std::string key;
  2651. BasicJsonType value;
  2652. while (true)
  2653. {
  2654. // store key
  2655. if (not expect(token_type::value_string))
  2656. {
  2657. return;
  2658. }
  2659. key = m_lexer.move_string();
  2660. bool keep_tag = false;
  2661. if (keep)
  2662. {
  2663. if (callback)
  2664. {
  2665. BasicJsonType k(key);
  2666. keep_tag = callback(depth, parse_event_t::key, k);
  2667. }
  2668. else
  2669. {
  2670. keep_tag = true;
  2671. }
  2672. }
  2673. // parse separator (:)
  2674. get_token();
  2675. if (not expect(token_type::name_separator))
  2676. {
  2677. return;
  2678. }
  2679. // parse and add value
  2680. get_token();
  2681. value.m_value.destroy(value.m_type);
  2682. value.m_type = value_t::discarded;
  2683. parse_internal(keep, value);
  2684. if (JSON_UNLIKELY(errored))
  2685. {
  2686. return;
  2687. }
  2688. if (keep and keep_tag and not value.is_discarded())
  2689. {
  2690. result.m_value.object->emplace(std::move(key), std::move(value));
  2691. }
  2692. // comma -> next value
  2693. get_token();
  2694. if (last_token == token_type::value_separator)
  2695. {
  2696. get_token();
  2697. continue;
  2698. }
  2699. // closing }
  2700. if (not expect(token_type::end_object))
  2701. {
  2702. return;
  2703. }
  2704. break;
  2705. }
  2706. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2707. {
  2708. result.m_value.destroy(result.m_type);
  2709. result.m_type = value_t::discarded;
  2710. }
  2711. break;
  2712. }
  2713. case token_type::begin_array:
  2714. {
  2715. if (keep)
  2716. {
  2717. if (callback)
  2718. {
  2719. keep = callback(depth++, parse_event_t::array_start, result);
  2720. }
  2721. if (not callback or keep)
  2722. {
  2723. // explicitly set result to array to cope with []
  2724. result.m_type = value_t::array;
  2725. result.m_value = value_t::array;
  2726. }
  2727. }
  2728. // read next token
  2729. get_token();
  2730. // closing ] -> we are done
  2731. if (last_token == token_type::end_array)
  2732. {
  2733. if (callback and not callback(--depth, parse_event_t::array_end, result))
  2734. {
  2735. result.m_value.destroy(result.m_type);
  2736. result.m_type = value_t::discarded;
  2737. }
  2738. break;
  2739. }
  2740. // parse values
  2741. BasicJsonType value;
  2742. while (true)
  2743. {
  2744. // parse value
  2745. value.m_value.destroy(value.m_type);
  2746. value.m_type = value_t::discarded;
  2747. parse_internal(keep, value);
  2748. if (JSON_UNLIKELY(errored))
  2749. {
  2750. return;
  2751. }
  2752. if (keep and not value.is_discarded())
  2753. {
  2754. result.m_value.array->push_back(std::move(value));
  2755. }
  2756. // comma -> next value
  2757. get_token();
  2758. if (last_token == token_type::value_separator)
  2759. {
  2760. get_token();
  2761. continue;
  2762. }
  2763. // closing ]
  2764. if (not expect(token_type::end_array))
  2765. {
  2766. return;
  2767. }
  2768. break;
  2769. }
  2770. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  2771. {
  2772. result.m_value.destroy(result.m_type);
  2773. result.m_type = value_t::discarded;
  2774. }
  2775. break;
  2776. }
  2777. case token_type::literal_null:
  2778. {
  2779. result.m_type = value_t::null;
  2780. break;
  2781. }
  2782. case token_type::value_string:
  2783. {
  2784. result.m_type = value_t::string;
  2785. result.m_value = m_lexer.move_string();
  2786. break;
  2787. }
  2788. case token_type::literal_true:
  2789. {
  2790. result.m_type = value_t::boolean;
  2791. result.m_value = true;
  2792. break;
  2793. }
  2794. case token_type::literal_false:
  2795. {
  2796. result.m_type = value_t::boolean;
  2797. result.m_value = false;
  2798. break;
  2799. }
  2800. case token_type::value_unsigned:
  2801. {
  2802. result.m_type = value_t::number_unsigned;
  2803. result.m_value = m_lexer.get_number_unsigned();
  2804. break;
  2805. }
  2806. case token_type::value_integer:
  2807. {
  2808. result.m_type = value_t::number_integer;
  2809. result.m_value = m_lexer.get_number_integer();
  2810. break;
  2811. }
  2812. case token_type::value_float:
  2813. {
  2814. result.m_type = value_t::number_float;
  2815. result.m_value = m_lexer.get_number_float();
  2816. // throw in case of infinity or NAN
  2817. if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
  2818. {
  2819. if (allow_exceptions)
  2820. {
  2821. JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
  2822. m_lexer.get_token_string() + "'"));
  2823. }
  2824. expect(token_type::uninitialized);
  2825. }
  2826. break;
  2827. }
  2828. case token_type::parse_error:
  2829. {
  2830. // using "uninitialized" to avoid "expected" message
  2831. if (not expect(token_type::uninitialized))
  2832. {
  2833. return;
  2834. }
  2835. break; // LCOV_EXCL_LINE
  2836. }
  2837. default:
  2838. {
  2839. // the last token was unexpected; we expected a value
  2840. if (not expect(token_type::literal_or_value))
  2841. {
  2842. return;
  2843. }
  2844. break; // LCOV_EXCL_LINE
  2845. }
  2846. }
  2847. if (keep and callback and not callback(depth, parse_event_t::value, result))
  2848. {
  2849. result.m_type = value_t::discarded;
  2850. }
  2851. }
  2852. /*!
  2853. @brief the actual acceptor
  2854. @invariant 1. The last token is not yet processed. Therefore, the caller
  2855. of this function must make sure a token has been read.
  2856. 2. When this function returns, the last token is processed.
  2857. That is, the last read character was already considered.
  2858. This invariant makes sure that no token needs to be "unput".
  2859. */
  2860. bool accept_internal()
  2861. {
  2862. switch (last_token)
  2863. {
  2864. case token_type::begin_object:
  2865. {
  2866. // read next token
  2867. get_token();
  2868. // closing } -> we are done
  2869. if (last_token == token_type::end_object)
  2870. {
  2871. return true;
  2872. }
  2873. // parse values
  2874. while (true)
  2875. {
  2876. // parse key
  2877. if (last_token != token_type::value_string)
  2878. {
  2879. return false;
  2880. }
  2881. // parse separator (:)
  2882. get_token();
  2883. if (last_token != token_type::name_separator)
  2884. {
  2885. return false;
  2886. }
  2887. // parse value
  2888. get_token();
  2889. if (not accept_internal())
  2890. {
  2891. return false;
  2892. }
  2893. // comma -> next value
  2894. get_token();
  2895. if (last_token == token_type::value_separator)
  2896. {
  2897. get_token();
  2898. continue;
  2899. }
  2900. // closing }
  2901. return (last_token == token_type::end_object);
  2902. }
  2903. }
  2904. case token_type::begin_array:
  2905. {
  2906. // read next token
  2907. get_token();
  2908. // closing ] -> we are done
  2909. if (last_token == token_type::end_array)
  2910. {
  2911. return true;
  2912. }
  2913. // parse values
  2914. while (true)
  2915. {
  2916. // parse value
  2917. if (not accept_internal())
  2918. {
  2919. return false;
  2920. }
  2921. // comma -> next value
  2922. get_token();
  2923. if (last_token == token_type::value_separator)
  2924. {
  2925. get_token();
  2926. continue;
  2927. }
  2928. // closing ]
  2929. return (last_token == token_type::end_array);
  2930. }
  2931. }
  2932. case token_type::value_float:
  2933. {
  2934. // reject infinity or NAN
  2935. return std::isfinite(m_lexer.get_number_float());
  2936. }
  2937. case token_type::literal_false:
  2938. case token_type::literal_null:
  2939. case token_type::literal_true:
  2940. case token_type::value_integer:
  2941. case token_type::value_string:
  2942. case token_type::value_unsigned:
  2943. return true;
  2944. default: // the last token was unexpected
  2945. return false;
  2946. }
  2947. }
  2948. /// get next token from lexer
  2949. token_type get_token()
  2950. {
  2951. return (last_token = m_lexer.scan());
  2952. }
  2953. /*!
  2954. @throw parse_error.101 if expected token did not occur
  2955. */
  2956. bool expect(token_type t)
  2957. {
  2958. if (JSON_UNLIKELY(t != last_token))
  2959. {
  2960. errored = true;
  2961. expected = t;
  2962. if (allow_exceptions)
  2963. {
  2964. throw_exception();
  2965. }
  2966. else
  2967. {
  2968. return false;
  2969. }
  2970. }
  2971. return true;
  2972. }
  2973. [[noreturn]] void throw_exception() const
  2974. {
  2975. std::string error_msg = "syntax error - ";
  2976. if (last_token == token_type::parse_error)
  2977. {
  2978. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  2979. m_lexer.get_token_string() + "'";
  2980. }
  2981. else
  2982. {
  2983. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  2984. }
  2985. if (expected != token_type::uninitialized)
  2986. {
  2987. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  2988. }
  2989. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  2990. }
  2991. private:
  2992. /// current level of recursion
  2993. int depth = 0;
  2994. /// callback function
  2995. const parser_callback_t callback = nullptr;
  2996. /// the type of the last read token
  2997. token_type last_token = token_type::uninitialized;
  2998. /// the lexer
  2999. lexer_t m_lexer;
  3000. /// whether a syntax error occurred
  3001. bool errored = false;
  3002. /// possible reason for the syntax error
  3003. token_type expected = token_type::uninitialized;
  3004. /// whether to throw exceptions in case of errors
  3005. const bool allow_exceptions = true;
  3006. };
  3007. ///////////////
  3008. // iterators //
  3009. ///////////////
  3010. /*!
  3011. @brief an iterator for primitive JSON types
  3012. This class models an iterator for primitive JSON types (boolean, number,
  3013. string). It's only purpose is to allow the iterator/const_iterator classes
  3014. to "iterate" over primitive values. Internally, the iterator is modeled by
  3015. a `difference_type` variable. Value begin_value (`0`) models the begin,
  3016. end_value (`1`) models past the end.
  3017. */
  3018. class primitive_iterator_t
  3019. {
  3020. public:
  3021. using difference_type = std::ptrdiff_t;
  3022. constexpr difference_type get_value() const noexcept
  3023. {
  3024. return m_it;
  3025. }
  3026. /// set iterator to a defined beginning
  3027. void set_begin() noexcept
  3028. {
  3029. m_it = begin_value;
  3030. }
  3031. /// set iterator to a defined past the end
  3032. void set_end() noexcept
  3033. {
  3034. m_it = end_value;
  3035. }
  3036. /// return whether the iterator can be dereferenced
  3037. constexpr bool is_begin() const noexcept
  3038. {
  3039. return m_it == begin_value;
  3040. }
  3041. /// return whether the iterator is at end
  3042. constexpr bool is_end() const noexcept
  3043. {
  3044. return m_it == end_value;
  3045. }
  3046. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3047. {
  3048. return lhs.m_it == rhs.m_it;
  3049. }
  3050. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3051. {
  3052. return lhs.m_it < rhs.m_it;
  3053. }
  3054. primitive_iterator_t operator+(difference_type i)
  3055. {
  3056. auto result = *this;
  3057. result += i;
  3058. return result;
  3059. }
  3060. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3061. {
  3062. return lhs.m_it - rhs.m_it;
  3063. }
  3064. friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
  3065. {
  3066. return os << it.m_it;
  3067. }
  3068. primitive_iterator_t& operator++()
  3069. {
  3070. ++m_it;
  3071. return *this;
  3072. }
  3073. primitive_iterator_t const operator++(int)
  3074. {
  3075. auto result = *this;
  3076. m_it++;
  3077. return result;
  3078. }
  3079. primitive_iterator_t& operator--()
  3080. {
  3081. --m_it;
  3082. return *this;
  3083. }
  3084. primitive_iterator_t const operator--(int)
  3085. {
  3086. auto result = *this;
  3087. m_it--;
  3088. return result;
  3089. }
  3090. primitive_iterator_t& operator+=(difference_type n)
  3091. {
  3092. m_it += n;
  3093. return *this;
  3094. }
  3095. primitive_iterator_t& operator-=(difference_type n)
  3096. {
  3097. m_it -= n;
  3098. return *this;
  3099. }
  3100. private:
  3101. static constexpr difference_type begin_value = 0;
  3102. static constexpr difference_type end_value = begin_value + 1;
  3103. /// iterator as signed integer type
  3104. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  3105. };
  3106. /*!
  3107. @brief an iterator value
  3108. @note This structure could easily be a union, but MSVC currently does not allow
  3109. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  3110. */
  3111. template<typename BasicJsonType> struct internal_iterator
  3112. {
  3113. /// iterator for JSON objects
  3114. typename BasicJsonType::object_t::iterator object_iterator {};
  3115. /// iterator for JSON arrays
  3116. typename BasicJsonType::array_t::iterator array_iterator {};
  3117. /// generic iterator for all other types
  3118. primitive_iterator_t primitive_iterator {};
  3119. };
  3120. template<typename IteratorType> class iteration_proxy;
  3121. /*!
  3122. @brief a template for a bidirectional iterator for the @ref basic_json class
  3123. This class implements a both iterators (iterator and const_iterator) for the
  3124. @ref basic_json class.
  3125. @note An iterator is called *initialized* when a pointer to a JSON value has
  3126. been set (e.g., by a constructor or a copy assignment). If the iterator is
  3127. default-constructed, it is *uninitialized* and most methods are undefined.
  3128. **The library uses assertions to detect calls on uninitialized iterators.**
  3129. @requirement The class satisfies the following concept requirements:
  3130. -
  3131. [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
  3132. The iterator that can be moved can be moved in both directions (i.e.
  3133. incremented and decremented).
  3134. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  3135. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  3136. */
  3137. template<typename BasicJsonType>
  3138. class iter_impl
  3139. {
  3140. /// allow basic_json to access private members
  3141. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  3142. friend BasicJsonType;
  3143. friend iteration_proxy<iter_impl>;
  3144. using object_t = typename BasicJsonType::object_t;
  3145. using array_t = typename BasicJsonType::array_t;
  3146. // make sure BasicJsonType is basic_json or const basic_json
  3147. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  3148. "iter_impl only accepts (const) basic_json");
  3149. public:
  3150. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  3151. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  3152. /// A user-defined iterator should provide publicly accessible typedefs named
  3153. /// iterator_category, value_type, difference_type, pointer, and reference.
  3154. /// Note that value_type is required to be non-const, even for constant iterators.
  3155. using iterator_category = std::bidirectional_iterator_tag;
  3156. /// the type of the values when the iterator is dereferenced
  3157. using value_type = typename BasicJsonType::value_type;
  3158. /// a type to represent differences between iterators
  3159. using difference_type = typename BasicJsonType::difference_type;
  3160. /// defines a pointer to the type iterated over (value_type)
  3161. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  3162. typename BasicJsonType::const_pointer,
  3163. typename BasicJsonType::pointer>::type;
  3164. /// defines a reference to the type iterated over (value_type)
  3165. using reference =
  3166. typename std::conditional<std::is_const<BasicJsonType>::value,
  3167. typename BasicJsonType::const_reference,
  3168. typename BasicJsonType::reference>::type;
  3169. /// default constructor
  3170. iter_impl() = default;
  3171. /*!
  3172. @brief constructor for a given JSON instance
  3173. @param[in] object pointer to a JSON object for this iterator
  3174. @pre object != nullptr
  3175. @post The iterator is initialized; i.e. `m_object != nullptr`.
  3176. */
  3177. explicit iter_impl(pointer object) noexcept : m_object(object)
  3178. {
  3179. assert(m_object != nullptr);
  3180. switch (m_object->m_type)
  3181. {
  3182. case value_t::object:
  3183. {
  3184. m_it.object_iterator = typename object_t::iterator();
  3185. break;
  3186. }
  3187. case value_t::array:
  3188. {
  3189. m_it.array_iterator = typename array_t::iterator();
  3190. break;
  3191. }
  3192. default:
  3193. {
  3194. m_it.primitive_iterator = primitive_iterator_t();
  3195. break;
  3196. }
  3197. }
  3198. }
  3199. /*!
  3200. @note The conventional copy constructor and copy assignment are implicitly
  3201. defined. Combined with the following converting constructor and
  3202. assignment, they support: (1) copy from iterator to iterator, (2)
  3203. copy from const iterator to const iterator, and (3) conversion from
  3204. iterator to const iterator. However conversion from const iterator
  3205. to iterator is not defined.
  3206. */
  3207. /*!
  3208. @brief converting constructor
  3209. @param[in] other non-const iterator to copy from
  3210. @note It is not checked whether @a other is initialized.
  3211. */
  3212. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3213. : m_object(other.m_object), m_it(other.m_it) {}
  3214. /*!
  3215. @brief converting assignment
  3216. @param[in,out] other non-const iterator to copy from
  3217. @return const/non-const iterator
  3218. @note It is not checked whether @a other is initialized.
  3219. */
  3220. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3221. {
  3222. m_object = other.m_object;
  3223. m_it = other.m_it;
  3224. return *this;
  3225. }
  3226. private:
  3227. /*!
  3228. @brief set the iterator to the first value
  3229. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3230. */
  3231. void set_begin() noexcept
  3232. {
  3233. assert(m_object != nullptr);
  3234. switch (m_object->m_type)
  3235. {
  3236. case value_t::object:
  3237. {
  3238. m_it.object_iterator = m_object->m_value.object->begin();
  3239. break;
  3240. }
  3241. case value_t::array:
  3242. {
  3243. m_it.array_iterator = m_object->m_value.array->begin();
  3244. break;
  3245. }
  3246. case value_t::null:
  3247. {
  3248. // set to end so begin()==end() is true: null is empty
  3249. m_it.primitive_iterator.set_end();
  3250. break;
  3251. }
  3252. default:
  3253. {
  3254. m_it.primitive_iterator.set_begin();
  3255. break;
  3256. }
  3257. }
  3258. }
  3259. /*!
  3260. @brief set the iterator past the last value
  3261. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3262. */
  3263. void set_end() noexcept
  3264. {
  3265. assert(m_object != nullptr);
  3266. switch (m_object->m_type)
  3267. {
  3268. case value_t::object:
  3269. {
  3270. m_it.object_iterator = m_object->m_value.object->end();
  3271. break;
  3272. }
  3273. case value_t::array:
  3274. {
  3275. m_it.array_iterator = m_object->m_value.array->end();
  3276. break;
  3277. }
  3278. default:
  3279. {
  3280. m_it.primitive_iterator.set_end();
  3281. break;
  3282. }
  3283. }
  3284. }
  3285. public:
  3286. /*!
  3287. @brief return a reference to the value pointed to by the iterator
  3288. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3289. */
  3290. reference operator*() const
  3291. {
  3292. assert(m_object != nullptr);
  3293. switch (m_object->m_type)
  3294. {
  3295. case value_t::object:
  3296. {
  3297. assert(m_it.object_iterator != m_object->m_value.object->end());
  3298. return m_it.object_iterator->second;
  3299. }
  3300. case value_t::array:
  3301. {
  3302. assert(m_it.array_iterator != m_object->m_value.array->end());
  3303. return *m_it.array_iterator;
  3304. }
  3305. case value_t::null:
  3306. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3307. default:
  3308. {
  3309. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3310. {
  3311. return *m_object;
  3312. }
  3313. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3314. }
  3315. }
  3316. }
  3317. /*!
  3318. @brief dereference the iterator
  3319. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3320. */
  3321. pointer operator->() const
  3322. {
  3323. assert(m_object != nullptr);
  3324. switch (m_object->m_type)
  3325. {
  3326. case value_t::object:
  3327. {
  3328. assert(m_it.object_iterator != m_object->m_value.object->end());
  3329. return &(m_it.object_iterator->second);
  3330. }
  3331. case value_t::array:
  3332. {
  3333. assert(m_it.array_iterator != m_object->m_value.array->end());
  3334. return &*m_it.array_iterator;
  3335. }
  3336. default:
  3337. {
  3338. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3339. {
  3340. return m_object;
  3341. }
  3342. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3343. }
  3344. }
  3345. }
  3346. /*!
  3347. @brief post-increment (it++)
  3348. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3349. */
  3350. iter_impl const operator++(int)
  3351. {
  3352. auto result = *this;
  3353. ++(*this);
  3354. return result;
  3355. }
  3356. /*!
  3357. @brief pre-increment (++it)
  3358. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3359. */
  3360. iter_impl& operator++()
  3361. {
  3362. assert(m_object != nullptr);
  3363. switch (m_object->m_type)
  3364. {
  3365. case value_t::object:
  3366. {
  3367. std::advance(m_it.object_iterator, 1);
  3368. break;
  3369. }
  3370. case value_t::array:
  3371. {
  3372. std::advance(m_it.array_iterator, 1);
  3373. break;
  3374. }
  3375. default:
  3376. {
  3377. ++m_it.primitive_iterator;
  3378. break;
  3379. }
  3380. }
  3381. return *this;
  3382. }
  3383. /*!
  3384. @brief post-decrement (it--)
  3385. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3386. */
  3387. iter_impl const operator--(int)
  3388. {
  3389. auto result = *this;
  3390. --(*this);
  3391. return result;
  3392. }
  3393. /*!
  3394. @brief pre-decrement (--it)
  3395. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3396. */
  3397. iter_impl& operator--()
  3398. {
  3399. assert(m_object != nullptr);
  3400. switch (m_object->m_type)
  3401. {
  3402. case value_t::object:
  3403. {
  3404. std::advance(m_it.object_iterator, -1);
  3405. break;
  3406. }
  3407. case value_t::array:
  3408. {
  3409. std::advance(m_it.array_iterator, -1);
  3410. break;
  3411. }
  3412. default:
  3413. {
  3414. --m_it.primitive_iterator;
  3415. break;
  3416. }
  3417. }
  3418. return *this;
  3419. }
  3420. /*!
  3421. @brief comparison: equal
  3422. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3423. */
  3424. bool operator==(const iter_impl& other) const
  3425. {
  3426. // if objects are not the same, the comparison is undefined
  3427. if (JSON_UNLIKELY(m_object != other.m_object))
  3428. {
  3429. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3430. }
  3431. assert(m_object != nullptr);
  3432. switch (m_object->m_type)
  3433. {
  3434. case value_t::object:
  3435. return (m_it.object_iterator == other.m_it.object_iterator);
  3436. case value_t::array:
  3437. return (m_it.array_iterator == other.m_it.array_iterator);
  3438. default:
  3439. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  3440. }
  3441. }
  3442. /*!
  3443. @brief comparison: not equal
  3444. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3445. */
  3446. bool operator!=(const iter_impl& other) const
  3447. {
  3448. return not operator==(other);
  3449. }
  3450. /*!
  3451. @brief comparison: smaller
  3452. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3453. */
  3454. bool operator<(const iter_impl& other) const
  3455. {
  3456. // if objects are not the same, the comparison is undefined
  3457. if (JSON_UNLIKELY(m_object != other.m_object))
  3458. {
  3459. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3460. }
  3461. assert(m_object != nullptr);
  3462. switch (m_object->m_type)
  3463. {
  3464. case value_t::object:
  3465. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  3466. case value_t::array:
  3467. return (m_it.array_iterator < other.m_it.array_iterator);
  3468. default:
  3469. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  3470. }
  3471. }
  3472. /*!
  3473. @brief comparison: less than or equal
  3474. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3475. */
  3476. bool operator<=(const iter_impl& other) const
  3477. {
  3478. return not other.operator < (*this);
  3479. }
  3480. /*!
  3481. @brief comparison: greater than
  3482. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3483. */
  3484. bool operator>(const iter_impl& other) const
  3485. {
  3486. return not operator<=(other);
  3487. }
  3488. /*!
  3489. @brief comparison: greater than or equal
  3490. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3491. */
  3492. bool operator>=(const iter_impl& other) const
  3493. {
  3494. return not operator<(other);
  3495. }
  3496. /*!
  3497. @brief add to iterator
  3498. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3499. */
  3500. iter_impl& operator+=(difference_type i)
  3501. {
  3502. assert(m_object != nullptr);
  3503. switch (m_object->m_type)
  3504. {
  3505. case value_t::object:
  3506. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3507. case value_t::array:
  3508. {
  3509. std::advance(m_it.array_iterator, i);
  3510. break;
  3511. }
  3512. default:
  3513. {
  3514. m_it.primitive_iterator += i;
  3515. break;
  3516. }
  3517. }
  3518. return *this;
  3519. }
  3520. /*!
  3521. @brief subtract from iterator
  3522. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3523. */
  3524. iter_impl& operator-=(difference_type i)
  3525. {
  3526. return operator+=(-i);
  3527. }
  3528. /*!
  3529. @brief add to iterator
  3530. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3531. */
  3532. iter_impl operator+(difference_type i) const
  3533. {
  3534. auto result = *this;
  3535. result += i;
  3536. return result;
  3537. }
  3538. /*!
  3539. @brief addition of distance and iterator
  3540. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3541. */
  3542. friend iter_impl operator+(difference_type i, const iter_impl& it)
  3543. {
  3544. auto result = it;
  3545. result += i;
  3546. return result;
  3547. }
  3548. /*!
  3549. @brief subtract from iterator
  3550. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3551. */
  3552. iter_impl operator-(difference_type i) const
  3553. {
  3554. auto result = *this;
  3555. result -= i;
  3556. return result;
  3557. }
  3558. /*!
  3559. @brief return difference
  3560. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3561. */
  3562. difference_type operator-(const iter_impl& other) const
  3563. {
  3564. assert(m_object != nullptr);
  3565. switch (m_object->m_type)
  3566. {
  3567. case value_t::object:
  3568. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3569. case value_t::array:
  3570. return m_it.array_iterator - other.m_it.array_iterator;
  3571. default:
  3572. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  3573. }
  3574. }
  3575. /*!
  3576. @brief access to successor
  3577. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3578. */
  3579. reference operator[](difference_type n) const
  3580. {
  3581. assert(m_object != nullptr);
  3582. switch (m_object->m_type)
  3583. {
  3584. case value_t::object:
  3585. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  3586. case value_t::array:
  3587. return *std::next(m_it.array_iterator, n);
  3588. case value_t::null:
  3589. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3590. default:
  3591. {
  3592. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  3593. {
  3594. return *m_object;
  3595. }
  3596. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3597. }
  3598. }
  3599. }
  3600. /*!
  3601. @brief return the key of an object iterator
  3602. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3603. */
  3604. typename object_t::key_type key() const
  3605. {
  3606. assert(m_object != nullptr);
  3607. if (JSON_LIKELY(m_object->is_object()))
  3608. {
  3609. return m_it.object_iterator->first;
  3610. }
  3611. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  3612. }
  3613. /*!
  3614. @brief return the value of an iterator
  3615. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3616. */
  3617. reference value() const
  3618. {
  3619. return operator*();
  3620. }
  3621. private:
  3622. /// associated JSON instance
  3623. pointer m_object = nullptr;
  3624. /// the actual iterator of the associated instance
  3625. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};
  3626. };
  3627. /// proxy class for the iterator_wrapper functions
  3628. template<typename IteratorType> class iteration_proxy
  3629. {
  3630. private:
  3631. /// helper class for iteration
  3632. class iteration_proxy_internal
  3633. {
  3634. private:
  3635. /// the iterator
  3636. IteratorType anchor;
  3637. /// an index for arrays (used to create key names)
  3638. std::size_t array_index = 0;
  3639. public:
  3640. explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
  3641. /// dereference operator (needed for range-based for)
  3642. iteration_proxy_internal& operator*()
  3643. {
  3644. return *this;
  3645. }
  3646. /// increment operator (needed for range-based for)
  3647. iteration_proxy_internal& operator++()
  3648. {
  3649. ++anchor;
  3650. ++array_index;
  3651. return *this;
  3652. }
  3653. /// inequality operator (needed for range-based for)
  3654. bool operator!=(const iteration_proxy_internal& o) const noexcept
  3655. {
  3656. return anchor != o.anchor;
  3657. }
  3658. /// return key of the iterator
  3659. std::string key() const
  3660. {
  3661. assert(anchor.m_object != nullptr);
  3662. switch (anchor.m_object->type())
  3663. {
  3664. // use integer array index as key
  3665. case value_t::array:
  3666. return std::to_string(array_index);
  3667. // use key from the object
  3668. case value_t::object:
  3669. return anchor.key();
  3670. // use an empty key for all primitive types
  3671. default:
  3672. return "";
  3673. }
  3674. }
  3675. /// return value of the iterator
  3676. typename IteratorType::reference value() const
  3677. {
  3678. return anchor.value();
  3679. }
  3680. };
  3681. /// the container to iterate
  3682. typename IteratorType::reference container;
  3683. public:
  3684. /// construct iteration proxy from a container
  3685. explicit iteration_proxy(typename IteratorType::reference cont)
  3686. : container(cont) {}
  3687. /// return iterator begin (needed for range-based for)
  3688. iteration_proxy_internal begin() noexcept
  3689. {
  3690. return iteration_proxy_internal(container.begin());
  3691. }
  3692. /// return iterator end (needed for range-based for)
  3693. iteration_proxy_internal end() noexcept
  3694. {
  3695. return iteration_proxy_internal(container.end());
  3696. }
  3697. };
  3698. /*!
  3699. @brief a template for a reverse iterator class
  3700. @tparam Base the base iterator type to reverse. Valid types are @ref
  3701. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  3702. create @ref const_reverse_iterator).
  3703. @requirement The class satisfies the following concept requirements:
  3704. -
  3705. [BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):
  3706. The iterator that can be moved can be moved in both directions (i.e.
  3707. incremented and decremented).
  3708. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  3709. It is possible to write to the pointed-to element (only if @a Base is
  3710. @ref iterator).
  3711. @since version 1.0.0
  3712. */
  3713. template<typename Base>
  3714. class json_reverse_iterator : public std::reverse_iterator<Base>
  3715. {
  3716. public:
  3717. using difference_type = std::ptrdiff_t;
  3718. /// shortcut to the reverse iterator adapter
  3719. using base_iterator = std::reverse_iterator<Base>;
  3720. /// the reference type for the pointed-to element
  3721. using reference = typename Base::reference;
  3722. /// create reverse iterator from iterator
  3723. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  3724. : base_iterator(it) {}
  3725. /// create reverse iterator from base class
  3726. json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  3727. /// post-increment (it++)
  3728. json_reverse_iterator const operator++(int)
  3729. {
  3730. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  3731. }
  3732. /// pre-increment (++it)
  3733. json_reverse_iterator& operator++()
  3734. {
  3735. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  3736. }
  3737. /// post-decrement (it--)
  3738. json_reverse_iterator const operator--(int)
  3739. {
  3740. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  3741. }
  3742. /// pre-decrement (--it)
  3743. json_reverse_iterator& operator--()
  3744. {
  3745. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  3746. }
  3747. /// add to iterator
  3748. json_reverse_iterator& operator+=(difference_type i)
  3749. {
  3750. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  3751. }
  3752. /// add to iterator
  3753. json_reverse_iterator operator+(difference_type i) const
  3754. {
  3755. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  3756. }
  3757. /// subtract from iterator
  3758. json_reverse_iterator operator-(difference_type i) const
  3759. {
  3760. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  3761. }
  3762. /// return difference
  3763. difference_type operator-(const json_reverse_iterator& other) const
  3764. {
  3765. return base_iterator(*this) - base_iterator(other);
  3766. }
  3767. /// access to successor
  3768. reference operator[](difference_type n) const
  3769. {
  3770. return *(this->operator+(n));
  3771. }
  3772. /// return the key of an object iterator
  3773. auto key() const -> decltype(std::declval<Base>().key())
  3774. {
  3775. auto it = --this->base();
  3776. return it.key();
  3777. }
  3778. /// return the value of an iterator
  3779. reference value() const
  3780. {
  3781. auto it = --this->base();
  3782. return it.operator * ();
  3783. }
  3784. };
  3785. /////////////////////
  3786. // output adapters //
  3787. /////////////////////
  3788. /// abstract output adapter interface
  3789. template<typename CharType> struct output_adapter_protocol
  3790. {
  3791. virtual void write_character(CharType c) = 0;
  3792. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  3793. virtual ~output_adapter_protocol() = default;
  3794. };
  3795. /// a type to simplify interfaces
  3796. template<typename CharType>
  3797. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  3798. /// output adapter for byte vectors
  3799. template<typename CharType>
  3800. class output_vector_adapter : public output_adapter_protocol<CharType>
  3801. {
  3802. public:
  3803. explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
  3804. void write_character(CharType c) override
  3805. {
  3806. v.push_back(c);
  3807. }
  3808. void write_characters(const CharType* s, std::size_t length) override
  3809. {
  3810. std::copy(s, s + length, std::back_inserter(v));
  3811. }
  3812. private:
  3813. std::vector<CharType>& v;
  3814. };
  3815. /// output adapter for output streams
  3816. template<typename CharType>
  3817. class output_stream_adapter : public output_adapter_protocol<CharType>
  3818. {
  3819. public:
  3820. explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
  3821. void write_character(CharType c) override
  3822. {
  3823. stream.put(c);
  3824. }
  3825. void write_characters(const CharType* s, std::size_t length) override
  3826. {
  3827. stream.write(s, static_cast<std::streamsize>(length));
  3828. }
  3829. private:
  3830. std::basic_ostream<CharType>& stream;
  3831. };
  3832. /// output adapter for basic_string
  3833. template<typename CharType>
  3834. class output_string_adapter : public output_adapter_protocol<CharType>
  3835. {
  3836. public:
  3837. explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
  3838. void write_character(CharType c) override
  3839. {
  3840. str.push_back(c);
  3841. }
  3842. void write_characters(const CharType* s, std::size_t length) override
  3843. {
  3844. str.append(s, length);
  3845. }
  3846. private:
  3847. std::basic_string<CharType>& str;
  3848. };
  3849. template<typename CharType>
  3850. class output_adapter
  3851. {
  3852. public:
  3853. output_adapter(std::vector<CharType>& vec)
  3854. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  3855. output_adapter(std::basic_ostream<CharType>& s)
  3856. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  3857. output_adapter(std::basic_string<CharType>& s)
  3858. : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
  3859. operator output_adapter_t<CharType>()
  3860. {
  3861. return oa;
  3862. }
  3863. private:
  3864. output_adapter_t<CharType> oa = nullptr;
  3865. };
  3866. //////////////////////////////
  3867. // binary reader and writer //
  3868. //////////////////////////////
  3869. /*!
  3870. @brief deserialization of CBOR and MessagePack values
  3871. */
  3872. template<typename BasicJsonType>
  3873. class binary_reader
  3874. {
  3875. using number_integer_t = typename BasicJsonType::number_integer_t;
  3876. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3877. public:
  3878. /*!
  3879. @brief create a binary reader
  3880. @param[in] adapter input adapter to read from
  3881. */
  3882. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  3883. {
  3884. assert(ia);
  3885. }
  3886. /*!
  3887. @brief create a JSON value from CBOR input
  3888. @param[in] strict whether to expect the input to be consumed completed
  3889. @return JSON value created from CBOR input
  3890. @throw parse_error.110 if input ended unexpectedly or the end of file was
  3891. not reached when @a strict was set to true
  3892. @throw parse_error.112 if unsupported byte was read
  3893. */
  3894. BasicJsonType parse_cbor(const bool strict)
  3895. {
  3896. const auto res = parse_cbor_internal();
  3897. if (strict)
  3898. {
  3899. get();
  3900. check_eof(true);
  3901. }
  3902. return res;
  3903. }
  3904. /*!
  3905. @brief create a JSON value from MessagePack input
  3906. @param[in] strict whether to expect the input to be consumed completed
  3907. @return JSON value created from MessagePack input
  3908. @throw parse_error.110 if input ended unexpectedly or the end of file was
  3909. not reached when @a strict was set to true
  3910. @throw parse_error.112 if unsupported byte was read
  3911. */
  3912. BasicJsonType parse_msgpack(const bool strict)
  3913. {
  3914. const auto res = parse_msgpack_internal();
  3915. if (strict)
  3916. {
  3917. get();
  3918. check_eof(true);
  3919. }
  3920. return res;
  3921. }
  3922. /*!
  3923. @brief determine system byte order
  3924. @return true if and only if system's byte order is little endian
  3925. @note from http://stackoverflow.com/a/1001328/266378
  3926. */
  3927. static constexpr bool little_endianess(int num = 1) noexcept
  3928. {
  3929. return (*reinterpret_cast<char*>(&num) == 1);
  3930. }
  3931. private:
  3932. /*!
  3933. @param[in] get_char whether a new character should be retrieved from the
  3934. input (true, default) or whether the last read
  3935. character should be considered instead
  3936. */
  3937. BasicJsonType parse_cbor_internal(const bool get_char = true)
  3938. {
  3939. switch (get_char ? get() : current)
  3940. {
  3941. // EOF
  3942. case std::char_traits<char>::eof():
  3943. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  3944. // Integer 0x00..0x17 (0..23)
  3945. case 0x00:
  3946. case 0x01:
  3947. case 0x02:
  3948. case 0x03:
  3949. case 0x04:
  3950. case 0x05:
  3951. case 0x06:
  3952. case 0x07:
  3953. case 0x08:
  3954. case 0x09:
  3955. case 0x0A:
  3956. case 0x0B:
  3957. case 0x0C:
  3958. case 0x0D:
  3959. case 0x0E:
  3960. case 0x0F:
  3961. case 0x10:
  3962. case 0x11:
  3963. case 0x12:
  3964. case 0x13:
  3965. case 0x14:
  3966. case 0x15:
  3967. case 0x16:
  3968. case 0x17:
  3969. return static_cast<number_unsigned_t>(current);
  3970. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  3971. return get_number<uint8_t>();
  3972. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  3973. return get_number<uint16_t>();
  3974. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  3975. return get_number<uint32_t>();
  3976. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  3977. return get_number<uint64_t>();
  3978. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  3979. case 0x20:
  3980. case 0x21:
  3981. case 0x22:
  3982. case 0x23:
  3983. case 0x24:
  3984. case 0x25:
  3985. case 0x26:
  3986. case 0x27:
  3987. case 0x28:
  3988. case 0x29:
  3989. case 0x2A:
  3990. case 0x2B:
  3991. case 0x2C:
  3992. case 0x2D:
  3993. case 0x2E:
  3994. case 0x2F:
  3995. case 0x30:
  3996. case 0x31:
  3997. case 0x32:
  3998. case 0x33:
  3999. case 0x34:
  4000. case 0x35:
  4001. case 0x36:
  4002. case 0x37:
  4003. return static_cast<int8_t>(0x20 - 1 - current);
  4004. case 0x38: // Negative integer (one-byte uint8_t follows)
  4005. {
  4006. // must be uint8_t !
  4007. return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
  4008. }
  4009. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4010. {
  4011. return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
  4012. }
  4013. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4014. {
  4015. return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
  4016. }
  4017. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4018. {
  4019. return static_cast<number_integer_t>(-1) -
  4020. static_cast<number_integer_t>(get_number<uint64_t>());
  4021. }
  4022. // UTF-8 string (0x00..0x17 bytes follow)
  4023. case 0x60:
  4024. case 0x61:
  4025. case 0x62:
  4026. case 0x63:
  4027. case 0x64:
  4028. case 0x65:
  4029. case 0x66:
  4030. case 0x67:
  4031. case 0x68:
  4032. case 0x69:
  4033. case 0x6A:
  4034. case 0x6B:
  4035. case 0x6C:
  4036. case 0x6D:
  4037. case 0x6E:
  4038. case 0x6F:
  4039. case 0x70:
  4040. case 0x71:
  4041. case 0x72:
  4042. case 0x73:
  4043. case 0x74:
  4044. case 0x75:
  4045. case 0x76:
  4046. case 0x77:
  4047. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4048. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4049. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4050. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4051. case 0x7F: // UTF-8 string (indefinite length)
  4052. {
  4053. return get_cbor_string();
  4054. }
  4055. // array (0x00..0x17 data items follow)
  4056. case 0x80:
  4057. case 0x81:
  4058. case 0x82:
  4059. case 0x83:
  4060. case 0x84:
  4061. case 0x85:
  4062. case 0x86:
  4063. case 0x87:
  4064. case 0x88:
  4065. case 0x89:
  4066. case 0x8A:
  4067. case 0x8B:
  4068. case 0x8C:
  4069. case 0x8D:
  4070. case 0x8E:
  4071. case 0x8F:
  4072. case 0x90:
  4073. case 0x91:
  4074. case 0x92:
  4075. case 0x93:
  4076. case 0x94:
  4077. case 0x95:
  4078. case 0x96:
  4079. case 0x97:
  4080. {
  4081. return get_cbor_array(current & 0x1F);
  4082. }
  4083. case 0x98: // array (one-byte uint8_t for n follows)
  4084. {
  4085. return get_cbor_array(get_number<uint8_t>());
  4086. }
  4087. case 0x99: // array (two-byte uint16_t for n follow)
  4088. {
  4089. return get_cbor_array(get_number<uint16_t>());
  4090. }
  4091. case 0x9A: // array (four-byte uint32_t for n follow)
  4092. {
  4093. return get_cbor_array(get_number<uint32_t>());
  4094. }
  4095. case 0x9B: // array (eight-byte uint64_t for n follow)
  4096. {
  4097. return get_cbor_array(get_number<uint64_t>());
  4098. }
  4099. case 0x9F: // array (indefinite length)
  4100. {
  4101. BasicJsonType result = value_t::array;
  4102. while (get() != 0xFF)
  4103. {
  4104. result.push_back(parse_cbor_internal(false));
  4105. }
  4106. return result;
  4107. }
  4108. // map (0x00..0x17 pairs of data items follow)
  4109. case 0xA0:
  4110. case 0xA1:
  4111. case 0xA2:
  4112. case 0xA3:
  4113. case 0xA4:
  4114. case 0xA5:
  4115. case 0xA6:
  4116. case 0xA7:
  4117. case 0xA8:
  4118. case 0xA9:
  4119. case 0xAA:
  4120. case 0xAB:
  4121. case 0xAC:
  4122. case 0xAD:
  4123. case 0xAE:
  4124. case 0xAF:
  4125. case 0xB0:
  4126. case 0xB1:
  4127. case 0xB2:
  4128. case 0xB3:
  4129. case 0xB4:
  4130. case 0xB5:
  4131. case 0xB6:
  4132. case 0xB7:
  4133. {
  4134. return get_cbor_object(current & 0x1F);
  4135. }
  4136. case 0xB8: // map (one-byte uint8_t for n follows)
  4137. {
  4138. return get_cbor_object(get_number<uint8_t>());
  4139. }
  4140. case 0xB9: // map (two-byte uint16_t for n follow)
  4141. {
  4142. return get_cbor_object(get_number<uint16_t>());
  4143. }
  4144. case 0xBA: // map (four-byte uint32_t for n follow)
  4145. {
  4146. return get_cbor_object(get_number<uint32_t>());
  4147. }
  4148. case 0xBB: // map (eight-byte uint64_t for n follow)
  4149. {
  4150. return get_cbor_object(get_number<uint64_t>());
  4151. }
  4152. case 0xBF: // map (indefinite length)
  4153. {
  4154. BasicJsonType result = value_t::object;
  4155. while (get() != 0xFF)
  4156. {
  4157. auto key = get_cbor_string();
  4158. result[key] = parse_cbor_internal();
  4159. }
  4160. return result;
  4161. }
  4162. case 0xF4: // false
  4163. {
  4164. return false;
  4165. }
  4166. case 0xF5: // true
  4167. {
  4168. return true;
  4169. }
  4170. case 0xF6: // null
  4171. {
  4172. return value_t::null;
  4173. }
  4174. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  4175. {
  4176. const int byte1 = get();
  4177. check_eof();
  4178. const int byte2 = get();
  4179. check_eof();
  4180. // code from RFC 7049, Appendix D, Figure 3:
  4181. // As half-precision floating-point numbers were only added
  4182. // to IEEE 754 in 2008, today's programming platforms often
  4183. // still only have limited support for them. It is very
  4184. // easy to include at least decoding support for them even
  4185. // without such support. An example of a small decoder for
  4186. // half-precision floating-point numbers in the C language
  4187. // is shown in Fig. 3.
  4188. const int half = (byte1 << 8) + byte2;
  4189. const int exp = (half >> 10) & 0x1F;
  4190. const int mant = half & 0x3FF;
  4191. double val;
  4192. if (exp == 0)
  4193. {
  4194. val = std::ldexp(mant, -24);
  4195. }
  4196. else if (exp != 31)
  4197. {
  4198. val = std::ldexp(mant + 1024, exp - 25);
  4199. }
  4200. else
  4201. {
  4202. val = (mant == 0) ? std::numeric_limits<double>::infinity()
  4203. : std::numeric_limits<double>::quiet_NaN();
  4204. }
  4205. return (half & 0x8000) != 0 ? -val : val;
  4206. }
  4207. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  4208. {
  4209. return get_number<float>();
  4210. }
  4211. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  4212. {
  4213. return get_number<double>();
  4214. }
  4215. default: // anything else (0xFF is handled inside the other types)
  4216. {
  4217. std::stringstream ss;
  4218. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4219. JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
  4220. }
  4221. }
  4222. }
  4223. BasicJsonType parse_msgpack_internal()
  4224. {
  4225. switch (get())
  4226. {
  4227. // EOF
  4228. case std::char_traits<char>::eof():
  4229. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4230. // positive fixint
  4231. case 0x00:
  4232. case 0x01:
  4233. case 0x02:
  4234. case 0x03:
  4235. case 0x04:
  4236. case 0x05:
  4237. case 0x06:
  4238. case 0x07:
  4239. case 0x08:
  4240. case 0x09:
  4241. case 0x0A:
  4242. case 0x0B:
  4243. case 0x0C:
  4244. case 0x0D:
  4245. case 0x0E:
  4246. case 0x0F:
  4247. case 0x10:
  4248. case 0x11:
  4249. case 0x12:
  4250. case 0x13:
  4251. case 0x14:
  4252. case 0x15:
  4253. case 0x16:
  4254. case 0x17:
  4255. case 0x18:
  4256. case 0x19:
  4257. case 0x1A:
  4258. case 0x1B:
  4259. case 0x1C:
  4260. case 0x1D:
  4261. case 0x1E:
  4262. case 0x1F:
  4263. case 0x20:
  4264. case 0x21:
  4265. case 0x22:
  4266. case 0x23:
  4267. case 0x24:
  4268. case 0x25:
  4269. case 0x26:
  4270. case 0x27:
  4271. case 0x28:
  4272. case 0x29:
  4273. case 0x2A:
  4274. case 0x2B:
  4275. case 0x2C:
  4276. case 0x2D:
  4277. case 0x2E:
  4278. case 0x2F:
  4279. case 0x30:
  4280. case 0x31:
  4281. case 0x32:
  4282. case 0x33:
  4283. case 0x34:
  4284. case 0x35:
  4285. case 0x36:
  4286. case 0x37:
  4287. case 0x38:
  4288. case 0x39:
  4289. case 0x3A:
  4290. case 0x3B:
  4291. case 0x3C:
  4292. case 0x3D:
  4293. case 0x3E:
  4294. case 0x3F:
  4295. case 0x40:
  4296. case 0x41:
  4297. case 0x42:
  4298. case 0x43:
  4299. case 0x44:
  4300. case 0x45:
  4301. case 0x46:
  4302. case 0x47:
  4303. case 0x48:
  4304. case 0x49:
  4305. case 0x4A:
  4306. case 0x4B:
  4307. case 0x4C:
  4308. case 0x4D:
  4309. case 0x4E:
  4310. case 0x4F:
  4311. case 0x50:
  4312. case 0x51:
  4313. case 0x52:
  4314. case 0x53:
  4315. case 0x54:
  4316. case 0x55:
  4317. case 0x56:
  4318. case 0x57:
  4319. case 0x58:
  4320. case 0x59:
  4321. case 0x5A:
  4322. case 0x5B:
  4323. case 0x5C:
  4324. case 0x5D:
  4325. case 0x5E:
  4326. case 0x5F:
  4327. case 0x60:
  4328. case 0x61:
  4329. case 0x62:
  4330. case 0x63:
  4331. case 0x64:
  4332. case 0x65:
  4333. case 0x66:
  4334. case 0x67:
  4335. case 0x68:
  4336. case 0x69:
  4337. case 0x6A:
  4338. case 0x6B:
  4339. case 0x6C:
  4340. case 0x6D:
  4341. case 0x6E:
  4342. case 0x6F:
  4343. case 0x70:
  4344. case 0x71:
  4345. case 0x72:
  4346. case 0x73:
  4347. case 0x74:
  4348. case 0x75:
  4349. case 0x76:
  4350. case 0x77:
  4351. case 0x78:
  4352. case 0x79:
  4353. case 0x7A:
  4354. case 0x7B:
  4355. case 0x7C:
  4356. case 0x7D:
  4357. case 0x7E:
  4358. case 0x7F:
  4359. return static_cast<number_unsigned_t>(current);
  4360. // fixmap
  4361. case 0x80:
  4362. case 0x81:
  4363. case 0x82:
  4364. case 0x83:
  4365. case 0x84:
  4366. case 0x85:
  4367. case 0x86:
  4368. case 0x87:
  4369. case 0x88:
  4370. case 0x89:
  4371. case 0x8A:
  4372. case 0x8B:
  4373. case 0x8C:
  4374. case 0x8D:
  4375. case 0x8E:
  4376. case 0x8F:
  4377. {
  4378. return get_msgpack_object(current & 0x0F);
  4379. }
  4380. // fixarray
  4381. case 0x90:
  4382. case 0x91:
  4383. case 0x92:
  4384. case 0x93:
  4385. case 0x94:
  4386. case 0x95:
  4387. case 0x96:
  4388. case 0x97:
  4389. case 0x98:
  4390. case 0x99:
  4391. case 0x9A:
  4392. case 0x9B:
  4393. case 0x9C:
  4394. case 0x9D:
  4395. case 0x9E:
  4396. case 0x9F:
  4397. {
  4398. return get_msgpack_array(current & 0x0F);
  4399. }
  4400. // fixstr
  4401. case 0xA0:
  4402. case 0xA1:
  4403. case 0xA2:
  4404. case 0xA3:
  4405. case 0xA4:
  4406. case 0xA5:
  4407. case 0xA6:
  4408. case 0xA7:
  4409. case 0xA8:
  4410. case 0xA9:
  4411. case 0xAA:
  4412. case 0xAB:
  4413. case 0xAC:
  4414. case 0xAD:
  4415. case 0xAE:
  4416. case 0xAF:
  4417. case 0xB0:
  4418. case 0xB1:
  4419. case 0xB2:
  4420. case 0xB3:
  4421. case 0xB4:
  4422. case 0xB5:
  4423. case 0xB6:
  4424. case 0xB7:
  4425. case 0xB8:
  4426. case 0xB9:
  4427. case 0xBA:
  4428. case 0xBB:
  4429. case 0xBC:
  4430. case 0xBD:
  4431. case 0xBE:
  4432. case 0xBF:
  4433. return get_msgpack_string();
  4434. case 0xC0: // nil
  4435. return value_t::null;
  4436. case 0xC2: // false
  4437. return false;
  4438. case 0xC3: // true
  4439. return true;
  4440. case 0xCA: // float 32
  4441. return get_number<float>();
  4442. case 0xCB: // float 64
  4443. return get_number<double>();
  4444. case 0xCC: // uint 8
  4445. return get_number<uint8_t>();
  4446. case 0xCD: // uint 16
  4447. return get_number<uint16_t>();
  4448. case 0xCE: // uint 32
  4449. return get_number<uint32_t>();
  4450. case 0xCF: // uint 64
  4451. return get_number<uint64_t>();
  4452. case 0xD0: // int 8
  4453. return get_number<int8_t>();
  4454. case 0xD1: // int 16
  4455. return get_number<int16_t>();
  4456. case 0xD2: // int 32
  4457. return get_number<int32_t>();
  4458. case 0xD3: // int 64
  4459. return get_number<int64_t>();
  4460. case 0xD9: // str 8
  4461. case 0xDA: // str 16
  4462. case 0xDB: // str 32
  4463. return get_msgpack_string();
  4464. case 0xDC: // array 16
  4465. {
  4466. return get_msgpack_array(get_number<uint16_t>());
  4467. }
  4468. case 0xDD: // array 32
  4469. {
  4470. return get_msgpack_array(get_number<uint32_t>());
  4471. }
  4472. case 0xDE: // map 16
  4473. {
  4474. return get_msgpack_object(get_number<uint16_t>());
  4475. }
  4476. case 0xDF: // map 32
  4477. {
  4478. return get_msgpack_object(get_number<uint32_t>());
  4479. }
  4480. // positive fixint
  4481. case 0xE0:
  4482. case 0xE1:
  4483. case 0xE2:
  4484. case 0xE3:
  4485. case 0xE4:
  4486. case 0xE5:
  4487. case 0xE6:
  4488. case 0xE7:
  4489. case 0xE8:
  4490. case 0xE9:
  4491. case 0xEA:
  4492. case 0xEB:
  4493. case 0xEC:
  4494. case 0xED:
  4495. case 0xEE:
  4496. case 0xEF:
  4497. case 0xF0:
  4498. case 0xF1:
  4499. case 0xF2:
  4500. case 0xF3:
  4501. case 0xF4:
  4502. case 0xF5:
  4503. case 0xF6:
  4504. case 0xF7:
  4505. case 0xF8:
  4506. case 0xF9:
  4507. case 0xFA:
  4508. case 0xFB:
  4509. case 0xFC:
  4510. case 0xFD:
  4511. case 0xFE:
  4512. case 0xFF:
  4513. return static_cast<int8_t>(current);
  4514. default: // anything else
  4515. {
  4516. std::stringstream ss;
  4517. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4518. JSON_THROW(parse_error::create(112, chars_read,
  4519. "error reading MessagePack; last byte: 0x" + ss.str()));
  4520. }
  4521. }
  4522. }
  4523. /*!
  4524. @brief get next character from the input
  4525. This function provides the interface to the used input adapter. It does
  4526. not throw in case the input reached EOF, but returns a -'ve valued
  4527. `std::char_traits<char>::eof()` in that case.
  4528. @return character read from the input
  4529. */
  4530. int get()
  4531. {
  4532. ++chars_read;
  4533. return (current = ia->get_character());
  4534. }
  4535. /*
  4536. @brief read a number from the input
  4537. @tparam NumberType the type of the number
  4538. @return number of type @a NumberType
  4539. @note This function needs to respect the system's endianess, because
  4540. bytes in CBOR and MessagePack are stored in network order (big
  4541. endian) and therefore need reordering on little endian systems.
  4542. @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
  4543. */
  4544. template<typename NumberType> NumberType get_number()
  4545. {
  4546. // step 1: read input into array with system's byte order
  4547. std::array<uint8_t, sizeof(NumberType)> vec;
  4548. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  4549. {
  4550. get();
  4551. check_eof();
  4552. // reverse byte order prior to conversion if necessary
  4553. if (is_little_endian)
  4554. {
  4555. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  4556. }
  4557. else
  4558. {
  4559. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  4560. }
  4561. }
  4562. // step 2: convert array into number of type T and return
  4563. NumberType result;
  4564. std::memcpy(&result, vec.data(), sizeof(NumberType));
  4565. return result;
  4566. }
  4567. /*!
  4568. @brief create a string by reading characters from the input
  4569. @param[in] len number of bytes to read
  4570. @note We can not reserve @a len bytes for the result, because @a len
  4571. may be too large. Usually, @ref check_eof() detects the end of
  4572. the input before we run out of string memory.
  4573. @return string created by reading @a len bytes
  4574. @throw parse_error.110 if input has less than @a len bytes
  4575. */
  4576. template<typename NumberType>
  4577. std::string get_string(const NumberType len)
  4578. {
  4579. std::string result;
  4580. std::generate_n(std::back_inserter(result), len, [this]()
  4581. {
  4582. get();
  4583. check_eof();
  4584. return static_cast<char>(current);
  4585. });
  4586. return result;
  4587. }
  4588. /*!
  4589. @brief reads a CBOR string
  4590. This function first reads starting bytes to determine the expected
  4591. string length and then copies this number of bytes into a string.
  4592. Additionally, CBOR's strings with indefinite lengths are supported.
  4593. @return string
  4594. @throw parse_error.110 if input ended
  4595. @throw parse_error.113 if an unexpected byte is read
  4596. */
  4597. std::string get_cbor_string()
  4598. {
  4599. check_eof();
  4600. switch (current)
  4601. {
  4602. // UTF-8 string (0x00..0x17 bytes follow)
  4603. case 0x60:
  4604. case 0x61:
  4605. case 0x62:
  4606. case 0x63:
  4607. case 0x64:
  4608. case 0x65:
  4609. case 0x66:
  4610. case 0x67:
  4611. case 0x68:
  4612. case 0x69:
  4613. case 0x6A:
  4614. case 0x6B:
  4615. case 0x6C:
  4616. case 0x6D:
  4617. case 0x6E:
  4618. case 0x6F:
  4619. case 0x70:
  4620. case 0x71:
  4621. case 0x72:
  4622. case 0x73:
  4623. case 0x74:
  4624. case 0x75:
  4625. case 0x76:
  4626. case 0x77:
  4627. {
  4628. return get_string(current & 0x1F);
  4629. }
  4630. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4631. {
  4632. return get_string(get_number<uint8_t>());
  4633. }
  4634. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4635. {
  4636. return get_string(get_number<uint16_t>());
  4637. }
  4638. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4639. {
  4640. return get_string(get_number<uint32_t>());
  4641. }
  4642. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4643. {
  4644. return get_string(get_number<uint64_t>());
  4645. }
  4646. case 0x7F: // UTF-8 string (indefinite length)
  4647. {
  4648. std::string result;
  4649. while (get() != 0xFF)
  4650. {
  4651. check_eof();
  4652. result.push_back(static_cast<char>(current));
  4653. }
  4654. return result;
  4655. }
  4656. default:
  4657. {
  4658. std::stringstream ss;
  4659. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4660. JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
  4661. }
  4662. }
  4663. }
  4664. template<typename NumberType>
  4665. BasicJsonType get_cbor_array(const NumberType len)
  4666. {
  4667. BasicJsonType result = value_t::array;
  4668. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  4669. {
  4670. return parse_cbor_internal();
  4671. });
  4672. return result;
  4673. }
  4674. template<typename NumberType>
  4675. BasicJsonType get_cbor_object(const NumberType len)
  4676. {
  4677. BasicJsonType result = value_t::object;
  4678. std::generate_n(std::inserter(*result.m_value.object,
  4679. result.m_value.object->end()),
  4680. len, [this]()
  4681. {
  4682. get();
  4683. auto key = get_cbor_string();
  4684. auto val = parse_cbor_internal();
  4685. return std::make_pair(std::move(key), std::move(val));
  4686. });
  4687. return result;
  4688. }
  4689. /*!
  4690. @brief reads a MessagePack string
  4691. This function first reads starting bytes to determine the expected
  4692. string length and then copies this number of bytes into a string.
  4693. @return string
  4694. @throw parse_error.110 if input ended
  4695. @throw parse_error.113 if an unexpected byte is read
  4696. */
  4697. std::string get_msgpack_string()
  4698. {
  4699. check_eof();
  4700. switch (current)
  4701. {
  4702. // fixstr
  4703. case 0xA0:
  4704. case 0xA1:
  4705. case 0xA2:
  4706. case 0xA3:
  4707. case 0xA4:
  4708. case 0xA5:
  4709. case 0xA6:
  4710. case 0xA7:
  4711. case 0xA8:
  4712. case 0xA9:
  4713. case 0xAA:
  4714. case 0xAB:
  4715. case 0xAC:
  4716. case 0xAD:
  4717. case 0xAE:
  4718. case 0xAF:
  4719. case 0xB0:
  4720. case 0xB1:
  4721. case 0xB2:
  4722. case 0xB3:
  4723. case 0xB4:
  4724. case 0xB5:
  4725. case 0xB6:
  4726. case 0xB7:
  4727. case 0xB8:
  4728. case 0xB9:
  4729. case 0xBA:
  4730. case 0xBB:
  4731. case 0xBC:
  4732. case 0xBD:
  4733. case 0xBE:
  4734. case 0xBF:
  4735. {
  4736. return get_string(current & 0x1F);
  4737. }
  4738. case 0xD9: // str 8
  4739. {
  4740. return get_string(get_number<uint8_t>());
  4741. }
  4742. case 0xDA: // str 16
  4743. {
  4744. return get_string(get_number<uint16_t>());
  4745. }
  4746. case 0xDB: // str 32
  4747. {
  4748. return get_string(get_number<uint32_t>());
  4749. }
  4750. default:
  4751. {
  4752. std::stringstream ss;
  4753. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;
  4754. JSON_THROW(parse_error::create(113, chars_read,
  4755. "expected a MessagePack string; last byte: 0x" + ss.str()));
  4756. }
  4757. }
  4758. }
  4759. template<typename NumberType>
  4760. BasicJsonType get_msgpack_array(const NumberType len)
  4761. {
  4762. BasicJsonType result = value_t::array;
  4763. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  4764. {
  4765. return parse_msgpack_internal();
  4766. });
  4767. return result;
  4768. }
  4769. template<typename NumberType>
  4770. BasicJsonType get_msgpack_object(const NumberType len)
  4771. {
  4772. BasicJsonType result = value_t::object;
  4773. std::generate_n(std::inserter(*result.m_value.object,
  4774. result.m_value.object->end()),
  4775. len, [this]()
  4776. {
  4777. get();
  4778. auto key = get_msgpack_string();
  4779. auto val = parse_msgpack_internal();
  4780. return std::make_pair(std::move(key), std::move(val));
  4781. });
  4782. return result;
  4783. }
  4784. /*!
  4785. @brief check if input ended
  4786. @throw parse_error.110 if input ended
  4787. */
  4788. void check_eof(const bool expect_eof = false) const
  4789. {
  4790. if (expect_eof)
  4791. {
  4792. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  4793. {
  4794. JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
  4795. }
  4796. }
  4797. else
  4798. {
  4799. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  4800. {
  4801. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4802. }
  4803. }
  4804. }
  4805. private:
  4806. /// input adapter
  4807. input_adapter_t ia = nullptr;
  4808. /// the current character
  4809. int current = std::char_traits<char>::eof();
  4810. /// the number of characters read
  4811. std::size_t chars_read = 0;
  4812. /// whether we can assume little endianess
  4813. const bool is_little_endian = little_endianess();
  4814. };
  4815. /*!
  4816. @brief serialization to CBOR and MessagePack values
  4817. */
  4818. template<typename BasicJsonType, typename CharType>
  4819. class binary_writer
  4820. {
  4821. public:
  4822. /*!
  4823. @brief create a binary writer
  4824. @param[in] adapter output adapter to write to
  4825. */
  4826. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  4827. {
  4828. assert(oa);
  4829. }
  4830. /*!
  4831. @brief[in] j JSON value to serialize
  4832. */
  4833. void write_cbor(const BasicJsonType& j)
  4834. {
  4835. switch (j.type())
  4836. {
  4837. case value_t::null:
  4838. {
  4839. oa->write_character(static_cast<CharType>(0xF6));
  4840. break;
  4841. }
  4842. case value_t::boolean:
  4843. {
  4844. oa->write_character(j.m_value.boolean
  4845. ? static_cast<CharType>(0xF5)
  4846. : static_cast<CharType>(0xF4));
  4847. break;
  4848. }
  4849. case value_t::number_integer:
  4850. {
  4851. if (j.m_value.number_integer >= 0)
  4852. {
  4853. // CBOR does not differentiate between positive signed
  4854. // integers and unsigned integers. Therefore, we used the
  4855. // code from the value_t::number_unsigned case here.
  4856. if (j.m_value.number_integer <= 0x17)
  4857. {
  4858. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  4859. }
  4860. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  4861. {
  4862. oa->write_character(static_cast<CharType>(0x18));
  4863. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  4864. }
  4865. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  4866. {
  4867. oa->write_character(static_cast<CharType>(0x19));
  4868. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  4869. }
  4870. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  4871. {
  4872. oa->write_character(static_cast<CharType>(0x1A));
  4873. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  4874. }
  4875. else
  4876. {
  4877. oa->write_character(static_cast<CharType>(0x1B));
  4878. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  4879. }
  4880. }
  4881. else
  4882. {
  4883. // The conversions below encode the sign in the first
  4884. // byte, and the value is converted to a positive number.
  4885. const auto positive_number = -1 - j.m_value.number_integer;
  4886. if (j.m_value.number_integer >= -24)
  4887. {
  4888. write_number(static_cast<uint8_t>(0x20 + positive_number));
  4889. }
  4890. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  4891. {
  4892. oa->write_character(static_cast<CharType>(0x38));
  4893. write_number(static_cast<uint8_t>(positive_number));
  4894. }
  4895. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  4896. {
  4897. oa->write_character(static_cast<CharType>(0x39));
  4898. write_number(static_cast<uint16_t>(positive_number));
  4899. }
  4900. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  4901. {
  4902. oa->write_character(static_cast<CharType>(0x3A));
  4903. write_number(static_cast<uint32_t>(positive_number));
  4904. }
  4905. else
  4906. {
  4907. oa->write_character(static_cast<CharType>(0x3B));
  4908. write_number(static_cast<uint64_t>(positive_number));
  4909. }
  4910. }
  4911. break;
  4912. }
  4913. case value_t::number_unsigned:
  4914. {
  4915. if (j.m_value.number_unsigned <= 0x17)
  4916. {
  4917. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  4918. }
  4919. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  4920. {
  4921. oa->write_character(static_cast<CharType>(0x18));
  4922. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  4923. }
  4924. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  4925. {
  4926. oa->write_character(static_cast<CharType>(0x19));
  4927. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  4928. }
  4929. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  4930. {
  4931. oa->write_character(static_cast<CharType>(0x1A));
  4932. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  4933. }
  4934. else
  4935. {
  4936. oa->write_character(static_cast<CharType>(0x1B));
  4937. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  4938. }
  4939. break;
  4940. }
  4941. case value_t::number_float: // Double-Precision Float
  4942. {
  4943. oa->write_character(static_cast<CharType>(0xFB));
  4944. write_number(j.m_value.number_float);
  4945. break;
  4946. }
  4947. case value_t::string:
  4948. {
  4949. // step 1: write control byte and the string length
  4950. const auto N = j.m_value.string->size();
  4951. if (N <= 0x17)
  4952. {
  4953. write_number(static_cast<uint8_t>(0x60 + N));
  4954. }
  4955. else if (N <= 0xFF)
  4956. {
  4957. oa->write_character(static_cast<CharType>(0x78));
  4958. write_number(static_cast<uint8_t>(N));
  4959. }
  4960. else if (N <= 0xFFFF)
  4961. {
  4962. oa->write_character(static_cast<CharType>(0x79));
  4963. write_number(static_cast<uint16_t>(N));
  4964. }
  4965. else if (N <= 0xFFFFFFFF)
  4966. {
  4967. oa->write_character(static_cast<CharType>(0x7A));
  4968. write_number(static_cast<uint32_t>(N));
  4969. }
  4970. // LCOV_EXCL_START
  4971. else if (N <= 0xFFFFFFFFFFFFFFFF)
  4972. {
  4973. oa->write_character(static_cast<CharType>(0x7B));
  4974. write_number(static_cast<uint64_t>(N));
  4975. }
  4976. // LCOV_EXCL_STOP
  4977. // step 2: write the string
  4978. oa->write_characters(
  4979. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  4980. j.m_value.string->size());
  4981. break;
  4982. }
  4983. case value_t::array:
  4984. {
  4985. // step 1: write control byte and the array size
  4986. const auto N = j.m_value.array->size();
  4987. if (N <= 0x17)
  4988. {
  4989. write_number(static_cast<uint8_t>(0x80 + N));
  4990. }
  4991. else if (N <= 0xFF)
  4992. {
  4993. oa->write_character(static_cast<CharType>(0x98));
  4994. write_number(static_cast<uint8_t>(N));
  4995. }
  4996. else if (N <= 0xFFFF)
  4997. {
  4998. oa->write_character(static_cast<CharType>(0x99));
  4999. write_number(static_cast<uint16_t>(N));
  5000. }
  5001. else if (N <= 0xFFFFFFFF)
  5002. {
  5003. oa->write_character(static_cast<CharType>(0x9A));
  5004. write_number(static_cast<uint32_t>(N));
  5005. }
  5006. // LCOV_EXCL_START
  5007. else if (N <= 0xFFFFFFFFFFFFFFFF)
  5008. {
  5009. oa->write_character(static_cast<CharType>(0x9B));
  5010. write_number(static_cast<uint64_t>(N));
  5011. }
  5012. // LCOV_EXCL_STOP
  5013. // step 2: write each element
  5014. for (const auto& el : *j.m_value.array)
  5015. {
  5016. write_cbor(el);
  5017. }
  5018. break;
  5019. }
  5020. case value_t::object:
  5021. {
  5022. // step 1: write control byte and the object size
  5023. const auto N = j.m_value.object->size();
  5024. if (N <= 0x17)
  5025. {
  5026. write_number(static_cast<uint8_t>(0xA0 + N));
  5027. }
  5028. else if (N <= 0xFF)
  5029. {
  5030. oa->write_character(static_cast<CharType>(0xB8));
  5031. write_number(static_cast<uint8_t>(N));
  5032. }
  5033. else if (N <= 0xFFFF)
  5034. {
  5035. oa->write_character(static_cast<CharType>(0xB9));
  5036. write_number(static_cast<uint16_t>(N));
  5037. }
  5038. else if (N <= 0xFFFFFFFF)
  5039. {
  5040. oa->write_character(static_cast<CharType>(0xBA));
  5041. write_number(static_cast<uint32_t>(N));
  5042. }
  5043. // LCOV_EXCL_START
  5044. else if (N <= 0xFFFFFFFFFFFFFFFF)
  5045. {
  5046. oa->write_character(static_cast<CharType>(0xBB));
  5047. write_number(static_cast<uint64_t>(N));
  5048. }
  5049. // LCOV_EXCL_STOP
  5050. // step 2: write each element
  5051. for (const auto& el : *j.m_value.object)
  5052. {
  5053. write_cbor(el.first);
  5054. write_cbor(el.second);
  5055. }
  5056. break;
  5057. }
  5058. default:
  5059. break;
  5060. }
  5061. }
  5062. /*!
  5063. @brief[in] j JSON value to serialize
  5064. */
  5065. void write_msgpack(const BasicJsonType& j)
  5066. {
  5067. switch (j.type())
  5068. {
  5069. case value_t::null: // nil
  5070. {
  5071. oa->write_character(static_cast<CharType>(0xC0));
  5072. break;
  5073. }
  5074. case value_t::boolean: // true and false
  5075. {
  5076. oa->write_character(j.m_value.boolean
  5077. ? static_cast<CharType>(0xC3)
  5078. : static_cast<CharType>(0xC2));
  5079. break;
  5080. }
  5081. case value_t::number_integer:
  5082. {
  5083. if (j.m_value.number_integer >= 0)
  5084. {
  5085. // MessagePack does not differentiate between positive
  5086. // signed integers and unsigned integers. Therefore, we used
  5087. // the code from the value_t::number_unsigned case here.
  5088. if (j.m_value.number_unsigned < 128)
  5089. {
  5090. // positive fixnum
  5091. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5092. }
  5093. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5094. {
  5095. // uint 8
  5096. oa->write_character(static_cast<CharType>(0xCC));
  5097. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5098. }
  5099. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5100. {
  5101. // uint 16
  5102. oa->write_character(static_cast<CharType>(0xCD));
  5103. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5104. }
  5105. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5106. {
  5107. // uint 32
  5108. oa->write_character(static_cast<CharType>(0xCE));
  5109. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5110. }
  5111. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5112. {
  5113. // uint 64
  5114. oa->write_character(static_cast<CharType>(0xCF));
  5115. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5116. }
  5117. }
  5118. else
  5119. {
  5120. if (j.m_value.number_integer >= -32)
  5121. {
  5122. // negative fixnum
  5123. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5124. }
  5125. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
  5126. j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  5127. {
  5128. // int 8
  5129. oa->write_character(static_cast<CharType>(0xD0));
  5130. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5131. }
  5132. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
  5133. j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  5134. {
  5135. // int 16
  5136. oa->write_character(static_cast<CharType>(0xD1));
  5137. write_number(static_cast<int16_t>(j.m_value.number_integer));
  5138. }
  5139. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
  5140. j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  5141. {
  5142. // int 32
  5143. oa->write_character(static_cast<CharType>(0xD2));
  5144. write_number(static_cast<int32_t>(j.m_value.number_integer));
  5145. }
  5146. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
  5147. j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  5148. {
  5149. // int 64
  5150. oa->write_character(static_cast<CharType>(0xD3));
  5151. write_number(static_cast<int64_t>(j.m_value.number_integer));
  5152. }
  5153. }
  5154. break;
  5155. }
  5156. case value_t::number_unsigned:
  5157. {
  5158. if (j.m_value.number_unsigned < 128)
  5159. {
  5160. // positive fixnum
  5161. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5162. }
  5163. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5164. {
  5165. // uint 8
  5166. oa->write_character(static_cast<CharType>(0xCC));
  5167. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5168. }
  5169. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5170. {
  5171. // uint 16
  5172. oa->write_character(static_cast<CharType>(0xCD));
  5173. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5174. }
  5175. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5176. {
  5177. // uint 32
  5178. oa->write_character(static_cast<CharType>(0xCE));
  5179. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5180. }
  5181. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5182. {
  5183. // uint 64
  5184. oa->write_character(static_cast<CharType>(0xCF));
  5185. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5186. }
  5187. break;
  5188. }
  5189. case value_t::number_float: // float 64
  5190. {
  5191. oa->write_character(static_cast<CharType>(0xCB));
  5192. write_number(j.m_value.number_float);
  5193. break;
  5194. }
  5195. case value_t::string:
  5196. {
  5197. // step 1: write control byte and the string length
  5198. const auto N = j.m_value.string->size();
  5199. if (N <= 31)
  5200. {
  5201. // fixstr
  5202. write_number(static_cast<uint8_t>(0xA0 | N));
  5203. }
  5204. else if (N <= 255)
  5205. {
  5206. // str 8
  5207. oa->write_character(static_cast<CharType>(0xD9));
  5208. write_number(static_cast<uint8_t>(N));
  5209. }
  5210. else if (N <= 65535)
  5211. {
  5212. // str 16
  5213. oa->write_character(static_cast<CharType>(0xDA));
  5214. write_number(static_cast<uint16_t>(N));
  5215. }
  5216. else if (N <= 4294967295)
  5217. {
  5218. // str 32
  5219. oa->write_character(static_cast<CharType>(0xDB));
  5220. write_number(static_cast<uint32_t>(N));
  5221. }
  5222. // step 2: write the string
  5223. oa->write_characters(
  5224. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  5225. j.m_value.string->size());
  5226. break;
  5227. }
  5228. case value_t::array:
  5229. {
  5230. // step 1: write control byte and the array size
  5231. const auto N = j.m_value.array->size();
  5232. if (N <= 15)
  5233. {
  5234. // fixarray
  5235. write_number(static_cast<uint8_t>(0x90 | N));
  5236. }
  5237. else if (N <= 0xFFFF)
  5238. {
  5239. // array 16
  5240. oa->write_character(static_cast<CharType>(0xDC));
  5241. write_number(static_cast<uint16_t>(N));
  5242. }
  5243. else if (N <= 0xFFFFFFFF)
  5244. {
  5245. // array 32
  5246. oa->write_character(static_cast<CharType>(0xDD));
  5247. write_number(static_cast<uint32_t>(N));
  5248. }
  5249. // step 2: write each element
  5250. for (const auto& el : *j.m_value.array)
  5251. {
  5252. write_msgpack(el);
  5253. }
  5254. break;
  5255. }
  5256. case value_t::object:
  5257. {
  5258. // step 1: write control byte and the object size
  5259. const auto N = j.m_value.object->size();
  5260. if (N <= 15)
  5261. {
  5262. // fixmap
  5263. write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
  5264. }
  5265. else if (N <= 65535)
  5266. {
  5267. // map 16
  5268. oa->write_character(static_cast<CharType>(0xDE));
  5269. write_number(static_cast<uint16_t>(N));
  5270. }
  5271. else if (N <= 4294967295)
  5272. {
  5273. // map 32
  5274. oa->write_character(static_cast<CharType>(0xDF));
  5275. write_number(static_cast<uint32_t>(N));
  5276. }
  5277. // step 2: write each element
  5278. for (const auto& el : *j.m_value.object)
  5279. {
  5280. write_msgpack(el.first);
  5281. write_msgpack(el.second);
  5282. }
  5283. break;
  5284. }
  5285. default:
  5286. break;
  5287. }
  5288. }
  5289. private:
  5290. /*
  5291. @brief write a number to output input
  5292. @param[in] n number of type @a NumberType
  5293. @tparam NumberType the type of the number
  5294. @note This function needs to respect the system's endianess, because bytes
  5295. in CBOR and MessagePack are stored in network order (big endian) and
  5296. therefore need reordering on little endian systems.
  5297. */
  5298. template<typename NumberType> void write_number(NumberType n)
  5299. {
  5300. // step 1: write number to array of length NumberType
  5301. std::array<CharType, sizeof(NumberType)> vec;
  5302. std::memcpy(vec.data(), &n, sizeof(NumberType));
  5303. // step 2: write array to output (with possible reordering)
  5304. if (is_little_endian)
  5305. {
  5306. // reverse byte order prior to conversion if necessary
  5307. std::reverse(vec.begin(), vec.end());
  5308. }
  5309. oa->write_characters(vec.data(), sizeof(NumberType));
  5310. }
  5311. private:
  5312. /// whether we can assume little endianess
  5313. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  5314. /// the output
  5315. output_adapter_t<CharType> oa = nullptr;
  5316. };
  5317. ///////////////////
  5318. // serialization //
  5319. ///////////////////
  5320. template<typename BasicJsonType>
  5321. class serializer
  5322. {
  5323. using string_t = typename BasicJsonType::string_t;
  5324. using number_float_t = typename BasicJsonType::number_float_t;
  5325. using number_integer_t = typename BasicJsonType::number_integer_t;
  5326. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5327. public:
  5328. /*!
  5329. @param[in] s output stream to serialize to
  5330. @param[in] ichar indentation character to use
  5331. */
  5332. serializer(output_adapter_t<char> s, const char ichar)
  5333. : o(std::move(s)), loc(std::localeconv()),
  5334. thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
  5335. decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
  5336. indent_char(ichar), indent_string(512, indent_char) {}
  5337. // delete because of pointer members
  5338. serializer(const serializer&) = delete;
  5339. serializer& operator=(const serializer&) = delete;
  5340. /*!
  5341. @brief internal implementation of the serialization function
  5342. This function is called by the public member function dump and organizes
  5343. the serialization internally. The indentation level is propagated as
  5344. additional parameter. In case of arrays and objects, the function is
  5345. called recursively.
  5346. - strings and object keys are escaped using `escape_string()`
  5347. - integer numbers are converted implicitly via `operator<<`
  5348. - floating-point numbers are converted to a string using `"%g"` format
  5349. @param[in] val value to serialize
  5350. @param[in] pretty_print whether the output shall be pretty-printed
  5351. @param[in] indent_step the indent level
  5352. @param[in] current_indent the current indent level (only used internally)
  5353. */
  5354. void dump(const BasicJsonType& val, const bool pretty_print,
  5355. const bool ensure_ascii,
  5356. const unsigned int indent_step,
  5357. const unsigned int current_indent = 0)
  5358. {
  5359. switch (val.m_type)
  5360. {
  5361. case value_t::object:
  5362. {
  5363. if (val.m_value.object->empty())
  5364. {
  5365. o->write_characters("{}", 2);
  5366. return;
  5367. }
  5368. if (pretty_print)
  5369. {
  5370. o->write_characters("{\n", 2);
  5371. // variable to hold indentation for recursive calls
  5372. const auto new_indent = current_indent + indent_step;
  5373. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  5374. {
  5375. indent_string.resize(indent_string.size() * 2, ' ');
  5376. }
  5377. // first n-1 elements
  5378. auto i = val.m_value.object->cbegin();
  5379. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5380. {
  5381. o->write_characters(indent_string.c_str(), new_indent);
  5382. o->write_character('\"');
  5383. dump_escaped(i->first, ensure_ascii);
  5384. o->write_characters("\": ", 3);
  5385. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  5386. o->write_characters(",\n", 2);
  5387. }
  5388. // last element
  5389. assert(i != val.m_value.object->cend());
  5390. assert(std::next(i) == val.m_value.object->cend());
  5391. o->write_characters(indent_string.c_str(), new_indent);
  5392. o->write_character('\"');
  5393. dump_escaped(i->first, ensure_ascii);
  5394. o->write_characters("\": ", 3);
  5395. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  5396. o->write_character('\n');
  5397. o->write_characters(indent_string.c_str(), current_indent);
  5398. o->write_character('}');
  5399. }
  5400. else
  5401. {
  5402. o->write_character('{');
  5403. // first n-1 elements
  5404. auto i = val.m_value.object->cbegin();
  5405. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5406. {
  5407. o->write_character('\"');
  5408. dump_escaped(i->first, ensure_ascii);
  5409. o->write_characters("\":", 2);
  5410. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  5411. o->write_character(',');
  5412. }
  5413. // last element
  5414. assert(i != val.m_value.object->cend());
  5415. assert(std::next(i) == val.m_value.object->cend());
  5416. o->write_character('\"');
  5417. dump_escaped(i->first, ensure_ascii);
  5418. o->write_characters("\":", 2);
  5419. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  5420. o->write_character('}');
  5421. }
  5422. return;
  5423. }
  5424. case value_t::array:
  5425. {
  5426. if (val.m_value.array->empty())
  5427. {
  5428. o->write_characters("[]", 2);
  5429. return;
  5430. }
  5431. if (pretty_print)
  5432. {
  5433. o->write_characters("[\n", 2);
  5434. // variable to hold indentation for recursive calls
  5435. const auto new_indent = current_indent + indent_step;
  5436. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  5437. {
  5438. indent_string.resize(indent_string.size() * 2, ' ');
  5439. }
  5440. // first n-1 elements
  5441. for (auto i = val.m_value.array->cbegin();
  5442. i != val.m_value.array->cend() - 1; ++i)
  5443. {
  5444. o->write_characters(indent_string.c_str(), new_indent);
  5445. dump(*i, true, ensure_ascii, indent_step, new_indent);
  5446. o->write_characters(",\n", 2);
  5447. }
  5448. // last element
  5449. assert(not val.m_value.array->empty());
  5450. o->write_characters(indent_string.c_str(), new_indent);
  5451. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  5452. o->write_character('\n');
  5453. o->write_characters(indent_string.c_str(), current_indent);
  5454. o->write_character(']');
  5455. }
  5456. else
  5457. {
  5458. o->write_character('[');
  5459. // first n-1 elements
  5460. for (auto i = val.m_value.array->cbegin();
  5461. i != val.m_value.array->cend() - 1; ++i)
  5462. {
  5463. dump(*i, false, ensure_ascii, indent_step, current_indent);
  5464. o->write_character(',');
  5465. }
  5466. // last element
  5467. assert(not val.m_value.array->empty());
  5468. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  5469. o->write_character(']');
  5470. }
  5471. return;
  5472. }
  5473. case value_t::string:
  5474. {
  5475. o->write_character('\"');
  5476. dump_escaped(*val.m_value.string, ensure_ascii);
  5477. o->write_character('\"');
  5478. return;
  5479. }
  5480. case value_t::boolean:
  5481. {
  5482. if (val.m_value.boolean)
  5483. {
  5484. o->write_characters("true", 4);
  5485. }
  5486. else
  5487. {
  5488. o->write_characters("false", 5);
  5489. }
  5490. return;
  5491. }
  5492. case value_t::number_integer:
  5493. {
  5494. dump_integer(val.m_value.number_integer);
  5495. return;
  5496. }
  5497. case value_t::number_unsigned:
  5498. {
  5499. dump_integer(val.m_value.number_unsigned);
  5500. return;
  5501. }
  5502. case value_t::number_float:
  5503. {
  5504. dump_float(val.m_value.number_float);
  5505. return;
  5506. }
  5507. case value_t::discarded:
  5508. {
  5509. o->write_characters("<discarded>", 11);
  5510. return;
  5511. }
  5512. case value_t::null:
  5513. {
  5514. o->write_characters("null", 4);
  5515. return;
  5516. }
  5517. }
  5518. }
  5519. private:
  5520. /*!
  5521. @brief returns the number of expected bytes following in UTF-8 string
  5522. @param[in] u the first byte of a UTF-8 string
  5523. @return the number of expected bytes following
  5524. */
  5525. static constexpr std::size_t bytes_following(const uint8_t u)
  5526. {
  5527. return ((u <= 127) ? 0
  5528. : ((192 <= u and u <= 223) ? 1
  5529. : ((224 <= u and u <= 239) ? 2
  5530. : ((240 <= u and u <= 247) ? 3 : std::string::npos))));
  5531. }
  5532. /*!
  5533. @brief calculates the extra space to escape a JSON string
  5534. @param[in] s the string to escape
  5535. @param[in] ensure_ascii whether to escape non-ASCII characters with
  5536. \uXXXX sequences
  5537. @return the number of characters required to escape string @a s
  5538. @complexity Linear in the length of string @a s.
  5539. */
  5540. static std::size_t extra_space(const string_t& s,
  5541. const bool ensure_ascii) noexcept
  5542. {
  5543. std::size_t res = 0;
  5544. for (std::size_t i = 0; i < s.size(); ++i)
  5545. {
  5546. switch (s[i])
  5547. {
  5548. // control characters that can be escaped with a backslash
  5549. case '"':
  5550. case '\\':
  5551. case '\b':
  5552. case '\f':
  5553. case '\n':
  5554. case '\r':
  5555. case '\t':
  5556. {
  5557. // from c (1 byte) to \x (2 bytes)
  5558. res += 1;
  5559. break;
  5560. }
  5561. // control characters that need \uxxxx escaping
  5562. case 0x00:
  5563. case 0x01:
  5564. case 0x02:
  5565. case 0x03:
  5566. case 0x04:
  5567. case 0x05:
  5568. case 0x06:
  5569. case 0x07:
  5570. case 0x0B:
  5571. case 0x0E:
  5572. case 0x0F:
  5573. case 0x10:
  5574. case 0x11:
  5575. case 0x12:
  5576. case 0x13:
  5577. case 0x14:
  5578. case 0x15:
  5579. case 0x16:
  5580. case 0x17:
  5581. case 0x18:
  5582. case 0x19:
  5583. case 0x1A:
  5584. case 0x1B:
  5585. case 0x1C:
  5586. case 0x1D:
  5587. case 0x1E:
  5588. case 0x1F:
  5589. {
  5590. // from c (1 byte) to \uxxxx (6 bytes)
  5591. res += 5;
  5592. break;
  5593. }
  5594. default:
  5595. {
  5596. if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))
  5597. {
  5598. const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
  5599. // invalid characters will be detected by throw_if_invalid_utf8
  5600. assert (bytes != std::string::npos);
  5601. if (bytes == 3)
  5602. {
  5603. // codepoints that need 4 bytes (i.e., 3 additional
  5604. // bytes) in UTF-8 need a surrogate pair when \u
  5605. // escaping is used: from 4 bytes to \uxxxx\uxxxx
  5606. // (12 bytes)
  5607. res += (12 - bytes - 1);
  5608. }
  5609. else
  5610. {
  5611. // from x bytes to \uxxxx (6 bytes)
  5612. res += (6 - bytes - 1);
  5613. }
  5614. // skip the additional bytes
  5615. i += bytes;
  5616. }
  5617. break;
  5618. }
  5619. }
  5620. }
  5621. return res;
  5622. }
  5623. static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)
  5624. {
  5625. // expecting a proper codepoint
  5626. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  5627. // the last written character was the backslash before the 'u'
  5628. assert(result[pos] == '\\');
  5629. // write the 'u'
  5630. result[++pos] = 'u';
  5631. // convert a number 0..15 to its hex representation (0..f)
  5632. static const std::array<char, 16> hexify =
  5633. {
  5634. {
  5635. '0', '1', '2', '3', '4', '5', '6', '7',
  5636. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  5637. }
  5638. };
  5639. if (codepoint < 0x10000)
  5640. {
  5641. // codepoints U+0000..U+FFFF can be represented as \uxxxx.
  5642. result[++pos] = hexify[(codepoint >> 12) & 0x0F];
  5643. result[++pos] = hexify[(codepoint >> 8) & 0x0F];
  5644. result[++pos] = hexify[(codepoint >> 4) & 0x0F];
  5645. result[++pos] = hexify[codepoint & 0x0F];
  5646. }
  5647. else
  5648. {
  5649. // codepoints U+10000..U+10FFFF need a surrogate pair to be
  5650. // represented as \uxxxx\uxxxx.
  5651. // http://www.unicode.org/faq/utf_bom.html#utf16-4
  5652. codepoint -= 0x10000;
  5653. const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);
  5654. const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);
  5655. result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];
  5656. result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];
  5657. result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];
  5658. result[++pos] = hexify[high_surrogate & 0x0F];
  5659. ++pos; // backslash is already in output
  5660. result[++pos] = 'u';
  5661. result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];
  5662. result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];
  5663. result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];
  5664. result[++pos] = hexify[low_surrogate & 0x0F];
  5665. }
  5666. ++pos;
  5667. }
  5668. /*!
  5669. @brief dump escaped string
  5670. Escape a string by replacing certain special characters by a sequence of an
  5671. escape character (backslash) and another character and other control
  5672. characters by a sequence of "\u" followed by a four-digit hex
  5673. representation. The escaped string is written to output stream @a o.
  5674. @param[in] s the string to escape
  5675. @param[in] ensure_ascii whether to escape non-ASCII characters with
  5676. \uXXXX sequences
  5677. @complexity Linear in the length of string @a s.
  5678. */
  5679. void dump_escaped(const string_t& s, const bool ensure_ascii) const
  5680. {
  5681. throw_if_invalid_utf8(s);
  5682. const auto space = extra_space(s, ensure_ascii);
  5683. if (space == 0)
  5684. {
  5685. o->write_characters(s.c_str(), s.size());
  5686. return;
  5687. }
  5688. // create a result string of necessary size
  5689. string_t result(s.size() + space, '\\');
  5690. std::size_t pos = 0;
  5691. for (std::size_t i = 0; i < s.size(); ++i)
  5692. {
  5693. switch (s[i])
  5694. {
  5695. case '"': // quotation mark (0x22)
  5696. {
  5697. result[pos + 1] = '"';
  5698. pos += 2;
  5699. break;
  5700. }
  5701. case '\\': // reverse solidus (0x5C)
  5702. {
  5703. // nothing to change
  5704. pos += 2;
  5705. break;
  5706. }
  5707. case '\b': // backspace (0x08)
  5708. {
  5709. result[pos + 1] = 'b';
  5710. pos += 2;
  5711. break;
  5712. }
  5713. case '\f': // formfeed (0x0C)
  5714. {
  5715. result[pos + 1] = 'f';
  5716. pos += 2;
  5717. break;
  5718. }
  5719. case '\n': // newline (0x0A)
  5720. {
  5721. result[pos + 1] = 'n';
  5722. pos += 2;
  5723. break;
  5724. }
  5725. case '\r': // carriage return (0x0D)
  5726. {
  5727. result[pos + 1] = 'r';
  5728. pos += 2;
  5729. break;
  5730. }
  5731. case '\t': // horizontal tab (0x09)
  5732. {
  5733. result[pos + 1] = 't';
  5734. pos += 2;
  5735. break;
  5736. }
  5737. default:
  5738. {
  5739. // escape control characters (0x00..0x1F) or, if
  5740. // ensure_ascii parameter is used, non-ASCII characters
  5741. if ((0x00 <= s[i] and s[i] <= 0x1F) or
  5742. (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))
  5743. {
  5744. const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
  5745. // invalid characters will be detected by throw_if_invalid_utf8
  5746. assert (bytes != std::string::npos);
  5747. // check that the additional bytes are present
  5748. assert(i + bytes < s.size());
  5749. // to use \uxxxx escaping, we first need to calculate
  5750. // the codepoint from the UTF-8 bytes
  5751. int codepoint = 0;
  5752. // bytes is unsigned type:
  5753. assert(bytes <= 3);
  5754. switch (bytes)
  5755. {
  5756. case 0:
  5757. {
  5758. codepoint = s[i] & 0xFF;
  5759. break;
  5760. }
  5761. case 1:
  5762. {
  5763. codepoint = ((s[i] & 0x3F) << 6)
  5764. + (s[i + 1] & 0x7F);
  5765. break;
  5766. }
  5767. case 2:
  5768. {
  5769. codepoint = ((s[i] & 0x1F) << 12)
  5770. + ((s[i + 1] & 0x7F) << 6)
  5771. + (s[i + 2] & 0x7F);
  5772. break;
  5773. }
  5774. case 3:
  5775. {
  5776. codepoint = ((s[i] & 0xF) << 18)
  5777. + ((s[i + 1] & 0x7F) << 12)
  5778. + ((s[i + 2] & 0x7F) << 6)
  5779. + (s[i + 3] & 0x7F);
  5780. break;
  5781. }
  5782. default:
  5783. break; // LCOV_EXCL_LINE
  5784. }
  5785. escape_codepoint(codepoint, result, pos);
  5786. i += bytes;
  5787. }
  5788. else
  5789. {
  5790. // all other characters are added as-is
  5791. result[pos++] = s[i];
  5792. }
  5793. break;
  5794. }
  5795. }
  5796. }
  5797. assert(pos == result.size());
  5798. o->write_characters(result.c_str(), result.size());
  5799. }
  5800. /*!
  5801. @brief dump an integer
  5802. Dump a given integer to output stream @a o. Works internally with
  5803. @a number_buffer.
  5804. @param[in] x integer number (signed or unsigned) to dump
  5805. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  5806. */
  5807. template<typename NumberType, detail::enable_if_t<
  5808. std::is_same<NumberType, number_unsigned_t>::value or
  5809. std::is_same<NumberType, number_integer_t>::value,
  5810. int> = 0>
  5811. void dump_integer(NumberType x)
  5812. {
  5813. // special case for "0"
  5814. if (x == 0)
  5815. {
  5816. o->write_character('0');
  5817. return;
  5818. }
  5819. const bool is_negative = (x <= 0) and (x != 0); // see issue #755
  5820. std::size_t i = 0;
  5821. while (x != 0)
  5822. {
  5823. // spare 1 byte for '\0'
  5824. assert(i < number_buffer.size() - 1);
  5825. const auto digit = std::labs(static_cast<long>(x % 10));
  5826. number_buffer[i++] = static_cast<char>('0' + digit);
  5827. x /= 10;
  5828. }
  5829. if (is_negative)
  5830. {
  5831. // make sure there is capacity for the '-'
  5832. assert(i < number_buffer.size() - 2);
  5833. number_buffer[i++] = '-';
  5834. }
  5835. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  5836. o->write_characters(number_buffer.data(), i);
  5837. }
  5838. /*!
  5839. @brief dump a floating-point number
  5840. Dump a given floating-point number to output stream @a o. Works internally
  5841. with @a number_buffer.
  5842. @param[in] x floating-point number to dump
  5843. */
  5844. void dump_float(number_float_t x)
  5845. {
  5846. // NaN / inf
  5847. if (not std::isfinite(x) or std::isnan(x))
  5848. {
  5849. o->write_characters("null", 4);
  5850. return;
  5851. }
  5852. // get number of digits for a text -> float -> text round-trip
  5853. static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
  5854. // the actual conversion
  5855. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  5856. // negative value indicates an error
  5857. assert(len > 0);
  5858. // check if buffer was large enough
  5859. assert(static_cast<std::size_t>(len) < number_buffer.size());
  5860. // erase thousands separator
  5861. if (thousands_sep != '\0')
  5862. {
  5863. const auto end = std::remove(number_buffer.begin(),
  5864. number_buffer.begin() + len, thousands_sep);
  5865. std::fill(end, number_buffer.end(), '\0');
  5866. assert((end - number_buffer.begin()) <= len);
  5867. len = (end - number_buffer.begin());
  5868. }
  5869. // convert decimal point to '.'
  5870. if (decimal_point != '\0' and decimal_point != '.')
  5871. {
  5872. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  5873. if (dec_pos != number_buffer.end())
  5874. {
  5875. *dec_pos = '.';
  5876. }
  5877. }
  5878. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  5879. // determine if need to append ".0"
  5880. const bool value_is_int_like =
  5881. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  5882. [](char c)
  5883. {
  5884. return (c == '.' or c == 'e');
  5885. });
  5886. if (value_is_int_like)
  5887. {
  5888. o->write_characters(".0", 2);
  5889. }
  5890. }
  5891. /*!
  5892. @brief check whether a string is UTF-8 encoded
  5893. The function checks each byte of a string whether it is UTF-8 encoded. The
  5894. result of the check is stored in the @a state parameter. The function must
  5895. be called initially with state 0 (accept). State 1 means the string must
  5896. be rejected, because the current byte is not allowed. If the string is
  5897. completely processed, but the state is non-zero, the string ended
  5898. prematurely; that is, the last byte indicated more bytes should have
  5899. followed.
  5900. @param[in,out] state the state of the decoding
  5901. @param[in] byte next byte to decode
  5902. @note The function has been edited: a std::array is used and the code
  5903. point is not calculated.
  5904. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
  5905. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  5906. */
  5907. static void decode(uint8_t& state, const uint8_t byte)
  5908. {
  5909. static const std::array<uint8_t, 400> utf8d =
  5910. {
  5911. {
  5912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
  5913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
  5914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
  5915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
  5916. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
  5917. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
  5918. 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
  5919. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  5920. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  5921. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  5922. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
  5923. 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
  5924. 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
  5925. 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
  5926. }
  5927. };
  5928. const uint8_t type = utf8d[byte];
  5929. state = utf8d[256u + state * 16u + type];
  5930. }
  5931. /*!
  5932. @brief throw an exception if a string is not UTF-8 encoded
  5933. @param[in] str UTF-8 string to check
  5934. @throw type_error.316 if passed string is not UTF-8 encoded
  5935. @since version 3.0.0
  5936. */
  5937. static void throw_if_invalid_utf8(const std::string& str)
  5938. {
  5939. // start with state 0 (= accept)
  5940. uint8_t state = 0;
  5941. for (size_t i = 0; i < str.size(); ++i)
  5942. {
  5943. const auto byte = static_cast<uint8_t>(str[i]);
  5944. decode(state, byte);
  5945. if (state == 1)
  5946. {
  5947. // state 1 means reject
  5948. std::stringstream ss;
  5949. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);
  5950. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str()));
  5951. }
  5952. }
  5953. if (state != 0)
  5954. {
  5955. // we finish reading, but do not accept: string was incomplete
  5956. std::stringstream ss;
  5957. ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(str.back()));
  5958. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str()));
  5959. }
  5960. }
  5961. private:
  5962. /// the output of the serializer
  5963. output_adapter_t<char> o = nullptr;
  5964. /// a (hopefully) large enough character buffer
  5965. std::array<char, 64> number_buffer{{}};
  5966. /// the locale
  5967. const std::lconv* loc = nullptr;
  5968. /// the locale's thousand separator character
  5969. const char thousands_sep = '\0';
  5970. /// the locale's decimal point character
  5971. const char decimal_point = '\0';
  5972. /// the indentation character
  5973. const char indent_char;
  5974. /// the indentation string
  5975. string_t indent_string;
  5976. };
  5977. template<typename BasicJsonType>
  5978. class json_ref
  5979. {
  5980. public:
  5981. using value_type = BasicJsonType;
  5982. json_ref(value_type&& value)
  5983. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  5984. {}
  5985. json_ref(const value_type& value)
  5986. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  5987. {}
  5988. json_ref(std::initializer_list<json_ref> init)
  5989. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  5990. {}
  5991. template<class... Args>
  5992. json_ref(Args&& ... args)
  5993. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
  5994. {}
  5995. // class should be movable only
  5996. json_ref(json_ref&&) = default;
  5997. json_ref(const json_ref&) = delete;
  5998. json_ref& operator=(const json_ref&) = delete;
  5999. value_type moved_or_copied() const
  6000. {
  6001. if (is_rvalue)
  6002. {
  6003. return std::move(*value_ref);
  6004. }
  6005. return *value_ref;
  6006. }
  6007. value_type const& operator*() const
  6008. {
  6009. return *static_cast<value_type const*>(value_ref);
  6010. }
  6011. value_type const* operator->() const
  6012. {
  6013. return static_cast<value_type const*>(value_ref);
  6014. }
  6015. private:
  6016. mutable value_type owned_value = nullptr;
  6017. value_type* value_ref = nullptr;
  6018. const bool is_rvalue;
  6019. };
  6020. } // namespace detail
  6021. /// namespace to hold default `to_json` / `from_json` functions
  6022. namespace
  6023. {
  6024. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  6025. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  6026. }
  6027. /*!
  6028. @brief default JSONSerializer template argument
  6029. This serializer ignores the template arguments and uses ADL
  6030. ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
  6031. for serialization.
  6032. */
  6033. template<typename, typename>
  6034. struct adl_serializer
  6035. {
  6036. /*!
  6037. @brief convert a JSON value to any value type
  6038. This function is usually called by the `get()` function of the
  6039. @ref basic_json class (either explicit or via conversion operators).
  6040. @param[in] j JSON value to read from
  6041. @param[in,out] val value to write to
  6042. */
  6043. template<typename BasicJsonType, typename ValueType>
  6044. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  6045. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  6046. {
  6047. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  6048. }
  6049. /*!
  6050. @brief convert any value type to a JSON value
  6051. This function is usually called by the constructors of the @ref basic_json
  6052. class.
  6053. @param[in,out] j JSON value to write to
  6054. @param[in] val value to read from
  6055. */
  6056. template<typename BasicJsonType, typename ValueType>
  6057. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  6058. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  6059. {
  6060. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  6061. }
  6062. };
  6063. /*!
  6064. @brief JSON Pointer
  6065. A JSON pointer defines a string syntax for identifying a specific value
  6066. within a JSON document. It can be used with functions `at` and
  6067. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  6068. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  6069. @since version 2.0.0
  6070. */
  6071. class json_pointer
  6072. {
  6073. /// allow basic_json to access private members
  6074. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6075. friend class basic_json;
  6076. public:
  6077. /*!
  6078. @brief create JSON pointer
  6079. Create a JSON pointer according to the syntax described in
  6080. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  6081. @param[in] s string representing the JSON pointer; if omitted, the empty
  6082. string is assumed which references the whole JSON value
  6083. @throw parse_error.107 if the given JSON pointer @a s is nonempty and
  6084. does not begin with a slash (`/`); see example below
  6085. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
  6086. is not followed by `0` (representing `~`) or `1` (representing `/`);
  6087. see example below
  6088. @liveexample{The example shows the construction several valid JSON
  6089. pointers as well as the exceptional behavior.,json_pointer}
  6090. @since version 2.0.0
  6091. */
  6092. explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {}
  6093. /*!
  6094. @brief return a string representation of the JSON pointer
  6095. @invariant For each JSON pointer `ptr`, it holds:
  6096. @code {.cpp}
  6097. ptr == json_pointer(ptr.to_string());
  6098. @endcode
  6099. @return a string representation of the JSON pointer
  6100. @liveexample{The example shows the result of `to_string`.,
  6101. json_pointer__to_string}
  6102. @since version 2.0.0
  6103. */
  6104. std::string to_string() const noexcept
  6105. {
  6106. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  6107. std::string{},
  6108. [](const std::string & a, const std::string & b)
  6109. {
  6110. return a + "/" + escape(b);
  6111. });
  6112. }
  6113. /// @copydoc to_string()
  6114. operator std::string() const
  6115. {
  6116. return to_string();
  6117. }
  6118. /*!
  6119. @param[in] s reference token to be converted into an array index
  6120. @return integer representation of @a s
  6121. @throw out_of_range.404 if string @a s could not be converted to an integer
  6122. */
  6123. static int array_index(const std::string& s)
  6124. {
  6125. size_t processed_chars = 0;
  6126. const int res = std::stoi(s, &processed_chars);
  6127. // check if the string was completely read
  6128. if (JSON_UNLIKELY(processed_chars != s.size()))
  6129. {
  6130. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  6131. }
  6132. return res;
  6133. }
  6134. private:
  6135. /*!
  6136. @brief remove and return last reference pointer
  6137. @throw out_of_range.405 if JSON pointer has no parent
  6138. */
  6139. std::string pop_back()
  6140. {
  6141. if (JSON_UNLIKELY(is_root()))
  6142. {
  6143. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  6144. }
  6145. auto last = reference_tokens.back();
  6146. reference_tokens.pop_back();
  6147. return last;
  6148. }
  6149. /// return whether pointer points to the root document
  6150. bool is_root() const
  6151. {
  6152. return reference_tokens.empty();
  6153. }
  6154. json_pointer top() const
  6155. {
  6156. if (JSON_UNLIKELY(is_root()))
  6157. {
  6158. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  6159. }
  6160. json_pointer result = *this;
  6161. result.reference_tokens = {reference_tokens[0]};
  6162. return result;
  6163. }
  6164. /*!
  6165. @brief create and return a reference to the pointed to value
  6166. @complexity Linear in the number of reference tokens.
  6167. @throw parse_error.109 if array index is not a number
  6168. @throw type_error.313 if value cannot be unflattened
  6169. */
  6170. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6171. NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;
  6172. /*!
  6173. @brief return a reference to the pointed to value
  6174. @note This version does not throw if a value is not present, but tries to
  6175. create nested values instead. For instance, calling this function
  6176. with pointer `"/this/that"` on a null value is equivalent to calling
  6177. `operator[]("this").operator[]("that")` on that value, effectively
  6178. changing the null value to an object.
  6179. @param[in] ptr a JSON value
  6180. @return reference to the JSON value pointed to by the JSON pointer
  6181. @complexity Linear in the length of the JSON pointer.
  6182. @throw parse_error.106 if an array index begins with '0'
  6183. @throw parse_error.109 if an array index was not a number
  6184. @throw out_of_range.404 if the JSON pointer can not be resolved
  6185. */
  6186. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6187. NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6188. /*!
  6189. @throw parse_error.106 if an array index begins with '0'
  6190. @throw parse_error.109 if an array index was not a number
  6191. @throw out_of_range.402 if the array index '-' is used
  6192. @throw out_of_range.404 if the JSON pointer can not be resolved
  6193. */
  6194. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6195. NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6196. /*!
  6197. @brief return a const reference to the pointed to value
  6198. @param[in] ptr a JSON value
  6199. @return const reference to the JSON value pointed to by the JSON
  6200. pointer
  6201. @throw parse_error.106 if an array index begins with '0'
  6202. @throw parse_error.109 if an array index was not a number
  6203. @throw out_of_range.402 if the array index '-' is used
  6204. @throw out_of_range.404 if the JSON pointer can not be resolved
  6205. */
  6206. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6207. const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6208. /*!
  6209. @throw parse_error.106 if an array index begins with '0'
  6210. @throw parse_error.109 if an array index was not a number
  6211. @throw out_of_range.402 if the array index '-' is used
  6212. @throw out_of_range.404 if the JSON pointer can not be resolved
  6213. */
  6214. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6215. const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6216. /*!
  6217. @brief split the string input to reference tokens
  6218. @note This function is only called by the json_pointer constructor.
  6219. All exceptions below are documented there.
  6220. @throw parse_error.107 if the pointer is not empty or begins with '/'
  6221. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  6222. */
  6223. static std::vector<std::string> split(const std::string& reference_string)
  6224. {
  6225. std::vector<std::string> result;
  6226. // special case: empty reference string -> no reference tokens
  6227. if (reference_string.empty())
  6228. {
  6229. return result;
  6230. }
  6231. // check if nonempty reference string begins with slash
  6232. if (JSON_UNLIKELY(reference_string[0] != '/'))
  6233. {
  6234. JSON_THROW(detail::parse_error::create(107, 1,
  6235. "JSON pointer must be empty or begin with '/' - was: '" +
  6236. reference_string + "'"));
  6237. }
  6238. // extract the reference tokens:
  6239. // - slash: position of the last read slash (or end of string)
  6240. // - start: position after the previous slash
  6241. for (
  6242. // search for the first slash after the first character
  6243. std::size_t slash = reference_string.find_first_of('/', 1),
  6244. // set the beginning of the first reference token
  6245. start = 1;
  6246. // we can stop if start == string::npos+1 = 0
  6247. start != 0;
  6248. // set the beginning of the next reference token
  6249. // (will eventually be 0 if slash == std::string::npos)
  6250. start = slash + 1,
  6251. // find next slash
  6252. slash = reference_string.find_first_of('/', start))
  6253. {
  6254. // use the text between the beginning of the reference token
  6255. // (start) and the last slash (slash).
  6256. auto reference_token = reference_string.substr(start, slash - start);
  6257. // check reference tokens are properly escaped
  6258. for (std::size_t pos = reference_token.find_first_of('~');
  6259. pos != std::string::npos;
  6260. pos = reference_token.find_first_of('~', pos + 1))
  6261. {
  6262. assert(reference_token[pos] == '~');
  6263. // ~ must be followed by 0 or 1
  6264. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  6265. (reference_token[pos + 1] != '0' and
  6266. reference_token[pos + 1] != '1')))
  6267. {
  6268. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  6269. }
  6270. }
  6271. // finally, store the reference token
  6272. unescape(reference_token);
  6273. result.push_back(reference_token);
  6274. }
  6275. return result;
  6276. }
  6277. /*!
  6278. @brief replace all occurrences of a substring by another string
  6279. @param[in,out] s the string to manipulate; changed so that all
  6280. occurrences of @a f are replaced with @a t
  6281. @param[in] f the substring to replace with @a t
  6282. @param[in] t the string to replace @a f
  6283. @pre The search string @a f must not be empty. **This precondition is
  6284. enforced with an assertion.**
  6285. @since version 2.0.0
  6286. */
  6287. static void replace_substring(std::string& s, const std::string& f,
  6288. const std::string& t)
  6289. {
  6290. assert(not f.empty());
  6291. for (auto pos = s.find(f); // find first occurrence of f
  6292. pos != std::string::npos; // make sure f was found
  6293. s.replace(pos, f.size(), t), // replace with t, and
  6294. pos = s.find(f, pos + t.size())) // find next occurrence of f
  6295. {}
  6296. }
  6297. /// escape "~"" to "~0" and "/" to "~1"
  6298. static std::string escape(std::string s)
  6299. {
  6300. replace_substring(s, "~", "~0");
  6301. replace_substring(s, "/", "~1");
  6302. return s;
  6303. }
  6304. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  6305. static void unescape(std::string& s)
  6306. {
  6307. replace_substring(s, "~1", "/");
  6308. replace_substring(s, "~0", "~");
  6309. }
  6310. /*!
  6311. @param[in] reference_string the reference string to the current value
  6312. @param[in] value the value to consider
  6313. @param[in,out] result the result object to insert values to
  6314. @note Empty objects or arrays are flattened to `null`.
  6315. */
  6316. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6317. static void flatten(const std::string& reference_string,
  6318. const NLOHMANN_BASIC_JSON_TPL& value,
  6319. NLOHMANN_BASIC_JSON_TPL& result);
  6320. /*!
  6321. @param[in] value flattened JSON
  6322. @return unflattened JSON
  6323. @throw parse_error.109 if array index is not a number
  6324. @throw type_error.314 if value is not an object
  6325. @throw type_error.315 if object values are not primitive
  6326. @throw type_error.313 if value cannot be unflattened
  6327. */
  6328. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6329. static NLOHMANN_BASIC_JSON_TPL
  6330. unflatten(const NLOHMANN_BASIC_JSON_TPL& value);
  6331. friend bool operator==(json_pointer const& lhs,
  6332. json_pointer const& rhs) noexcept;
  6333. friend bool operator!=(json_pointer const& lhs,
  6334. json_pointer const& rhs) noexcept;
  6335. /// the reference tokens
  6336. std::vector<std::string> reference_tokens;
  6337. };
  6338. /*!
  6339. @brief a class to store JSON values
  6340. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  6341. in @ref object_t)
  6342. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  6343. in @ref array_t)
  6344. @tparam StringType type for JSON strings and object keys (`std::string` by
  6345. default; will be used in @ref string_t)
  6346. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  6347. in @ref boolean_t)
  6348. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  6349. default; will be used in @ref number_integer_t)
  6350. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  6351. `uint64_t` by default; will be used in @ref number_unsigned_t)
  6352. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  6353. default; will be used in @ref number_float_t)
  6354. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  6355. default)
  6356. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  6357. and `from_json()` (@ref adl_serializer by default)
  6358. @requirement The class satisfies the following concept requirements:
  6359. - Basic
  6360. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  6361. JSON values can be default constructed. The result will be a JSON null
  6362. value.
  6363. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  6364. A JSON value can be constructed from an rvalue argument.
  6365. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  6366. A JSON value can be copy-constructed from an lvalue expression.
  6367. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  6368. A JSON value van be assigned from an rvalue argument.
  6369. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  6370. A JSON value can be copy-assigned from an lvalue expression.
  6371. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  6372. JSON values can be destructed.
  6373. - Layout
  6374. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  6375. JSON values have
  6376. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  6377. All non-static data members are private and standard layout types, the
  6378. class has no virtual functions or (virtual) base classes.
  6379. - Library-wide
  6380. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  6381. JSON values can be compared with `==`, see @ref
  6382. operator==(const_reference,const_reference).
  6383. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  6384. JSON values can be compared with `<`, see @ref
  6385. operator<(const_reference,const_reference).
  6386. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  6387. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  6388. other compatible types, using unqualified function call @ref swap().
  6389. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  6390. JSON values can be compared against `std::nullptr_t` objects which are used
  6391. to model the `null` value.
  6392. - Container
  6393. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  6394. JSON values can be used like STL containers and provide iterator access.
  6395. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  6396. JSON values can be used like STL containers and provide reverse iterator
  6397. access.
  6398. @invariant The member variables @a m_value and @a m_type have the following
  6399. relationship:
  6400. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  6401. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  6402. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  6403. The invariants are checked by member function assert_invariant().
  6404. @internal
  6405. @note ObjectType trick from http://stackoverflow.com/a/9860911
  6406. @endinternal
  6407. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  6408. Format](http://rfc7159.net/rfc7159)
  6409. @since version 1.0.0
  6410. @nosubgrouping
  6411. */
  6412. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6413. class basic_json
  6414. {
  6415. private:
  6416. template<detail::value_t> friend struct detail::external_constructor;
  6417. friend ::nlohmann::json_pointer;
  6418. friend ::nlohmann::detail::parser<basic_json>;
  6419. friend ::nlohmann::detail::serializer<basic_json>;
  6420. template<typename BasicJsonType>
  6421. friend class ::nlohmann::detail::iter_impl;
  6422. template<typename BasicJsonType, typename CharType>
  6423. friend class ::nlohmann::detail::binary_writer;
  6424. template<typename BasicJsonType>
  6425. friend class ::nlohmann::detail::binary_reader;
  6426. /// workaround type for MSVC
  6427. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  6428. // convenience aliases for types residing in namespace detail;
  6429. using lexer = ::nlohmann::detail::lexer<basic_json>;
  6430. using parser = ::nlohmann::detail::parser<basic_json>;
  6431. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  6432. template<typename BasicJsonType>
  6433. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  6434. template<typename BasicJsonType>
  6435. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  6436. template<typename Iterator>
  6437. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  6438. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  6439. template<typename CharType>
  6440. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  6441. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  6442. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  6443. using serializer = ::nlohmann::detail::serializer<basic_json>;
  6444. public:
  6445. using value_t = detail::value_t;
  6446. /// @copydoc nlohmann::json_pointer
  6447. using json_pointer = ::nlohmann::json_pointer;
  6448. template<typename T, typename SFINAE>
  6449. using json_serializer = JSONSerializer<T, SFINAE>;
  6450. /// helper type for initializer lists of basic_json values
  6451. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  6452. ////////////////
  6453. // exceptions //
  6454. ////////////////
  6455. /// @name exceptions
  6456. /// Classes to implement user-defined exceptions.
  6457. /// @{
  6458. /// @copydoc detail::exception
  6459. using exception = detail::exception;
  6460. /// @copydoc detail::parse_error
  6461. using parse_error = detail::parse_error;
  6462. /// @copydoc detail::invalid_iterator
  6463. using invalid_iterator = detail::invalid_iterator;
  6464. /// @copydoc detail::type_error
  6465. using type_error = detail::type_error;
  6466. /// @copydoc detail::out_of_range
  6467. using out_of_range = detail::out_of_range;
  6468. /// @copydoc detail::other_error
  6469. using other_error = detail::other_error;
  6470. /// @}
  6471. /////////////////////
  6472. // container types //
  6473. /////////////////////
  6474. /// @name container types
  6475. /// The canonic container types to use @ref basic_json like any other STL
  6476. /// container.
  6477. /// @{
  6478. /// the type of elements in a basic_json container
  6479. using value_type = basic_json;
  6480. /// the type of an element reference
  6481. using reference = value_type&;
  6482. /// the type of an element const reference
  6483. using const_reference = const value_type&;
  6484. /// a type to represent differences between iterators
  6485. using difference_type = std::ptrdiff_t;
  6486. /// a type to represent container sizes
  6487. using size_type = std::size_t;
  6488. /// the allocator type
  6489. using allocator_type = AllocatorType<basic_json>;
  6490. /// the type of an element pointer
  6491. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  6492. /// the type of an element const pointer
  6493. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  6494. /// an iterator for a basic_json container
  6495. using iterator = iter_impl<basic_json>;
  6496. /// a const iterator for a basic_json container
  6497. using const_iterator = iter_impl<const basic_json>;
  6498. /// a reverse iterator for a basic_json container
  6499. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  6500. /// a const reverse iterator for a basic_json container
  6501. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  6502. /// @}
  6503. /*!
  6504. @brief returns the allocator associated with the container
  6505. */
  6506. static allocator_type get_allocator()
  6507. {
  6508. return allocator_type();
  6509. }
  6510. /*!
  6511. @brief returns version information on the library
  6512. This function returns a JSON object with information about the library,
  6513. including the version number and information on the platform and compiler.
  6514. @return JSON object holding version information
  6515. key | description
  6516. ----------- | ---------------
  6517. `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
  6518. `copyright` | The copyright line for the library as string.
  6519. `name` | The name of the library as string.
  6520. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  6521. `url` | The URL of the project as string.
  6522. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
  6523. @liveexample{The following code shows an example output of the `meta()`
  6524. function.,meta}
  6525. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  6526. changes to any JSON value.
  6527. @complexity Constant.
  6528. @since 2.1.0
  6529. */
  6530. static basic_json meta()
  6531. {
  6532. basic_json result;
  6533. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  6534. result["name"] = "JSON for Modern C++";
  6535. result["url"] = "https://github.com/nlohmann/json";
  6536. result["version"] =
  6537. {
  6538. {"string", "3.0.1"}, {"major", 3}, {"minor", 0}, {"patch", 1}
  6539. };
  6540. #ifdef _WIN32
  6541. result["platform"] = "win32";
  6542. #elif defined __linux__
  6543. result["platform"] = "linux";
  6544. #elif defined __APPLE__
  6545. result["platform"] = "apple";
  6546. #elif defined __unix__
  6547. result["platform"] = "unix";
  6548. #else
  6549. result["platform"] = "unknown";
  6550. #endif
  6551. #if defined(__ICC) || defined(__INTEL_COMPILER)
  6552. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  6553. #elif defined(__clang__)
  6554. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  6555. #elif defined(__GNUC__) || defined(__GNUG__)
  6556. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  6557. #elif defined(__HP_cc) || defined(__HP_aCC)
  6558. result["compiler"] = "hp"
  6559. #elif defined(__IBMCPP__)
  6560. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  6561. #elif defined(_MSC_VER)
  6562. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  6563. #elif defined(__PGI)
  6564. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  6565. #elif defined(__SUNPRO_CC)
  6566. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  6567. #else
  6568. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  6569. #endif
  6570. #ifdef __cplusplus
  6571. result["compiler"]["c++"] = std::to_string(__cplusplus);
  6572. #else
  6573. result["compiler"]["c++"] = "unknown";
  6574. #endif
  6575. return result;
  6576. }
  6577. ///////////////////////////
  6578. // JSON value data types //
  6579. ///////////////////////////
  6580. /// @name JSON value data types
  6581. /// The data types to store a JSON value. These types are derived from
  6582. /// the template arguments passed to class @ref basic_json.
  6583. /// @{
  6584. #if defined(JSON_HAS_CPP_14)
  6585. // Use transparent comparator if possible, combined with perfect forwarding
  6586. // on find() and count() calls prevents unnecessary string construction.
  6587. using object_comparator_t = std::less<>;
  6588. #else
  6589. using object_comparator_t = std::less<StringType>;
  6590. #endif
  6591. /*!
  6592. @brief a type for an object
  6593. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  6594. > An object is an unordered collection of zero or more name/value pairs,
  6595. > where a name is a string and a value is a string, number, boolean, null,
  6596. > object, or array.
  6597. To store objects in C++, a type is defined by the template parameters
  6598. described below.
  6599. @tparam ObjectType the container to store objects (e.g., `std::map` or
  6600. `std::unordered_map`)
  6601. @tparam StringType the type of the keys or names (e.g., `std::string`).
  6602. The comparison function `std::less<StringType>` is used to order elements
  6603. inside the container.
  6604. @tparam AllocatorType the allocator to use for objects (e.g.,
  6605. `std::allocator`)
  6606. #### Default type
  6607. With the default values for @a ObjectType (`std::map`), @a StringType
  6608. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  6609. value for @a object_t is:
  6610. @code {.cpp}
  6611. std::map<
  6612. std::string, // key_type
  6613. basic_json, // value_type
  6614. std::less<std::string>, // key_compare
  6615. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  6616. >
  6617. @endcode
  6618. #### Behavior
  6619. The choice of @a object_t influences the behavior of the JSON class. With
  6620. the default type, objects have the following behavior:
  6621. - When all names are unique, objects will be interoperable in the sense
  6622. that all software implementations receiving that object will agree on
  6623. the name-value mappings.
  6624. - When the names within an object are not unique, later stored name/value
  6625. pairs overwrite previously stored name/value pairs, leaving the used
  6626. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  6627. be treated as equal and both stored as `{"key": 1}`.
  6628. - Internally, name/value pairs are stored in lexicographical order of the
  6629. names. Objects will also be serialized (see @ref dump) in this order.
  6630. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  6631. and serialized as `{"a": 2, "b": 1}`.
  6632. - When comparing objects, the order of the name/value pairs is irrelevant.
  6633. This makes objects interoperable in the sense that they will not be
  6634. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  6635. `{"a": 2, "b": 1}` will be treated as equal.
  6636. #### Limits
  6637. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6638. > An implementation may set limits on the maximum depth of nesting.
  6639. In this class, the object's limit of nesting is not explicitly constrained.
  6640. However, a maximum depth of nesting may be introduced by the compiler or
  6641. runtime environment. A theoretical limit can be queried by calling the
  6642. @ref max_size function of a JSON object.
  6643. #### Storage
  6644. Objects are stored as pointers in a @ref basic_json type. That is, for any
  6645. access to object values, a pointer of type `object_t*` must be
  6646. dereferenced.
  6647. @sa @ref array_t -- type for an array value
  6648. @since version 1.0.0
  6649. @note The order name/value pairs are added to the object is *not*
  6650. preserved by the library. Therefore, iterating an object may return
  6651. name/value pairs in a different order than they were originally stored. In
  6652. fact, keys will be traversed in alphabetical order as `std::map` with
  6653. `std::less` is used by default. Please note this behavior conforms to [RFC
  6654. 7159](http://rfc7159.net/rfc7159), because any order implements the
  6655. specified "unordered" nature of JSON objects.
  6656. */
  6657. using object_t = ObjectType<StringType,
  6658. basic_json,
  6659. object_comparator_t,
  6660. AllocatorType<std::pair<const StringType,
  6661. basic_json>>>;
  6662. /*!
  6663. @brief a type for an array
  6664. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  6665. > An array is an ordered sequence of zero or more values.
  6666. To store objects in C++, a type is defined by the template parameters
  6667. explained below.
  6668. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  6669. `std::list`)
  6670. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  6671. #### Default type
  6672. With the default values for @a ArrayType (`std::vector`) and @a
  6673. AllocatorType (`std::allocator`), the default value for @a array_t is:
  6674. @code {.cpp}
  6675. std::vector<
  6676. basic_json, // value_type
  6677. std::allocator<basic_json> // allocator_type
  6678. >
  6679. @endcode
  6680. #### Limits
  6681. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6682. > An implementation may set limits on the maximum depth of nesting.
  6683. In this class, the array's limit of nesting is not explicitly constrained.
  6684. However, a maximum depth of nesting may be introduced by the compiler or
  6685. runtime environment. A theoretical limit can be queried by calling the
  6686. @ref max_size function of a JSON array.
  6687. #### Storage
  6688. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  6689. access to array values, a pointer of type `array_t*` must be dereferenced.
  6690. @sa @ref object_t -- type for an object value
  6691. @since version 1.0.0
  6692. */
  6693. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  6694. /*!
  6695. @brief a type for a string
  6696. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  6697. > A string is a sequence of zero or more Unicode characters.
  6698. To store objects in C++, a type is defined by the template parameter
  6699. described below. Unicode values are split by the JSON class into
  6700. byte-sized characters during deserialization.
  6701. @tparam StringType the container to store strings (e.g., `std::string`).
  6702. Note this container is used for keys/names in objects, see @ref object_t.
  6703. #### Default type
  6704. With the default values for @a StringType (`std::string`), the default
  6705. value for @a string_t is:
  6706. @code {.cpp}
  6707. std::string
  6708. @endcode
  6709. #### Encoding
  6710. Strings are stored in UTF-8 encoding. Therefore, functions like
  6711. `std::string::size()` or `std::string::length()` return the number of
  6712. bytes in the string rather than the number of characters or glyphs.
  6713. #### String comparison
  6714. [RFC 7159](http://rfc7159.net/rfc7159) states:
  6715. > Software implementations are typically required to test names of object
  6716. > members for equality. Implementations that transform the textual
  6717. > representation into sequences of Unicode code units and then perform the
  6718. > comparison numerically, code unit by code unit, are interoperable in the
  6719. > sense that implementations will agree in all cases on equality or
  6720. > inequality of two strings. For example, implementations that compare
  6721. > strings with escaped characters unconverted may incorrectly find that
  6722. > `"a\\b"` and `"a\u005Cb"` are not equal.
  6723. This implementation is interoperable as it does compare strings code unit
  6724. by code unit.
  6725. #### Storage
  6726. String values are stored as pointers in a @ref basic_json type. That is,
  6727. for any access to string values, a pointer of type `string_t*` must be
  6728. dereferenced.
  6729. @since version 1.0.0
  6730. */
  6731. using string_t = StringType;
  6732. /*!
  6733. @brief a type for a boolean
  6734. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  6735. type which differentiates the two literals `true` and `false`.
  6736. To store objects in C++, a type is defined by the template parameter @a
  6737. BooleanType which chooses the type to use.
  6738. #### Default type
  6739. With the default values for @a BooleanType (`bool`), the default value for
  6740. @a boolean_t is:
  6741. @code {.cpp}
  6742. bool
  6743. @endcode
  6744. #### Storage
  6745. Boolean values are stored directly inside a @ref basic_json type.
  6746. @since version 1.0.0
  6747. */
  6748. using boolean_t = BooleanType;
  6749. /*!
  6750. @brief a type for a number (integer)
  6751. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6752. > The representation of numbers is similar to that used in most
  6753. > programming languages. A number is represented in base 10 using decimal
  6754. > digits. It contains an integer component that may be prefixed with an
  6755. > optional minus sign, which may be followed by a fraction part and/or an
  6756. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6757. > cannot be represented in the grammar below (such as Infinity and NaN)
  6758. > are not permitted.
  6759. This description includes both integer and floating-point numbers.
  6760. However, C++ allows more precise storage if it is known whether the number
  6761. is a signed integer, an unsigned integer or a floating-point number.
  6762. Therefore, three different types, @ref number_integer_t, @ref
  6763. number_unsigned_t and @ref number_float_t are used.
  6764. To store integer numbers in C++, a type is defined by the template
  6765. parameter @a NumberIntegerType which chooses the type to use.
  6766. #### Default type
  6767. With the default values for @a NumberIntegerType (`int64_t`), the default
  6768. value for @a number_integer_t is:
  6769. @code {.cpp}
  6770. int64_t
  6771. @endcode
  6772. #### Default behavior
  6773. - The restrictions about leading zeros is not enforced in C++. Instead,
  6774. leading zeros in integer literals lead to an interpretation as octal
  6775. number. Internally, the value will be stored as decimal number. For
  6776. instance, the C++ integer literal `010` will be serialized to `8`.
  6777. During deserialization, leading zeros yield an error.
  6778. - Not-a-number (NaN) values will be serialized to `null`.
  6779. #### Limits
  6780. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6781. > An implementation may set limits on the range and precision of numbers.
  6782. When the default type is used, the maximal integer number that can be
  6783. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  6784. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  6785. that are out of range will yield over/underflow when used in a
  6786. constructor. During deserialization, too large or small integer numbers
  6787. will be automatically be stored as @ref number_unsigned_t or @ref
  6788. number_float_t.
  6789. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  6790. > Note that when such software is used, numbers that are integers and are
  6791. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  6792. > that implementations will agree exactly on their numeric values.
  6793. As this range is a subrange of the exactly supported range [INT64_MIN,
  6794. INT64_MAX], this class's integer type is interoperable.
  6795. #### Storage
  6796. Integer number values are stored directly inside a @ref basic_json type.
  6797. @sa @ref number_float_t -- type for number values (floating-point)
  6798. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  6799. @since version 1.0.0
  6800. */
  6801. using number_integer_t = NumberIntegerType;
  6802. /*!
  6803. @brief a type for a number (unsigned)
  6804. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6805. > The representation of numbers is similar to that used in most
  6806. > programming languages. A number is represented in base 10 using decimal
  6807. > digits. It contains an integer component that may be prefixed with an
  6808. > optional minus sign, which may be followed by a fraction part and/or an
  6809. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6810. > cannot be represented in the grammar below (such as Infinity and NaN)
  6811. > are not permitted.
  6812. This description includes both integer and floating-point numbers.
  6813. However, C++ allows more precise storage if it is known whether the number
  6814. is a signed integer, an unsigned integer or a floating-point number.
  6815. Therefore, three different types, @ref number_integer_t, @ref
  6816. number_unsigned_t and @ref number_float_t are used.
  6817. To store unsigned integer numbers in C++, a type is defined by the
  6818. template parameter @a NumberUnsignedType which chooses the type to use.
  6819. #### Default type
  6820. With the default values for @a NumberUnsignedType (`uint64_t`), the
  6821. default value for @a number_unsigned_t is:
  6822. @code {.cpp}
  6823. uint64_t
  6824. @endcode
  6825. #### Default behavior
  6826. - The restrictions about leading zeros is not enforced in C++. Instead,
  6827. leading zeros in integer literals lead to an interpretation as octal
  6828. number. Internally, the value will be stored as decimal number. For
  6829. instance, the C++ integer literal `010` will be serialized to `8`.
  6830. During deserialization, leading zeros yield an error.
  6831. - Not-a-number (NaN) values will be serialized to `null`.
  6832. #### Limits
  6833. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6834. > An implementation may set limits on the range and precision of numbers.
  6835. When the default type is used, the maximal integer number that can be
  6836. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  6837. number that can be stored is `0`. Integer numbers that are out of range
  6838. will yield over/underflow when used in a constructor. During
  6839. deserialization, too large or small integer numbers will be automatically
  6840. be stored as @ref number_integer_t or @ref number_float_t.
  6841. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  6842. > Note that when such software is used, numbers that are integers and are
  6843. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  6844. > that implementations will agree exactly on their numeric values.
  6845. As this range is a subrange (when considered in conjunction with the
  6846. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  6847. this class's integer type is interoperable.
  6848. #### Storage
  6849. Integer number values are stored directly inside a @ref basic_json type.
  6850. @sa @ref number_float_t -- type for number values (floating-point)
  6851. @sa @ref number_integer_t -- type for number values (integer)
  6852. @since version 2.0.0
  6853. */
  6854. using number_unsigned_t = NumberUnsignedType;
  6855. /*!
  6856. @brief a type for a number (floating-point)
  6857. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6858. > The representation of numbers is similar to that used in most
  6859. > programming languages. A number is represented in base 10 using decimal
  6860. > digits. It contains an integer component that may be prefixed with an
  6861. > optional minus sign, which may be followed by a fraction part and/or an
  6862. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6863. > cannot be represented in the grammar below (such as Infinity and NaN)
  6864. > are not permitted.
  6865. This description includes both integer and floating-point numbers.
  6866. However, C++ allows more precise storage if it is known whether the number
  6867. is a signed integer, an unsigned integer or a floating-point number.
  6868. Therefore, three different types, @ref number_integer_t, @ref
  6869. number_unsigned_t and @ref number_float_t are used.
  6870. To store floating-point numbers in C++, a type is defined by the template
  6871. parameter @a NumberFloatType which chooses the type to use.
  6872. #### Default type
  6873. With the default values for @a NumberFloatType (`double`), the default
  6874. value for @a number_float_t is:
  6875. @code {.cpp}
  6876. double
  6877. @endcode
  6878. #### Default behavior
  6879. - The restrictions about leading zeros is not enforced in C++. Instead,
  6880. leading zeros in floating-point literals will be ignored. Internally,
  6881. the value will be stored as decimal number. For instance, the C++
  6882. floating-point literal `01.2` will be serialized to `1.2`. During
  6883. deserialization, leading zeros yield an error.
  6884. - Not-a-number (NaN) values will be serialized to `null`.
  6885. #### Limits
  6886. [RFC 7159](http://rfc7159.net/rfc7159) states:
  6887. > This specification allows implementations to set limits on the range and
  6888. > precision of numbers accepted. Since software that implements IEEE
  6889. > 754-2008 binary64 (double precision) numbers is generally available and
  6890. > widely used, good interoperability can be achieved by implementations
  6891. > that expect no more precision or range than these provide, in the sense
  6892. > that implementations will approximate JSON numbers within the expected
  6893. > precision.
  6894. This implementation does exactly follow this approach, as it uses double
  6895. precision floating-point numbers. Note values smaller than
  6896. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  6897. will be stored as NaN internally and be serialized to `null`.
  6898. #### Storage
  6899. Floating-point number values are stored directly inside a @ref basic_json
  6900. type.
  6901. @sa @ref number_integer_t -- type for number values (integer)
  6902. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  6903. @since version 1.0.0
  6904. */
  6905. using number_float_t = NumberFloatType;
  6906. /// @}
  6907. private:
  6908. /// helper for exception-safe object creation
  6909. template<typename T, typename... Args>
  6910. static T* create(Args&& ... args)
  6911. {
  6912. AllocatorType<T> alloc;
  6913. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  6914. auto deleter = [&](T * object)
  6915. {
  6916. AllocatorTraits::deallocate(alloc, object, 1);
  6917. };
  6918. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  6919. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  6920. assert(object != nullptr);
  6921. return object.release();
  6922. }
  6923. ////////////////////////
  6924. // JSON value storage //
  6925. ////////////////////////
  6926. /*!
  6927. @brief a JSON value
  6928. The actual storage for a JSON value of the @ref basic_json class. This
  6929. union combines the different storage types for the JSON value types
  6930. defined in @ref value_t.
  6931. JSON type | value_t type | used type
  6932. --------- | --------------- | ------------------------
  6933. object | object | pointer to @ref object_t
  6934. array | array | pointer to @ref array_t
  6935. string | string | pointer to @ref string_t
  6936. boolean | boolean | @ref boolean_t
  6937. number | number_integer | @ref number_integer_t
  6938. number | number_unsigned | @ref number_unsigned_t
  6939. number | number_float | @ref number_float_t
  6940. null | null | *no value is stored*
  6941. @note Variable-length types (objects, arrays, and strings) are stored as
  6942. pointers. The size of the union should not exceed 64 bits if the default
  6943. value types are used.
  6944. @since version 1.0.0
  6945. */
  6946. union json_value
  6947. {
  6948. /// object (stored with pointer to save storage)
  6949. object_t* object;
  6950. /// array (stored with pointer to save storage)
  6951. array_t* array;
  6952. /// string (stored with pointer to save storage)
  6953. string_t* string;
  6954. /// boolean
  6955. boolean_t boolean;
  6956. /// number (integer)
  6957. number_integer_t number_integer;
  6958. /// number (unsigned integer)
  6959. number_unsigned_t number_unsigned;
  6960. /// number (floating-point)
  6961. number_float_t number_float;
  6962. /// default constructor (for null values)
  6963. json_value() = default;
  6964. /// constructor for booleans
  6965. json_value(boolean_t v) noexcept : boolean(v) {}
  6966. /// constructor for numbers (integer)
  6967. json_value(number_integer_t v) noexcept : number_integer(v) {}
  6968. /// constructor for numbers (unsigned)
  6969. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  6970. /// constructor for numbers (floating-point)
  6971. json_value(number_float_t v) noexcept : number_float(v) {}
  6972. /// constructor for empty values of a given type
  6973. json_value(value_t t)
  6974. {
  6975. switch (t)
  6976. {
  6977. case value_t::object:
  6978. {
  6979. object = create<object_t>();
  6980. break;
  6981. }
  6982. case value_t::array:
  6983. {
  6984. array = create<array_t>();
  6985. break;
  6986. }
  6987. case value_t::string:
  6988. {
  6989. string = create<string_t>("");
  6990. break;
  6991. }
  6992. case value_t::boolean:
  6993. {
  6994. boolean = boolean_t(false);
  6995. break;
  6996. }
  6997. case value_t::number_integer:
  6998. {
  6999. number_integer = number_integer_t(0);
  7000. break;
  7001. }
  7002. case value_t::number_unsigned:
  7003. {
  7004. number_unsigned = number_unsigned_t(0);
  7005. break;
  7006. }
  7007. case value_t::number_float:
  7008. {
  7009. number_float = number_float_t(0.0);
  7010. break;
  7011. }
  7012. case value_t::null:
  7013. {
  7014. object = nullptr; // silence warning, see #821
  7015. break;
  7016. }
  7017. default:
  7018. {
  7019. object = nullptr; // silence warning, see #821
  7020. if (JSON_UNLIKELY(t == value_t::null))
  7021. {
  7022. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.0.1")); // LCOV_EXCL_LINE
  7023. }
  7024. break;
  7025. }
  7026. }
  7027. }
  7028. /// constructor for strings
  7029. json_value(const string_t& value)
  7030. {
  7031. string = create<string_t>(value);
  7032. }
  7033. /// constructor for rvalue strings
  7034. json_value(string_t&& value)
  7035. {
  7036. string = create<string_t>(std::move(value));
  7037. }
  7038. /// constructor for objects
  7039. json_value(const object_t& value)
  7040. {
  7041. object = create<object_t>(value);
  7042. }
  7043. /// constructor for rvalue objects
  7044. json_value(object_t&& value)
  7045. {
  7046. object = create<object_t>(std::move(value));
  7047. }
  7048. /// constructor for arrays
  7049. json_value(const array_t& value)
  7050. {
  7051. array = create<array_t>(value);
  7052. }
  7053. /// constructor for rvalue arrays
  7054. json_value(array_t&& value)
  7055. {
  7056. array = create<array_t>(std::move(value));
  7057. }
  7058. void destroy(value_t t)
  7059. {
  7060. switch (t)
  7061. {
  7062. case value_t::object:
  7063. {
  7064. AllocatorType<object_t> alloc;
  7065. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  7066. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  7067. break;
  7068. }
  7069. case value_t::array:
  7070. {
  7071. AllocatorType<array_t> alloc;
  7072. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  7073. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  7074. break;
  7075. }
  7076. case value_t::string:
  7077. {
  7078. AllocatorType<string_t> alloc;
  7079. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  7080. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  7081. break;
  7082. }
  7083. default:
  7084. {
  7085. break;
  7086. }
  7087. }
  7088. }
  7089. };
  7090. /*!
  7091. @brief checks the class invariants
  7092. This function asserts the class invariants. It needs to be called at the
  7093. end of every constructor to make sure that created objects respect the
  7094. invariant. Furthermore, it has to be called each time the type of a JSON
  7095. value is changed, because the invariant expresses a relationship between
  7096. @a m_type and @a m_value.
  7097. */
  7098. void assert_invariant() const
  7099. {
  7100. assert(m_type != value_t::object or m_value.object != nullptr);
  7101. assert(m_type != value_t::array or m_value.array != nullptr);
  7102. assert(m_type != value_t::string or m_value.string != nullptr);
  7103. }
  7104. public:
  7105. //////////////////////////
  7106. // JSON parser callback //
  7107. //////////////////////////
  7108. /*!
  7109. @brief parser event types
  7110. The parser callback distinguishes the following events:
  7111. - `object_start`: the parser read `{` and started to process a JSON object
  7112. - `key`: the parser read a key of a value in an object
  7113. - `object_end`: the parser read `}` and finished processing a JSON object
  7114. - `array_start`: the parser read `[` and started to process a JSON array
  7115. - `array_end`: the parser read `]` and finished processing a JSON array
  7116. - `value`: the parser finished reading a JSON value
  7117. @image html callback_events.png "Example when certain parse events are triggered"
  7118. @sa @ref parser_callback_t for more information and examples
  7119. */
  7120. using parse_event_t = typename parser::parse_event_t;
  7121. /*!
  7122. @brief per-element parser callback type
  7123. With a parser callback function, the result of parsing a JSON text can be
  7124. influenced. When passed to @ref parse, it is called on certain events
  7125. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  7126. depth @a depth and context JSON value @a parsed. The return value of the
  7127. callback function is a boolean indicating whether the element that emitted
  7128. the callback shall be kept or not.
  7129. We distinguish six scenarios (determined by the event type) in which the
  7130. callback function can be called. The following table describes the values
  7131. of the parameters @a depth, @a event, and @a parsed.
  7132. parameter @a event | description | parameter @a depth | parameter @a parsed
  7133. ------------------ | ----------- | ------------------ | -------------------
  7134. parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
  7135. parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
  7136. parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
  7137. parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
  7138. parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
  7139. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  7140. @image html callback_events.png "Example when certain parse events are triggered"
  7141. Discarding a value (i.e., returning `false`) has different effects
  7142. depending on the context in which function was called:
  7143. - Discarded values in structured types are skipped. That is, the parser
  7144. will behave as if the discarded value was never read.
  7145. - In case a value outside a structured type is skipped, it is replaced
  7146. with `null`. This case happens if the top-level element is skipped.
  7147. @param[in] depth the depth of the recursion during parsing
  7148. @param[in] event an event of type parse_event_t indicating the context in
  7149. the callback function has been called
  7150. @param[in,out] parsed the current intermediate parse result; note that
  7151. writing to this value has no effect for parse_event_t::key events
  7152. @return Whether the JSON value which called the function during parsing
  7153. should be kept (`true`) or not (`false`). In the latter case, it is either
  7154. skipped completely or replaced by an empty discarded object.
  7155. @sa @ref parse for examples
  7156. @since version 1.0.0
  7157. */
  7158. using parser_callback_t = typename parser::parser_callback_t;
  7159. //////////////////
  7160. // constructors //
  7161. //////////////////
  7162. /// @name constructors and destructors
  7163. /// Constructors of class @ref basic_json, copy/move constructor, copy
  7164. /// assignment, static functions creating objects, and the destructor.
  7165. /// @{
  7166. /*!
  7167. @brief create an empty value with a given type
  7168. Create an empty JSON value with a given type. The value will be default
  7169. initialized with an empty value which depends on the type:
  7170. Value type | initial value
  7171. ----------- | -------------
  7172. null | `null`
  7173. boolean | `false`
  7174. string | `""`
  7175. number | `0`
  7176. object | `{}`
  7177. array | `[]`
  7178. @param[in] v the type of the value to create
  7179. @complexity Constant.
  7180. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7181. changes to any JSON value.
  7182. @liveexample{The following code shows the constructor for different @ref
  7183. value_t values,basic_json__value_t}
  7184. @sa @ref clear() -- restores the postcondition of this constructor
  7185. @since version 1.0.0
  7186. */
  7187. basic_json(const value_t v)
  7188. : m_type(v), m_value(v)
  7189. {
  7190. assert_invariant();
  7191. }
  7192. /*!
  7193. @brief create a null object
  7194. Create a `null` JSON value. It either takes a null pointer as parameter
  7195. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  7196. The passed null pointer itself is not read -- it is only used to choose
  7197. the right constructor.
  7198. @complexity Constant.
  7199. @exceptionsafety No-throw guarantee: this constructor never throws
  7200. exceptions.
  7201. @liveexample{The following code shows the constructor with and without a
  7202. null pointer parameter.,basic_json__nullptr_t}
  7203. @since version 1.0.0
  7204. */
  7205. basic_json(std::nullptr_t = nullptr) noexcept
  7206. : basic_json(value_t::null)
  7207. {
  7208. assert_invariant();
  7209. }
  7210. /*!
  7211. @brief create a JSON value
  7212. This is a "catch all" constructor for all compatible JSON types; that is,
  7213. types for which a `to_json()` method exists. The constructor forwards the
  7214. parameter @a val to that method (to `json_serializer<U>::to_json` method
  7215. with `U = uncvref_t<CompatibleType>`, to be exact).
  7216. Template type @a CompatibleType includes, but is not limited to, the
  7217. following types:
  7218. - **arrays**: @ref array_t and all kinds of compatible containers such as
  7219. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  7220. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  7221. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  7222. which a @ref basic_json value can be constructed.
  7223. - **objects**: @ref object_t and all kinds of compatible associative
  7224. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  7225. and `std::unordered_multimap` with a `key_type` compatible to
  7226. @ref string_t and a `value_type` from which a @ref basic_json value can
  7227. be constructed.
  7228. - **strings**: @ref string_t, string literals, and all compatible string
  7229. containers can be used.
  7230. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  7231. @ref number_float_t, and all convertible number types such as `int`,
  7232. `size_t`, `int64_t`, `float` or `double` can be used.
  7233. - **boolean**: @ref boolean_t / `bool` can be used.
  7234. See the examples below.
  7235. @tparam CompatibleType a type such that:
  7236. - @a CompatibleType is not derived from `std::istream`,
  7237. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  7238. constructors),
  7239. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  7240. @ref json_pointer, @ref iterator, etc ...)
  7241. - @ref @ref json_serializer<U> has a
  7242. `to_json(basic_json_t&, CompatibleType&&)` method
  7243. @tparam U = `uncvref_t<CompatibleType>`
  7244. @param[in] val the value to be forwarded to the respective constructor
  7245. @complexity Usually linear in the size of the passed @a val, also
  7246. depending on the implementation of the called `to_json()`
  7247. method.
  7248. @exceptionsafety Depends on the called constructor. For types directly
  7249. supported by the library (i.e., all types for which no `to_json()` function
  7250. was provided), strong guarantee holds: if an exception is thrown, there are
  7251. no changes to any JSON value.
  7252. @liveexample{The following code shows the constructor with several
  7253. compatible types.,basic_json__CompatibleType}
  7254. @since version 2.1.0
  7255. */
  7256. template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
  7257. detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
  7258. not std::is_same<U, basic_json_t>::value and
  7259. not detail::is_basic_json_nested_type<
  7260. basic_json_t, U>::value and
  7261. detail::has_to_json<basic_json, U>::value,
  7262. int> = 0>
  7263. basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
  7264. std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
  7265. {
  7266. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  7267. assert_invariant();
  7268. }
  7269. /*!
  7270. @brief create a container (array or object) from an initializer list
  7271. Creates a JSON value of type array or object from the passed initializer
  7272. list @a init. In case @a type_deduction is `true` (default), the type of
  7273. the JSON value to be created is deducted from the initializer list @a init
  7274. according to the following rules:
  7275. 1. If the list is empty, an empty JSON object value `{}` is created.
  7276. 2. If the list consists of pairs whose first element is a string, a JSON
  7277. object value is created where the first elements of the pairs are
  7278. treated as keys and the second elements are as values.
  7279. 3. In all other cases, an array is created.
  7280. The rules aim to create the best fit between a C++ initializer list and
  7281. JSON values. The rationale is as follows:
  7282. 1. The empty initializer list is written as `{}` which is exactly an empty
  7283. JSON object.
  7284. 2. C++ has no way of describing mapped types other than to list a list of
  7285. pairs. As JSON requires that keys must be of type string, rule 2 is the
  7286. weakest constraint one can pose on initializer lists to interpret them
  7287. as an object.
  7288. 3. In all other cases, the initializer list could not be interpreted as
  7289. JSON object type, so interpreting it as JSON array type is safe.
  7290. With the rules described above, the following JSON values cannot be
  7291. expressed by an initializer list:
  7292. - the empty array (`[]`): use @ref array(initializer_list_t)
  7293. with an empty initializer list in this case
  7294. - arrays whose elements satisfy rule 2: use @ref
  7295. array(initializer_list_t) with the same initializer list
  7296. in this case
  7297. @note When used without parentheses around an empty initializer list, @ref
  7298. basic_json() is called instead of this function, yielding the JSON null
  7299. value.
  7300. @param[in] init initializer list with JSON values
  7301. @param[in] type_deduction internal parameter; when set to `true`, the type
  7302. of the JSON value is deducted from the initializer list @a init; when set
  7303. to `false`, the type provided via @a manual_type is forced. This mode is
  7304. used by the functions @ref array(initializer_list_t) and
  7305. @ref object(initializer_list_t).
  7306. @param[in] manual_type internal parameter; when @a type_deduction is set
  7307. to `false`, the created JSON value will use the provided type (only @ref
  7308. value_t::array and @ref value_t::object are valid); when @a type_deduction
  7309. is set to `true`, this parameter has no effect
  7310. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  7311. `value_t::object`, but @a init contains an element which is not a pair
  7312. whose first element is a string. In this case, the constructor could not
  7313. create an object. If @a type_deduction would have be `true`, an array
  7314. would have been created. See @ref object(initializer_list_t)
  7315. for an example.
  7316. @complexity Linear in the size of the initializer list @a init.
  7317. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7318. changes to any JSON value.
  7319. @liveexample{The example below shows how JSON values are created from
  7320. initializer lists.,basic_json__list_init_t}
  7321. @sa @ref array(initializer_list_t) -- create a JSON array
  7322. value from an initializer list
  7323. @sa @ref object(initializer_list_t) -- create a JSON object
  7324. value from an initializer list
  7325. @since version 1.0.0
  7326. */
  7327. basic_json(initializer_list_t init,
  7328. bool type_deduction = true,
  7329. value_t manual_type = value_t::array)
  7330. {
  7331. // check if each element is an array with two elements whose first
  7332. // element is a string
  7333. bool is_an_object = std::all_of(init.begin(), init.end(),
  7334. [](const detail::json_ref<basic_json>& element_ref)
  7335. {
  7336. return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
  7337. });
  7338. // adjust type if type deduction is not wanted
  7339. if (not type_deduction)
  7340. {
  7341. // if array is wanted, do not create an object though possible
  7342. if (manual_type == value_t::array)
  7343. {
  7344. is_an_object = false;
  7345. }
  7346. // if object is wanted but impossible, throw an exception
  7347. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  7348. {
  7349. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  7350. }
  7351. }
  7352. if (is_an_object)
  7353. {
  7354. // the initializer list is a list of pairs -> create object
  7355. m_type = value_t::object;
  7356. m_value = value_t::object;
  7357. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  7358. {
  7359. auto element = element_ref.moved_or_copied();
  7360. m_value.object->emplace(
  7361. std::move(*((*element.m_value.array)[0].m_value.string)),
  7362. std::move((*element.m_value.array)[1]));
  7363. });
  7364. }
  7365. else
  7366. {
  7367. // the initializer list describes an array -> create array
  7368. m_type = value_t::array;
  7369. m_value.array = create<array_t>(init.begin(), init.end());
  7370. }
  7371. assert_invariant();
  7372. }
  7373. /*!
  7374. @brief explicitly create an array from an initializer list
  7375. Creates a JSON array value from a given initializer list. That is, given a
  7376. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  7377. initializer list is empty, the empty array `[]` is created.
  7378. @note This function is only needed to express two edge cases that cannot
  7379. be realized with the initializer list constructor (@ref
  7380. basic_json(initializer_list_t, bool, value_t)). These cases
  7381. are:
  7382. 1. creating an array whose elements are all pairs whose first element is a
  7383. string -- in this case, the initializer list constructor would create an
  7384. object, taking the first elements as keys
  7385. 2. creating an empty array -- passing the empty initializer list to the
  7386. initializer list constructor yields an empty object
  7387. @param[in] init initializer list with JSON values to create an array from
  7388. (optional)
  7389. @return JSON array value
  7390. @complexity Linear in the size of @a init.
  7391. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7392. changes to any JSON value.
  7393. @liveexample{The following code shows an example for the `array`
  7394. function.,array}
  7395. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  7396. create a JSON value from an initializer list
  7397. @sa @ref object(initializer_list_t) -- create a JSON object
  7398. value from an initializer list
  7399. @since version 1.0.0
  7400. */
  7401. static basic_json array(initializer_list_t init = {})
  7402. {
  7403. return basic_json(init, false, value_t::array);
  7404. }
  7405. /*!
  7406. @brief explicitly create an object from an initializer list
  7407. Creates a JSON object value from a given initializer list. The initializer
  7408. lists elements must be pairs, and their first elements must be strings. If
  7409. the initializer list is empty, the empty object `{}` is created.
  7410. @note This function is only added for symmetry reasons. In contrast to the
  7411. related function @ref array(initializer_list_t), there are
  7412. no cases which can only be expressed by this function. That is, any
  7413. initializer list @a init can also be passed to the initializer list
  7414. constructor @ref basic_json(initializer_list_t, bool, value_t).
  7415. @param[in] init initializer list to create an object from (optional)
  7416. @return JSON object value
  7417. @throw type_error.301 if @a init is not a list of pairs whose first
  7418. elements are strings. In this case, no object can be created. When such a
  7419. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  7420. an array would have been created from the passed initializer list @a init.
  7421. See example below.
  7422. @complexity Linear in the size of @a init.
  7423. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7424. changes to any JSON value.
  7425. @liveexample{The following code shows an example for the `object`
  7426. function.,object}
  7427. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  7428. create a JSON value from an initializer list
  7429. @sa @ref array(initializer_list_t) -- create a JSON array
  7430. value from an initializer list
  7431. @since version 1.0.0
  7432. */
  7433. static basic_json object(initializer_list_t init = {})
  7434. {
  7435. return basic_json(init, false, value_t::object);
  7436. }
  7437. /*!
  7438. @brief construct an array with count copies of given value
  7439. Constructs a JSON array value by creating @a cnt copies of a passed value.
  7440. In case @a cnt is `0`, an empty array is created.
  7441. @param[in] cnt the number of JSON copies of @a val to create
  7442. @param[in] val the JSON value to copy
  7443. @post `std::distance(begin(),end()) == cnt` holds.
  7444. @complexity Linear in @a cnt.
  7445. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7446. changes to any JSON value.
  7447. @liveexample{The following code shows examples for the @ref
  7448. basic_json(size_type\, const basic_json&)
  7449. constructor.,basic_json__size_type_basic_json}
  7450. @since version 1.0.0
  7451. */
  7452. basic_json(size_type cnt, const basic_json& val)
  7453. : m_type(value_t::array)
  7454. {
  7455. m_value.array = create<array_t>(cnt, val);
  7456. assert_invariant();
  7457. }
  7458. /*!
  7459. @brief construct a JSON container given an iterator range
  7460. Constructs the JSON value with the contents of the range `[first, last)`.
  7461. The semantics depends on the different types a JSON value can have:
  7462. - In case of a null type, invalid_iterator.206 is thrown.
  7463. - In case of other primitive types (number, boolean, or string), @a first
  7464. must be `begin()` and @a last must be `end()`. In this case, the value is
  7465. copied. Otherwise, invalid_iterator.204 is thrown.
  7466. - In case of structured types (array, object), the constructor behaves as
  7467. similar versions for `std::vector` or `std::map`; that is, a JSON array
  7468. or object is constructed from the values in the range.
  7469. @tparam InputIT an input iterator type (@ref iterator or @ref
  7470. const_iterator)
  7471. @param[in] first begin of the range to copy from (included)
  7472. @param[in] last end of the range to copy from (excluded)
  7473. @pre Iterators @a first and @a last must be initialized. **This
  7474. precondition is enforced with an assertion (see warning).** If
  7475. assertions are switched off, a violation of this precondition yields
  7476. undefined behavior.
  7477. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  7478. checked efficiently. Only certain edge cases are detected; see the
  7479. description of the exceptions below. A violation of this precondition
  7480. yields undefined behavior.
  7481. @warning A precondition is enforced with a runtime assertion that will
  7482. result in calling `std::abort` if this precondition is not met.
  7483. Assertions can be disabled by defining `NDEBUG` at compile time.
  7484. See http://en.cppreference.com/w/cpp/error/assert for more
  7485. information.
  7486. @throw invalid_iterator.201 if iterators @a first and @a last are not
  7487. compatible (i.e., do not belong to the same JSON value). In this case,
  7488. the range `[first, last)` is undefined.
  7489. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  7490. primitive type (number, boolean, or string), but @a first does not point
  7491. to the first element any more. In this case, the range `[first, last)` is
  7492. undefined. See example code below.
  7493. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  7494. null value. In this case, the range `[first, last)` is undefined.
  7495. @complexity Linear in distance between @a first and @a last.
  7496. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7497. changes to any JSON value.
  7498. @liveexample{The example below shows several ways to create JSON values by
  7499. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  7500. @since version 1.0.0
  7501. */
  7502. template<class InputIT, typename std::enable_if<
  7503. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  7504. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  7505. basic_json(InputIT first, InputIT last)
  7506. {
  7507. assert(first.m_object != nullptr);
  7508. assert(last.m_object != nullptr);
  7509. // make sure iterator fits the current value
  7510. if (JSON_UNLIKELY(first.m_object != last.m_object))
  7511. {
  7512. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  7513. }
  7514. // copy type from first iterator
  7515. m_type = first.m_object->m_type;
  7516. // check if iterator range is complete for primitive values
  7517. switch (m_type)
  7518. {
  7519. case value_t::boolean:
  7520. case value_t::number_float:
  7521. case value_t::number_integer:
  7522. case value_t::number_unsigned:
  7523. case value_t::string:
  7524. {
  7525. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  7526. or not last.m_it.primitive_iterator.is_end()))
  7527. {
  7528. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  7529. }
  7530. break;
  7531. }
  7532. default:
  7533. break;
  7534. }
  7535. switch (m_type)
  7536. {
  7537. case value_t::number_integer:
  7538. {
  7539. m_value.number_integer = first.m_object->m_value.number_integer;
  7540. break;
  7541. }
  7542. case value_t::number_unsigned:
  7543. {
  7544. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  7545. break;
  7546. }
  7547. case value_t::number_float:
  7548. {
  7549. m_value.number_float = first.m_object->m_value.number_float;
  7550. break;
  7551. }
  7552. case value_t::boolean:
  7553. {
  7554. m_value.boolean = first.m_object->m_value.boolean;
  7555. break;
  7556. }
  7557. case value_t::string:
  7558. {
  7559. m_value = *first.m_object->m_value.string;
  7560. break;
  7561. }
  7562. case value_t::object:
  7563. {
  7564. m_value.object = create<object_t>(first.m_it.object_iterator,
  7565. last.m_it.object_iterator);
  7566. break;
  7567. }
  7568. case value_t::array:
  7569. {
  7570. m_value.array = create<array_t>(first.m_it.array_iterator,
  7571. last.m_it.array_iterator);
  7572. break;
  7573. }
  7574. default:
  7575. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  7576. std::string(first.m_object->type_name())));
  7577. }
  7578. assert_invariant();
  7579. }
  7580. ///////////////////////////////////////
  7581. // other constructors and destructor //
  7582. ///////////////////////////////////////
  7583. /// @private
  7584. basic_json(const detail::json_ref<basic_json>& ref)
  7585. : basic_json(ref.moved_or_copied())
  7586. {}
  7587. /*!
  7588. @brief copy constructor
  7589. Creates a copy of a given JSON value.
  7590. @param[in] other the JSON value to copy
  7591. @post `*this == other`
  7592. @complexity Linear in the size of @a other.
  7593. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7594. changes to any JSON value.
  7595. @requirement This function helps `basic_json` satisfying the
  7596. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7597. requirements:
  7598. - The complexity is linear.
  7599. - As postcondition, it holds: `other == basic_json(other)`.
  7600. @liveexample{The following code shows an example for the copy
  7601. constructor.,basic_json__basic_json}
  7602. @since version 1.0.0
  7603. */
  7604. basic_json(const basic_json& other)
  7605. : m_type(other.m_type)
  7606. {
  7607. // check of passed value is valid
  7608. other.assert_invariant();
  7609. switch (m_type)
  7610. {
  7611. case value_t::object:
  7612. {
  7613. m_value = *other.m_value.object;
  7614. break;
  7615. }
  7616. case value_t::array:
  7617. {
  7618. m_value = *other.m_value.array;
  7619. break;
  7620. }
  7621. case value_t::string:
  7622. {
  7623. m_value = *other.m_value.string;
  7624. break;
  7625. }
  7626. case value_t::boolean:
  7627. {
  7628. m_value = other.m_value.boolean;
  7629. break;
  7630. }
  7631. case value_t::number_integer:
  7632. {
  7633. m_value = other.m_value.number_integer;
  7634. break;
  7635. }
  7636. case value_t::number_unsigned:
  7637. {
  7638. m_value = other.m_value.number_unsigned;
  7639. break;
  7640. }
  7641. case value_t::number_float:
  7642. {
  7643. m_value = other.m_value.number_float;
  7644. break;
  7645. }
  7646. default:
  7647. break;
  7648. }
  7649. assert_invariant();
  7650. }
  7651. /*!
  7652. @brief move constructor
  7653. Move constructor. Constructs a JSON value with the contents of the given
  7654. value @a other using move semantics. It "steals" the resources from @a
  7655. other and leaves it as JSON null value.
  7656. @param[in,out] other value to move to this object
  7657. @post `*this` has the same value as @a other before the call.
  7658. @post @a other is a JSON null value.
  7659. @complexity Constant.
  7660. @exceptionsafety No-throw guarantee: this constructor never throws
  7661. exceptions.
  7662. @requirement This function helps `basic_json` satisfying the
  7663. [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
  7664. requirements.
  7665. @liveexample{The code below shows the move constructor explicitly called
  7666. via std::move.,basic_json__moveconstructor}
  7667. @since version 1.0.0
  7668. */
  7669. basic_json(basic_json&& other) noexcept
  7670. : m_type(std::move(other.m_type)),
  7671. m_value(std::move(other.m_value))
  7672. {
  7673. // check that passed value is valid
  7674. other.assert_invariant();
  7675. // invalidate payload
  7676. other.m_type = value_t::null;
  7677. other.m_value = {};
  7678. assert_invariant();
  7679. }
  7680. /*!
  7681. @brief copy assignment
  7682. Copy assignment operator. Copies a JSON value via the "copy and swap"
  7683. strategy: It is expressed in terms of the copy constructor, destructor,
  7684. and the `swap()` member function.
  7685. @param[in] other value to copy from
  7686. @complexity Linear.
  7687. @requirement This function helps `basic_json` satisfying the
  7688. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7689. requirements:
  7690. - The complexity is linear.
  7691. @liveexample{The code below shows and example for the copy assignment. It
  7692. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  7693. copy of `a` (which is the null value after the swap) is
  7694. destroyed.,basic_json__copyassignment}
  7695. @since version 1.0.0
  7696. */
  7697. reference& operator=(basic_json other) noexcept (
  7698. std::is_nothrow_move_constructible<value_t>::value and
  7699. std::is_nothrow_move_assignable<value_t>::value and
  7700. std::is_nothrow_move_constructible<json_value>::value and
  7701. std::is_nothrow_move_assignable<json_value>::value
  7702. )
  7703. {
  7704. // check that passed value is valid
  7705. other.assert_invariant();
  7706. using std::swap;
  7707. swap(m_type, other.m_type);
  7708. swap(m_value, other.m_value);
  7709. assert_invariant();
  7710. return *this;
  7711. }
  7712. /*!
  7713. @brief destructor
  7714. Destroys the JSON value and frees all allocated memory.
  7715. @complexity Linear.
  7716. @requirement This function helps `basic_json` satisfying the
  7717. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7718. requirements:
  7719. - The complexity is linear.
  7720. - All stored elements are destroyed and all memory is freed.
  7721. @since version 1.0.0
  7722. */
  7723. ~basic_json()
  7724. {
  7725. assert_invariant();
  7726. m_value.destroy(m_type);
  7727. }
  7728. /// @}
  7729. public:
  7730. ///////////////////////
  7731. // object inspection //
  7732. ///////////////////////
  7733. /// @name object inspection
  7734. /// Functions to inspect the type of a JSON value.
  7735. /// @{
  7736. /*!
  7737. @brief serialization
  7738. Serialization function for JSON values. The function tries to mimic
  7739. Python's `json.dumps()` function, and currently supports its @a indent
  7740. and @a ensure_ascii parameters.
  7741. @param[in] indent If indent is nonnegative, then array elements and object
  7742. members will be pretty-printed with that indent level. An indent level of
  7743. `0` will only insert newlines. `-1` (the default) selects the most compact
  7744. representation.
  7745. @param[in] indent_char The character to use for indentation if @a indent is
  7746. greater than `0`. The default is ` ` (space).
  7747. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  7748. in the output are escaped with `\uXXXX` sequences, and the result consists
  7749. of ASCII characters only.
  7750. @return string containing the serialization of the JSON value
  7751. @throw type_error.316 if a string stored inside the JSON value is not
  7752. UTF-8 encoded
  7753. @complexity Linear.
  7754. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7755. changes in the JSON value.
  7756. @liveexample{The following example shows the effect of different @a indent\,
  7757. @a indent_char\, and @a ensure_ascii parameters to the result of the
  7758. serialization.,dump}
  7759. @see https://docs.python.org/2/library/json.html#json.dump
  7760. @since version 1.0.0; indentation character @a indent_char, option
  7761. @a ensure_ascii and exceptions added in version 3.0.0
  7762. */
  7763. string_t dump(const int indent = -1, const char indent_char = ' ',
  7764. const bool ensure_ascii = false) const
  7765. {
  7766. string_t result;
  7767. serializer s(detail::output_adapter<char>(result), indent_char);
  7768. if (indent >= 0)
  7769. {
  7770. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  7771. }
  7772. else
  7773. {
  7774. s.dump(*this, false, ensure_ascii, 0);
  7775. }
  7776. return result;
  7777. }
  7778. /*!
  7779. @brief return the type of the JSON value (explicit)
  7780. Return the type of the JSON value as a value from the @ref value_t
  7781. enumeration.
  7782. @return the type of the JSON value
  7783. Value type | return value
  7784. ------------------------- | -------------------------
  7785. null | value_t::null
  7786. boolean | value_t::boolean
  7787. string | value_t::string
  7788. number (integer) | value_t::number_integer
  7789. number (unsigned integer) | value_t::number_unsigned
  7790. number (floating-point) | value_t::number_float
  7791. object | value_t::object
  7792. array | value_t::array
  7793. discarded | value_t::discarded
  7794. @complexity Constant.
  7795. @exceptionsafety No-throw guarantee: this member function never throws
  7796. exceptions.
  7797. @liveexample{The following code exemplifies `type()` for all JSON
  7798. types.,type}
  7799. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  7800. @sa @ref type_name() -- return the type as string
  7801. @since version 1.0.0
  7802. */
  7803. constexpr value_t type() const noexcept
  7804. {
  7805. return m_type;
  7806. }
  7807. /*!
  7808. @brief return whether type is primitive
  7809. This function returns true if and only if the JSON type is primitive
  7810. (string, number, boolean, or null).
  7811. @return `true` if type is primitive (string, number, boolean, or null),
  7812. `false` otherwise.
  7813. @complexity Constant.
  7814. @exceptionsafety No-throw guarantee: this member function never throws
  7815. exceptions.
  7816. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  7817. types.,is_primitive}
  7818. @sa @ref is_structured() -- returns whether JSON value is structured
  7819. @sa @ref is_null() -- returns whether JSON value is `null`
  7820. @sa @ref is_string() -- returns whether JSON value is a string
  7821. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  7822. @sa @ref is_number() -- returns whether JSON value is a number
  7823. @since version 1.0.0
  7824. */
  7825. constexpr bool is_primitive() const noexcept
  7826. {
  7827. return is_null() or is_string() or is_boolean() or is_number();
  7828. }
  7829. /*!
  7830. @brief return whether type is structured
  7831. This function returns true if and only if the JSON type is structured
  7832. (array or object).
  7833. @return `true` if type is structured (array or object), `false` otherwise.
  7834. @complexity Constant.
  7835. @exceptionsafety No-throw guarantee: this member function never throws
  7836. exceptions.
  7837. @liveexample{The following code exemplifies `is_structured()` for all JSON
  7838. types.,is_structured}
  7839. @sa @ref is_primitive() -- returns whether value is primitive
  7840. @sa @ref is_array() -- returns whether value is an array
  7841. @sa @ref is_object() -- returns whether value is an object
  7842. @since version 1.0.0
  7843. */
  7844. constexpr bool is_structured() const noexcept
  7845. {
  7846. return is_array() or is_object();
  7847. }
  7848. /*!
  7849. @brief return whether value is null
  7850. This function returns true if and only if the JSON value is null.
  7851. @return `true` if type is null, `false` otherwise.
  7852. @complexity Constant.
  7853. @exceptionsafety No-throw guarantee: this member function never throws
  7854. exceptions.
  7855. @liveexample{The following code exemplifies `is_null()` for all JSON
  7856. types.,is_null}
  7857. @since version 1.0.0
  7858. */
  7859. constexpr bool is_null() const noexcept
  7860. {
  7861. return (m_type == value_t::null);
  7862. }
  7863. /*!
  7864. @brief return whether value is a boolean
  7865. This function returns true if and only if the JSON value is a boolean.
  7866. @return `true` if type is boolean, `false` otherwise.
  7867. @complexity Constant.
  7868. @exceptionsafety No-throw guarantee: this member function never throws
  7869. exceptions.
  7870. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  7871. types.,is_boolean}
  7872. @since version 1.0.0
  7873. */
  7874. constexpr bool is_boolean() const noexcept
  7875. {
  7876. return (m_type == value_t::boolean);
  7877. }
  7878. /*!
  7879. @brief return whether value is a number
  7880. This function returns true if and only if the JSON value is a number. This
  7881. includes both integer (signed and unsigned) and floating-point values.
  7882. @return `true` if type is number (regardless whether integer, unsigned
  7883. integer or floating-type), `false` otherwise.
  7884. @complexity Constant.
  7885. @exceptionsafety No-throw guarantee: this member function never throws
  7886. exceptions.
  7887. @liveexample{The following code exemplifies `is_number()` for all JSON
  7888. types.,is_number}
  7889. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  7890. integer number
  7891. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7892. number
  7893. @sa @ref is_number_float() -- check if value is a floating-point number
  7894. @since version 1.0.0
  7895. */
  7896. constexpr bool is_number() const noexcept
  7897. {
  7898. return is_number_integer() or is_number_float();
  7899. }
  7900. /*!
  7901. @brief return whether value is an integer number
  7902. This function returns true if and only if the JSON value is a signed or
  7903. unsigned integer number. This excludes floating-point values.
  7904. @return `true` if type is an integer or unsigned integer number, `false`
  7905. otherwise.
  7906. @complexity Constant.
  7907. @exceptionsafety No-throw guarantee: this member function never throws
  7908. exceptions.
  7909. @liveexample{The following code exemplifies `is_number_integer()` for all
  7910. JSON types.,is_number_integer}
  7911. @sa @ref is_number() -- check if value is a number
  7912. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7913. number
  7914. @sa @ref is_number_float() -- check if value is a floating-point number
  7915. @since version 1.0.0
  7916. */
  7917. constexpr bool is_number_integer() const noexcept
  7918. {
  7919. return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
  7920. }
  7921. /*!
  7922. @brief return whether value is an unsigned integer number
  7923. This function returns true if and only if the JSON value is an unsigned
  7924. integer number. This excludes floating-point and signed integer values.
  7925. @return `true` if type is an unsigned integer number, `false` otherwise.
  7926. @complexity Constant.
  7927. @exceptionsafety No-throw guarantee: this member function never throws
  7928. exceptions.
  7929. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  7930. JSON types.,is_number_unsigned}
  7931. @sa @ref is_number() -- check if value is a number
  7932. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  7933. integer number
  7934. @sa @ref is_number_float() -- check if value is a floating-point number
  7935. @since version 2.0.0
  7936. */
  7937. constexpr bool is_number_unsigned() const noexcept
  7938. {
  7939. return (m_type == value_t::number_unsigned);
  7940. }
  7941. /*!
  7942. @brief return whether value is a floating-point number
  7943. This function returns true if and only if the JSON value is a
  7944. floating-point number. This excludes signed and unsigned integer values.
  7945. @return `true` if type is a floating-point number, `false` otherwise.
  7946. @complexity Constant.
  7947. @exceptionsafety No-throw guarantee: this member function never throws
  7948. exceptions.
  7949. @liveexample{The following code exemplifies `is_number_float()` for all
  7950. JSON types.,is_number_float}
  7951. @sa @ref is_number() -- check if value is number
  7952. @sa @ref is_number_integer() -- check if value is an integer number
  7953. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7954. number
  7955. @since version 1.0.0
  7956. */
  7957. constexpr bool is_number_float() const noexcept
  7958. {
  7959. return (m_type == value_t::number_float);
  7960. }
  7961. /*!
  7962. @brief return whether value is an object
  7963. This function returns true if and only if the JSON value is an object.
  7964. @return `true` if type is object, `false` otherwise.
  7965. @complexity Constant.
  7966. @exceptionsafety No-throw guarantee: this member function never throws
  7967. exceptions.
  7968. @liveexample{The following code exemplifies `is_object()` for all JSON
  7969. types.,is_object}
  7970. @since version 1.0.0
  7971. */
  7972. constexpr bool is_object() const noexcept
  7973. {
  7974. return (m_type == value_t::object);
  7975. }
  7976. /*!
  7977. @brief return whether value is an array
  7978. This function returns true if and only if the JSON value is an array.
  7979. @return `true` if type is array, `false` otherwise.
  7980. @complexity Constant.
  7981. @exceptionsafety No-throw guarantee: this member function never throws
  7982. exceptions.
  7983. @liveexample{The following code exemplifies `is_array()` for all JSON
  7984. types.,is_array}
  7985. @since version 1.0.0
  7986. */
  7987. constexpr bool is_array() const noexcept
  7988. {
  7989. return (m_type == value_t::array);
  7990. }
  7991. /*!
  7992. @brief return whether value is a string
  7993. This function returns true if and only if the JSON value is a string.
  7994. @return `true` if type is string, `false` otherwise.
  7995. @complexity Constant.
  7996. @exceptionsafety No-throw guarantee: this member function never throws
  7997. exceptions.
  7998. @liveexample{The following code exemplifies `is_string()` for all JSON
  7999. types.,is_string}
  8000. @since version 1.0.0
  8001. */
  8002. constexpr bool is_string() const noexcept
  8003. {
  8004. return (m_type == value_t::string);
  8005. }
  8006. /*!
  8007. @brief return whether value is discarded
  8008. This function returns true if and only if the JSON value was discarded
  8009. during parsing with a callback function (see @ref parser_callback_t).
  8010. @note This function will always be `false` for JSON values after parsing.
  8011. That is, discarded values can only occur during parsing, but will be
  8012. removed when inside a structured value or replaced by null in other cases.
  8013. @return `true` if type is discarded, `false` otherwise.
  8014. @complexity Constant.
  8015. @exceptionsafety No-throw guarantee: this member function never throws
  8016. exceptions.
  8017. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  8018. types.,is_discarded}
  8019. @since version 1.0.0
  8020. */
  8021. constexpr bool is_discarded() const noexcept
  8022. {
  8023. return (m_type == value_t::discarded);
  8024. }
  8025. /*!
  8026. @brief return the type of the JSON value (implicit)
  8027. Implicitly return the type of the JSON value as a value from the @ref
  8028. value_t enumeration.
  8029. @return the type of the JSON value
  8030. @complexity Constant.
  8031. @exceptionsafety No-throw guarantee: this member function never throws
  8032. exceptions.
  8033. @liveexample{The following code exemplifies the @ref value_t operator for
  8034. all JSON types.,operator__value_t}
  8035. @sa @ref type() -- return the type of the JSON value (explicit)
  8036. @sa @ref type_name() -- return the type as string
  8037. @since version 1.0.0
  8038. */
  8039. constexpr operator value_t() const noexcept
  8040. {
  8041. return m_type;
  8042. }
  8043. /// @}
  8044. private:
  8045. //////////////////
  8046. // value access //
  8047. //////////////////
  8048. /// get a boolean (explicit)
  8049. boolean_t get_impl(boolean_t* /*unused*/) const
  8050. {
  8051. if (JSON_LIKELY(is_boolean()))
  8052. {
  8053. return m_value.boolean;
  8054. }
  8055. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  8056. }
  8057. /// get a pointer to the value (object)
  8058. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  8059. {
  8060. return is_object() ? m_value.object : nullptr;
  8061. }
  8062. /// get a pointer to the value (object)
  8063. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  8064. {
  8065. return is_object() ? m_value.object : nullptr;
  8066. }
  8067. /// get a pointer to the value (array)
  8068. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  8069. {
  8070. return is_array() ? m_value.array : nullptr;
  8071. }
  8072. /// get a pointer to the value (array)
  8073. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  8074. {
  8075. return is_array() ? m_value.array : nullptr;
  8076. }
  8077. /// get a pointer to the value (string)
  8078. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  8079. {
  8080. return is_string() ? m_value.string : nullptr;
  8081. }
  8082. /// get a pointer to the value (string)
  8083. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  8084. {
  8085. return is_string() ? m_value.string : nullptr;
  8086. }
  8087. /// get a pointer to the value (boolean)
  8088. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  8089. {
  8090. return is_boolean() ? &m_value.boolean : nullptr;
  8091. }
  8092. /// get a pointer to the value (boolean)
  8093. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  8094. {
  8095. return is_boolean() ? &m_value.boolean : nullptr;
  8096. }
  8097. /// get a pointer to the value (integer number)
  8098. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  8099. {
  8100. return is_number_integer() ? &m_value.number_integer : nullptr;
  8101. }
  8102. /// get a pointer to the value (integer number)
  8103. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  8104. {
  8105. return is_number_integer() ? &m_value.number_integer : nullptr;
  8106. }
  8107. /// get a pointer to the value (unsigned number)
  8108. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  8109. {
  8110. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  8111. }
  8112. /// get a pointer to the value (unsigned number)
  8113. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  8114. {
  8115. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  8116. }
  8117. /// get a pointer to the value (floating-point number)
  8118. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  8119. {
  8120. return is_number_float() ? &m_value.number_float : nullptr;
  8121. }
  8122. /// get a pointer to the value (floating-point number)
  8123. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  8124. {
  8125. return is_number_float() ? &m_value.number_float : nullptr;
  8126. }
  8127. /*!
  8128. @brief helper function to implement get_ref()
  8129. This function helps to implement get_ref() without code duplication for
  8130. const and non-const overloads
  8131. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  8132. @throw type_error.303 if ReferenceType does not match underlying value
  8133. type of the current JSON
  8134. */
  8135. template<typename ReferenceType, typename ThisType>
  8136. static ReferenceType get_ref_impl(ThisType& obj)
  8137. {
  8138. // delegate the call to get_ptr<>()
  8139. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  8140. if (JSON_LIKELY(ptr != nullptr))
  8141. {
  8142. return *ptr;
  8143. }
  8144. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  8145. }
  8146. public:
  8147. /// @name value access
  8148. /// Direct access to the stored value of a JSON value.
  8149. /// @{
  8150. /*!
  8151. @brief get special-case overload
  8152. This overloads avoids a lot of template boilerplate, it can be seen as the
  8153. identity method
  8154. @tparam BasicJsonType == @ref basic_json
  8155. @return a copy of *this
  8156. @complexity Constant.
  8157. @since version 2.1.0
  8158. */
  8159. template<typename BasicJsonType, detail::enable_if_t<
  8160. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  8161. int> = 0>
  8162. basic_json get() const
  8163. {
  8164. return *this;
  8165. }
  8166. /*!
  8167. @brief get a value (explicit)
  8168. Explicit type conversion between the JSON value and a compatible value
  8169. which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  8170. and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  8171. The value is converted by calling the @ref json_serializer<ValueType>
  8172. `from_json()` method.
  8173. The function is equivalent to executing
  8174. @code {.cpp}
  8175. ValueType ret;
  8176. JSONSerializer<ValueType>::from_json(*this, ret);
  8177. return ret;
  8178. @endcode
  8179. This overloads is chosen if:
  8180. - @a ValueType is not @ref basic_json,
  8181. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  8182. `void from_json(const basic_json&, ValueType&)`, and
  8183. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  8184. the form `ValueType from_json(const basic_json&)`
  8185. @tparam ValueTypeCV the provided value type
  8186. @tparam ValueType the returned value type
  8187. @return copy of the JSON value, converted to @a ValueType
  8188. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  8189. @liveexample{The example below shows several conversions from JSON values
  8190. to other types. There a few things to note: (1) Floating-point numbers can
  8191. be converted to integers\, (2) A JSON array can be converted to a standard
  8192. `std::vector<short>`\, (3) A JSON object can be converted to C++
  8193. associative containers such as `std::unordered_map<std::string\,
  8194. json>`.,get__ValueType_const}
  8195. @since version 2.1.0
  8196. */
  8197. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  8198. detail::enable_if_t <
  8199. not std::is_same<basic_json_t, ValueType>::value and
  8200. detail::has_from_json<basic_json_t, ValueType>::value and
  8201. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  8202. int> = 0>
  8203. ValueType get() const noexcept(noexcept(
  8204. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  8205. {
  8206. // we cannot static_assert on ValueTypeCV being non-const, because
  8207. // there is support for get<const basic_json_t>(), which is why we
  8208. // still need the uncvref
  8209. static_assert(not std::is_reference<ValueTypeCV>::value,
  8210. "get() cannot be used with reference types, you might want to use get_ref()");
  8211. static_assert(std::is_default_constructible<ValueType>::value,
  8212. "types must be DefaultConstructible when used with get()");
  8213. ValueType ret;
  8214. JSONSerializer<ValueType>::from_json(*this, ret);
  8215. return ret;
  8216. }
  8217. /*!
  8218. @brief get a value (explicit); special case
  8219. Explicit type conversion between the JSON value and a compatible value
  8220. which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  8221. and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  8222. The value is converted by calling the @ref json_serializer<ValueType>
  8223. `from_json()` method.
  8224. The function is equivalent to executing
  8225. @code {.cpp}
  8226. return JSONSerializer<ValueTypeCV>::from_json(*this);
  8227. @endcode
  8228. This overloads is chosen if:
  8229. - @a ValueType is not @ref basic_json and
  8230. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  8231. `ValueType from_json(const basic_json&)`
  8232. @note If @ref json_serializer<ValueType> has both overloads of
  8233. `from_json()`, this one is chosen.
  8234. @tparam ValueTypeCV the provided value type
  8235. @tparam ValueType the returned value type
  8236. @return copy of the JSON value, converted to @a ValueType
  8237. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  8238. @since version 2.1.0
  8239. */
  8240. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  8241. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  8242. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  8243. int> = 0>
  8244. ValueType get() const noexcept(noexcept(
  8245. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  8246. {
  8247. static_assert(not std::is_reference<ValueTypeCV>::value,
  8248. "get() cannot be used with reference types, you might want to use get_ref()");
  8249. return JSONSerializer<ValueTypeCV>::from_json(*this);
  8250. }
  8251. /*!
  8252. @brief get a pointer value (explicit)
  8253. Explicit pointer access to the internally stored JSON value. No copies are
  8254. made.
  8255. @warning The pointer becomes invalid if the underlying JSON object
  8256. changes.
  8257. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  8258. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  8259. @ref number_unsigned_t, or @ref number_float_t.
  8260. @return pointer to the internally stored JSON value if the requested
  8261. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  8262. @complexity Constant.
  8263. @liveexample{The example below shows how pointers to internal values of a
  8264. JSON value can be requested. Note that no type conversions are made and a
  8265. `nullptr` is returned if the value and the requested pointer type does not
  8266. match.,get__PointerType}
  8267. @sa @ref get_ptr() for explicit pointer-member access
  8268. @since version 1.0.0
  8269. */
  8270. template<typename PointerType, typename std::enable_if<
  8271. std::is_pointer<PointerType>::value, int>::type = 0>
  8272. PointerType get() noexcept
  8273. {
  8274. // delegate the call to get_ptr
  8275. return get_ptr<PointerType>();
  8276. }
  8277. /*!
  8278. @brief get a pointer value (explicit)
  8279. @copydoc get()
  8280. */
  8281. template<typename PointerType, typename std::enable_if<
  8282. std::is_pointer<PointerType>::value, int>::type = 0>
  8283. constexpr const PointerType get() const noexcept
  8284. {
  8285. // delegate the call to get_ptr
  8286. return get_ptr<PointerType>();
  8287. }
  8288. /*!
  8289. @brief get a pointer value (implicit)
  8290. Implicit pointer access to the internally stored JSON value. No copies are
  8291. made.
  8292. @warning Writing data to the pointee of the result yields an undefined
  8293. state.
  8294. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  8295. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  8296. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  8297. assertion.
  8298. @return pointer to the internally stored JSON value if the requested
  8299. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  8300. @complexity Constant.
  8301. @liveexample{The example below shows how pointers to internal values of a
  8302. JSON value can be requested. Note that no type conversions are made and a
  8303. `nullptr` is returned if the value and the requested pointer type does not
  8304. match.,get_ptr}
  8305. @since version 1.0.0
  8306. */
  8307. template<typename PointerType, typename std::enable_if<
  8308. std::is_pointer<PointerType>::value, int>::type = 0>
  8309. PointerType get_ptr() noexcept
  8310. {
  8311. // get the type of the PointerType (remove pointer and const)
  8312. using pointee_t = typename std::remove_const<typename
  8313. std::remove_pointer<typename
  8314. std::remove_const<PointerType>::type>::type>::type;
  8315. // make sure the type matches the allowed types
  8316. static_assert(
  8317. std::is_same<object_t, pointee_t>::value
  8318. or std::is_same<array_t, pointee_t>::value
  8319. or std::is_same<string_t, pointee_t>::value
  8320. or std::is_same<boolean_t, pointee_t>::value
  8321. or std::is_same<number_integer_t, pointee_t>::value
  8322. or std::is_same<number_unsigned_t, pointee_t>::value
  8323. or std::is_same<number_float_t, pointee_t>::value
  8324. , "incompatible pointer type");
  8325. // delegate the call to get_impl_ptr<>()
  8326. return get_impl_ptr(static_cast<PointerType>(nullptr));
  8327. }
  8328. /*!
  8329. @brief get a pointer value (implicit)
  8330. @copydoc get_ptr()
  8331. */
  8332. template<typename PointerType, typename std::enable_if<
  8333. std::is_pointer<PointerType>::value and
  8334. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  8335. constexpr const PointerType get_ptr() const noexcept
  8336. {
  8337. // get the type of the PointerType (remove pointer and const)
  8338. using pointee_t = typename std::remove_const<typename
  8339. std::remove_pointer<typename
  8340. std::remove_const<PointerType>::type>::type>::type;
  8341. // make sure the type matches the allowed types
  8342. static_assert(
  8343. std::is_same<object_t, pointee_t>::value
  8344. or std::is_same<array_t, pointee_t>::value
  8345. or std::is_same<string_t, pointee_t>::value
  8346. or std::is_same<boolean_t, pointee_t>::value
  8347. or std::is_same<number_integer_t, pointee_t>::value
  8348. or std::is_same<number_unsigned_t, pointee_t>::value
  8349. or std::is_same<number_float_t, pointee_t>::value
  8350. , "incompatible pointer type");
  8351. // delegate the call to get_impl_ptr<>() const
  8352. return get_impl_ptr(static_cast<PointerType>(nullptr));
  8353. }
  8354. /*!
  8355. @brief get a reference value (implicit)
  8356. Implicit reference access to the internally stored JSON value. No copies
  8357. are made.
  8358. @warning Writing data to the referee of the result yields an undefined
  8359. state.
  8360. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  8361. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  8362. @ref number_float_t. Enforced by static assertion.
  8363. @return reference to the internally stored JSON value if the requested
  8364. reference type @a ReferenceType fits to the JSON value; throws
  8365. type_error.303 otherwise
  8366. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  8367. with the stored JSON value; see example below
  8368. @complexity Constant.
  8369. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  8370. @since version 1.1.0
  8371. */
  8372. template<typename ReferenceType, typename std::enable_if<
  8373. std::is_reference<ReferenceType>::value, int>::type = 0>
  8374. ReferenceType get_ref()
  8375. {
  8376. // delegate call to get_ref_impl
  8377. return get_ref_impl<ReferenceType>(*this);
  8378. }
  8379. /*!
  8380. @brief get a reference value (implicit)
  8381. @copydoc get_ref()
  8382. */
  8383. template<typename ReferenceType, typename std::enable_if<
  8384. std::is_reference<ReferenceType>::value and
  8385. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  8386. ReferenceType get_ref() const
  8387. {
  8388. // delegate call to get_ref_impl
  8389. return get_ref_impl<ReferenceType>(*this);
  8390. }
  8391. /*!
  8392. @brief get a value (implicit)
  8393. Implicit type conversion between the JSON value and a compatible value.
  8394. The call is realized by calling @ref get() const.
  8395. @tparam ValueType non-pointer type compatible to the JSON value, for
  8396. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  8397. `std::vector` types for JSON arrays. The character type of @ref string_t
  8398. as well as an initializer list of this type is excluded to avoid
  8399. ambiguities as these types implicitly convert to `std::string`.
  8400. @return copy of the JSON value, converted to type @a ValueType
  8401. @throw type_error.302 in case passed type @a ValueType is incompatible
  8402. to the JSON value type (e.g., the JSON value is of type boolean, but a
  8403. string is requested); see example below
  8404. @complexity Linear in the size of the JSON value.
  8405. @liveexample{The example below shows several conversions from JSON values
  8406. to other types. There a few things to note: (1) Floating-point numbers can
  8407. be converted to integers\, (2) A JSON array can be converted to a standard
  8408. `std::vector<short>`\, (3) A JSON object can be converted to C++
  8409. associative containers such as `std::unordered_map<std::string\,
  8410. json>`.,operator__ValueType}
  8411. @since version 1.0.0
  8412. */
  8413. template < typename ValueType, typename std::enable_if <
  8414. not std::is_pointer<ValueType>::value and
  8415. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  8416. not std::is_same<ValueType, typename string_t::value_type>::value
  8417. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  8418. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  8419. #endif
  8420. #if defined(JSON_HAS_CPP_17)
  8421. and not std::is_same<ValueType, typename std::string_view>::value
  8422. #endif
  8423. , int >::type = 0 >
  8424. operator ValueType() const
  8425. {
  8426. // delegate the call to get<>() const
  8427. return get<ValueType>();
  8428. }
  8429. /// @}
  8430. ////////////////////
  8431. // element access //
  8432. ////////////////////
  8433. /// @name element access
  8434. /// Access to the JSON value.
  8435. /// @{
  8436. /*!
  8437. @brief access specified array element with bounds checking
  8438. Returns a reference to the element at specified location @a idx, with
  8439. bounds checking.
  8440. @param[in] idx index of the element to access
  8441. @return reference to the element at index @a idx
  8442. @throw type_error.304 if the JSON value is not an array; in this case,
  8443. calling `at` with an index makes no sense. See example below.
  8444. @throw out_of_range.401 if the index @a idx is out of range of the array;
  8445. that is, `idx >= size()`. See example below.
  8446. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8447. changes in the JSON value.
  8448. @complexity Constant.
  8449. @since version 1.0.0
  8450. @liveexample{The example below shows how array elements can be read and
  8451. written using `at()`. It also demonstrates the different exceptions that
  8452. can be thrown.,at__size_type}
  8453. */
  8454. reference at(size_type idx)
  8455. {
  8456. // at only works for arrays
  8457. if (JSON_LIKELY(is_array()))
  8458. {
  8459. JSON_TRY
  8460. {
  8461. return m_value.array->at(idx);
  8462. }
  8463. JSON_CATCH (std::out_of_range&)
  8464. {
  8465. // create better exception explanation
  8466. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  8467. }
  8468. }
  8469. else
  8470. {
  8471. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8472. }
  8473. }
  8474. /*!
  8475. @brief access specified array element with bounds checking
  8476. Returns a const reference to the element at specified location @a idx,
  8477. with bounds checking.
  8478. @param[in] idx index of the element to access
  8479. @return const reference to the element at index @a idx
  8480. @throw type_error.304 if the JSON value is not an array; in this case,
  8481. calling `at` with an index makes no sense. See example below.
  8482. @throw out_of_range.401 if the index @a idx is out of range of the array;
  8483. that is, `idx >= size()`. See example below.
  8484. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8485. changes in the JSON value.
  8486. @complexity Constant.
  8487. @since version 1.0.0
  8488. @liveexample{The example below shows how array elements can be read using
  8489. `at()`. It also demonstrates the different exceptions that can be thrown.,
  8490. at__size_type_const}
  8491. */
  8492. const_reference at(size_type idx) const
  8493. {
  8494. // at only works for arrays
  8495. if (JSON_LIKELY(is_array()))
  8496. {
  8497. JSON_TRY
  8498. {
  8499. return m_value.array->at(idx);
  8500. }
  8501. JSON_CATCH (std::out_of_range&)
  8502. {
  8503. // create better exception explanation
  8504. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  8505. }
  8506. }
  8507. else
  8508. {
  8509. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8510. }
  8511. }
  8512. /*!
  8513. @brief access specified object element with bounds checking
  8514. Returns a reference to the element at with specified key @a key, with
  8515. bounds checking.
  8516. @param[in] key key of the element to access
  8517. @return reference to the element at key @a key
  8518. @throw type_error.304 if the JSON value is not an object; in this case,
  8519. calling `at` with a key makes no sense. See example below.
  8520. @throw out_of_range.403 if the key @a key is is not stored in the object;
  8521. that is, `find(key) == end()`. See example below.
  8522. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8523. changes in the JSON value.
  8524. @complexity Logarithmic in the size of the container.
  8525. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8526. access by reference
  8527. @sa @ref value() for access by value with a default value
  8528. @since version 1.0.0
  8529. @liveexample{The example below shows how object elements can be read and
  8530. written using `at()`. It also demonstrates the different exceptions that
  8531. can be thrown.,at__object_t_key_type}
  8532. */
  8533. reference at(const typename object_t::key_type& key)
  8534. {
  8535. // at only works for objects
  8536. if (JSON_LIKELY(is_object()))
  8537. {
  8538. JSON_TRY
  8539. {
  8540. return m_value.object->at(key);
  8541. }
  8542. JSON_CATCH (std::out_of_range&)
  8543. {
  8544. // create better exception explanation
  8545. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  8546. }
  8547. }
  8548. else
  8549. {
  8550. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8551. }
  8552. }
  8553. /*!
  8554. @brief access specified object element with bounds checking
  8555. Returns a const reference to the element at with specified key @a key,
  8556. with bounds checking.
  8557. @param[in] key key of the element to access
  8558. @return const reference to the element at key @a key
  8559. @throw type_error.304 if the JSON value is not an object; in this case,
  8560. calling `at` with a key makes no sense. See example below.
  8561. @throw out_of_range.403 if the key @a key is is not stored in the object;
  8562. that is, `find(key) == end()`. See example below.
  8563. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8564. changes in the JSON value.
  8565. @complexity Logarithmic in the size of the container.
  8566. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8567. access by reference
  8568. @sa @ref value() for access by value with a default value
  8569. @since version 1.0.0
  8570. @liveexample{The example below shows how object elements can be read using
  8571. `at()`. It also demonstrates the different exceptions that can be thrown.,
  8572. at__object_t_key_type_const}
  8573. */
  8574. const_reference at(const typename object_t::key_type& key) const
  8575. {
  8576. // at only works for objects
  8577. if (JSON_LIKELY(is_object()))
  8578. {
  8579. JSON_TRY
  8580. {
  8581. return m_value.object->at(key);
  8582. }
  8583. JSON_CATCH (std::out_of_range&)
  8584. {
  8585. // create better exception explanation
  8586. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  8587. }
  8588. }
  8589. else
  8590. {
  8591. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8592. }
  8593. }
  8594. /*!
  8595. @brief access specified array element
  8596. Returns a reference to the element at specified location @a idx.
  8597. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  8598. then the array is silently filled up with `null` values to make `idx` a
  8599. valid reference to the last stored element.
  8600. @param[in] idx index of the element to access
  8601. @return reference to the element at index @a idx
  8602. @throw type_error.305 if the JSON value is not an array or null; in that
  8603. cases, using the [] operator with an index makes no sense.
  8604. @complexity Constant if @a idx is in the range of the array. Otherwise
  8605. linear in `idx - size()`.
  8606. @liveexample{The example below shows how array elements can be read and
  8607. written using `[]` operator. Note the addition of `null`
  8608. values.,operatorarray__size_type}
  8609. @since version 1.0.0
  8610. */
  8611. reference operator[](size_type idx)
  8612. {
  8613. // implicitly convert null value to an empty array
  8614. if (is_null())
  8615. {
  8616. m_type = value_t::array;
  8617. m_value.array = create<array_t>();
  8618. assert_invariant();
  8619. }
  8620. // operator[] only works for arrays
  8621. if (JSON_LIKELY(is_array()))
  8622. {
  8623. // fill up array with null values if given idx is outside range
  8624. if (idx >= m_value.array->size())
  8625. {
  8626. m_value.array->insert(m_value.array->end(),
  8627. idx - m_value.array->size() + 1,
  8628. basic_json());
  8629. }
  8630. return m_value.array->operator[](idx);
  8631. }
  8632. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8633. }
  8634. /*!
  8635. @brief access specified array element
  8636. Returns a const reference to the element at specified location @a idx.
  8637. @param[in] idx index of the element to access
  8638. @return const reference to the element at index @a idx
  8639. @throw type_error.305 if the JSON value is not an array; in that case,
  8640. using the [] operator with an index makes no sense.
  8641. @complexity Constant.
  8642. @liveexample{The example below shows how array elements can be read using
  8643. the `[]` operator.,operatorarray__size_type_const}
  8644. @since version 1.0.0
  8645. */
  8646. const_reference operator[](size_type idx) const
  8647. {
  8648. // const operator[] only works for arrays
  8649. if (JSON_LIKELY(is_array()))
  8650. {
  8651. return m_value.array->operator[](idx);
  8652. }
  8653. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8654. }
  8655. /*!
  8656. @brief access specified object element
  8657. Returns a reference to the element at with specified key @a key.
  8658. @note If @a key is not found in the object, then it is silently added to
  8659. the object and filled with a `null` value to make `key` a valid reference.
  8660. In case the value was `null` before, it is converted to an object.
  8661. @param[in] key key of the element to access
  8662. @return reference to the element at key @a key
  8663. @throw type_error.305 if the JSON value is not an object or null; in that
  8664. cases, using the [] operator with a key makes no sense.
  8665. @complexity Logarithmic in the size of the container.
  8666. @liveexample{The example below shows how object elements can be read and
  8667. written using the `[]` operator.,operatorarray__key_type}
  8668. @sa @ref at(const typename object_t::key_type&) for access by reference
  8669. with range checking
  8670. @sa @ref value() for access by value with a default value
  8671. @since version 1.0.0
  8672. */
  8673. reference operator[](const typename object_t::key_type& key)
  8674. {
  8675. // implicitly convert null value to an empty object
  8676. if (is_null())
  8677. {
  8678. m_type = value_t::object;
  8679. m_value.object = create<object_t>();
  8680. assert_invariant();
  8681. }
  8682. // operator[] only works for objects
  8683. if (JSON_LIKELY(is_object()))
  8684. {
  8685. return m_value.object->operator[](key);
  8686. }
  8687. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8688. }
  8689. /*!
  8690. @brief read-only access specified object element
  8691. Returns a const reference to the element at with specified key @a key. No
  8692. bounds checking is performed.
  8693. @warning If the element with key @a key does not exist, the behavior is
  8694. undefined.
  8695. @param[in] key key of the element to access
  8696. @return const reference to the element at key @a key
  8697. @pre The element with key @a key must exist. **This precondition is
  8698. enforced with an assertion.**
  8699. @throw type_error.305 if the JSON value is not an object; in that case,
  8700. using the [] operator with a key makes no sense.
  8701. @complexity Logarithmic in the size of the container.
  8702. @liveexample{The example below shows how object elements can be read using
  8703. the `[]` operator.,operatorarray__key_type_const}
  8704. @sa @ref at(const typename object_t::key_type&) for access by reference
  8705. with range checking
  8706. @sa @ref value() for access by value with a default value
  8707. @since version 1.0.0
  8708. */
  8709. const_reference operator[](const typename object_t::key_type& key) const
  8710. {
  8711. // const operator[] only works for objects
  8712. if (JSON_LIKELY(is_object()))
  8713. {
  8714. assert(m_value.object->find(key) != m_value.object->end());
  8715. return m_value.object->find(key)->second;
  8716. }
  8717. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8718. }
  8719. /*!
  8720. @brief access specified object element
  8721. Returns a reference to the element at with specified key @a key.
  8722. @note If @a key is not found in the object, then it is silently added to
  8723. the object and filled with a `null` value to make `key` a valid reference.
  8724. In case the value was `null` before, it is converted to an object.
  8725. @param[in] key key of the element to access
  8726. @return reference to the element at key @a key
  8727. @throw type_error.305 if the JSON value is not an object or null; in that
  8728. cases, using the [] operator with a key makes no sense.
  8729. @complexity Logarithmic in the size of the container.
  8730. @liveexample{The example below shows how object elements can be read and
  8731. written using the `[]` operator.,operatorarray__key_type}
  8732. @sa @ref at(const typename object_t::key_type&) for access by reference
  8733. with range checking
  8734. @sa @ref value() for access by value with a default value
  8735. @since version 1.1.0
  8736. */
  8737. template<typename T>
  8738. reference operator[](T* key)
  8739. {
  8740. // implicitly convert null to object
  8741. if (is_null())
  8742. {
  8743. m_type = value_t::object;
  8744. m_value = value_t::object;
  8745. assert_invariant();
  8746. }
  8747. // at only works for objects
  8748. if (JSON_LIKELY(is_object()))
  8749. {
  8750. return m_value.object->operator[](key);
  8751. }
  8752. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8753. }
  8754. /*!
  8755. @brief read-only access specified object element
  8756. Returns a const reference to the element at with specified key @a key. No
  8757. bounds checking is performed.
  8758. @warning If the element with key @a key does not exist, the behavior is
  8759. undefined.
  8760. @param[in] key key of the element to access
  8761. @return const reference to the element at key @a key
  8762. @pre The element with key @a key must exist. **This precondition is
  8763. enforced with an assertion.**
  8764. @throw type_error.305 if the JSON value is not an object; in that case,
  8765. using the [] operator with a key makes no sense.
  8766. @complexity Logarithmic in the size of the container.
  8767. @liveexample{The example below shows how object elements can be read using
  8768. the `[]` operator.,operatorarray__key_type_const}
  8769. @sa @ref at(const typename object_t::key_type&) for access by reference
  8770. with range checking
  8771. @sa @ref value() for access by value with a default value
  8772. @since version 1.1.0
  8773. */
  8774. template<typename T>
  8775. const_reference operator[](T* key) const
  8776. {
  8777. // at only works for objects
  8778. if (JSON_LIKELY(is_object()))
  8779. {
  8780. assert(m_value.object->find(key) != m_value.object->end());
  8781. return m_value.object->find(key)->second;
  8782. }
  8783. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8784. }
  8785. /*!
  8786. @brief access specified object element with default value
  8787. Returns either a copy of an object's element at the specified key @a key
  8788. or a given default value if no element with key @a key exists.
  8789. The function is basically equivalent to executing
  8790. @code {.cpp}
  8791. try {
  8792. return at(key);
  8793. } catch(out_of_range) {
  8794. return default_value;
  8795. }
  8796. @endcode
  8797. @note Unlike @ref at(const typename object_t::key_type&), this function
  8798. does not throw if the given key @a key was not found.
  8799. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  8800. function does not implicitly add an element to the position defined by @a
  8801. key. This function is furthermore also applicable to const objects.
  8802. @param[in] key key of the element to access
  8803. @param[in] default_value the value to return if @a key is not found
  8804. @tparam ValueType type compatible to JSON values, for instance `int` for
  8805. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  8806. JSON arrays. Note the type of the expected value at @a key and the default
  8807. value @a default_value must be compatible.
  8808. @return copy of the element at key @a key or @a default_value if @a key
  8809. is not found
  8810. @throw type_error.306 if the JSON value is not an object; in that case,
  8811. using `value()` with a key makes no sense.
  8812. @complexity Logarithmic in the size of the container.
  8813. @liveexample{The example below shows how object elements can be queried
  8814. with a default value.,basic_json__value}
  8815. @sa @ref at(const typename object_t::key_type&) for access by reference
  8816. with range checking
  8817. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8818. access by reference
  8819. @since version 1.0.0
  8820. */
  8821. template<class ValueType, typename std::enable_if<
  8822. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  8823. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  8824. {
  8825. // at only works for objects
  8826. if (JSON_LIKELY(is_object()))
  8827. {
  8828. // if key is found, return value and given default value otherwise
  8829. const auto it = find(key);
  8830. if (it != end())
  8831. {
  8832. return *it;
  8833. }
  8834. return default_value;
  8835. }
  8836. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  8837. }
  8838. /*!
  8839. @brief overload for a default value of type const char*
  8840. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  8841. */
  8842. string_t value(const typename object_t::key_type& key, const char* default_value) const
  8843. {
  8844. return value(key, string_t(default_value));
  8845. }
  8846. /*!
  8847. @brief access specified object element via JSON Pointer with default value
  8848. Returns either a copy of an object's element at the specified key @a key
  8849. or a given default value if no element with key @a key exists.
  8850. The function is basically equivalent to executing
  8851. @code {.cpp}
  8852. try {
  8853. return at(ptr);
  8854. } catch(out_of_range) {
  8855. return default_value;
  8856. }
  8857. @endcode
  8858. @note Unlike @ref at(const json_pointer&), this function does not throw
  8859. if the given key @a key was not found.
  8860. @param[in] ptr a JSON pointer to the element to access
  8861. @param[in] default_value the value to return if @a ptr found no value
  8862. @tparam ValueType type compatible to JSON values, for instance `int` for
  8863. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  8864. JSON arrays. Note the type of the expected value at @a key and the default
  8865. value @a default_value must be compatible.
  8866. @return copy of the element at key @a key or @a default_value if @a key
  8867. is not found
  8868. @throw type_error.306 if the JSON value is not an objec; in that case,
  8869. using `value()` with a key makes no sense.
  8870. @complexity Logarithmic in the size of the container.
  8871. @liveexample{The example below shows how object elements can be queried
  8872. with a default value.,basic_json__value_ptr}
  8873. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  8874. @since version 2.0.2
  8875. */
  8876. template<class ValueType, typename std::enable_if<
  8877. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  8878. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  8879. {
  8880. // at only works for objects
  8881. if (JSON_LIKELY(is_object()))
  8882. {
  8883. // if pointer resolves a value, return it or use default value
  8884. JSON_TRY
  8885. {
  8886. return ptr.get_checked(this);
  8887. }
  8888. JSON_CATCH (out_of_range&)
  8889. {
  8890. return default_value;
  8891. }
  8892. }
  8893. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  8894. }
  8895. /*!
  8896. @brief overload for a default value of type const char*
  8897. @copydoc basic_json::value(const json_pointer&, ValueType) const
  8898. */
  8899. string_t value(const json_pointer& ptr, const char* default_value) const
  8900. {
  8901. return value(ptr, string_t(default_value));
  8902. }
  8903. /*!
  8904. @brief access the first element
  8905. Returns a reference to the first element in the container. For a JSON
  8906. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  8907. @return In case of a structured type (array or object), a reference to the
  8908. first element is returned. In case of number, string, or boolean values, a
  8909. reference to the value is returned.
  8910. @complexity Constant.
  8911. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  8912. or an empty array or object (undefined behavior, **guarded by
  8913. assertions**).
  8914. @post The JSON value remains unchanged.
  8915. @throw invalid_iterator.214 when called on `null` value
  8916. @liveexample{The following code shows an example for `front()`.,front}
  8917. @sa @ref back() -- access the last element
  8918. @since version 1.0.0
  8919. */
  8920. reference front()
  8921. {
  8922. return *begin();
  8923. }
  8924. /*!
  8925. @copydoc basic_json::front()
  8926. */
  8927. const_reference front() const
  8928. {
  8929. return *cbegin();
  8930. }
  8931. /*!
  8932. @brief access the last element
  8933. Returns a reference to the last element in the container. For a JSON
  8934. container `c`, the expression `c.back()` is equivalent to
  8935. @code {.cpp}
  8936. auto tmp = c.end();
  8937. --tmp;
  8938. return *tmp;
  8939. @endcode
  8940. @return In case of a structured type (array or object), a reference to the
  8941. last element is returned. In case of number, string, or boolean values, a
  8942. reference to the value is returned.
  8943. @complexity Constant.
  8944. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  8945. or an empty array or object (undefined behavior, **guarded by
  8946. assertions**).
  8947. @post The JSON value remains unchanged.
  8948. @throw invalid_iterator.214 when called on a `null` value. See example
  8949. below.
  8950. @liveexample{The following code shows an example for `back()`.,back}
  8951. @sa @ref front() -- access the first element
  8952. @since version 1.0.0
  8953. */
  8954. reference back()
  8955. {
  8956. auto tmp = end();
  8957. --tmp;
  8958. return *tmp;
  8959. }
  8960. /*!
  8961. @copydoc basic_json::back()
  8962. */
  8963. const_reference back() const
  8964. {
  8965. auto tmp = cend();
  8966. --tmp;
  8967. return *tmp;
  8968. }
  8969. /*!
  8970. @brief remove element given an iterator
  8971. Removes the element specified by iterator @a pos. The iterator @a pos must
  8972. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  8973. but is not dereferenceable) cannot be used as a value for @a pos.
  8974. If called on a primitive type other than `null`, the resulting JSON value
  8975. will be `null`.
  8976. @param[in] pos iterator to the element to remove
  8977. @return Iterator following the last removed element. If the iterator @a
  8978. pos refers to the last element, the `end()` iterator is returned.
  8979. @tparam IteratorType an @ref iterator or @ref const_iterator
  8980. @post Invalidates iterators and references at or after the point of the
  8981. erase, including the `end()` iterator.
  8982. @throw type_error.307 if called on a `null` value; example: `"cannot use
  8983. erase() with null"`
  8984. @throw invalid_iterator.202 if called on an iterator which does not belong
  8985. to the current JSON value; example: `"iterator does not fit current
  8986. value"`
  8987. @throw invalid_iterator.205 if called on a primitive type with invalid
  8988. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  8989. out of range"`
  8990. @complexity The complexity depends on the type:
  8991. - objects: amortized constant
  8992. - arrays: linear in distance between @a pos and the end of the container
  8993. - strings: linear in the length of the string
  8994. - other types: constant
  8995. @liveexample{The example shows the result of `erase()` for different JSON
  8996. types.,erase__IteratorType}
  8997. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  8998. the given range
  8999. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  9000. from an object at the given key
  9001. @sa @ref erase(const size_type) -- removes the element from an array at
  9002. the given index
  9003. @since version 1.0.0
  9004. */
  9005. template<class IteratorType, typename std::enable_if<
  9006. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  9007. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  9008. = 0>
  9009. IteratorType erase(IteratorType pos)
  9010. {
  9011. // make sure iterator fits the current value
  9012. if (JSON_UNLIKELY(this != pos.m_object))
  9013. {
  9014. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  9015. }
  9016. IteratorType result = end();
  9017. switch (m_type)
  9018. {
  9019. case value_t::boolean:
  9020. case value_t::number_float:
  9021. case value_t::number_integer:
  9022. case value_t::number_unsigned:
  9023. case value_t::string:
  9024. {
  9025. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  9026. {
  9027. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  9028. }
  9029. if (is_string())
  9030. {
  9031. AllocatorType<string_t> alloc;
  9032. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  9033. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  9034. m_value.string = nullptr;
  9035. }
  9036. m_type = value_t::null;
  9037. assert_invariant();
  9038. break;
  9039. }
  9040. case value_t::object:
  9041. {
  9042. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  9043. break;
  9044. }
  9045. case value_t::array:
  9046. {
  9047. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  9048. break;
  9049. }
  9050. default:
  9051. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9052. }
  9053. return result;
  9054. }
  9055. /*!
  9056. @brief remove elements given an iterator range
  9057. Removes the element specified by the range `[first; last)`. The iterator
  9058. @a first does not need to be dereferenceable if `first == last`: erasing
  9059. an empty range is a no-op.
  9060. If called on a primitive type other than `null`, the resulting JSON value
  9061. will be `null`.
  9062. @param[in] first iterator to the beginning of the range to remove
  9063. @param[in] last iterator past the end of the range to remove
  9064. @return Iterator following the last removed element. If the iterator @a
  9065. second refers to the last element, the `end()` iterator is returned.
  9066. @tparam IteratorType an @ref iterator or @ref const_iterator
  9067. @post Invalidates iterators and references at or after the point of the
  9068. erase, including the `end()` iterator.
  9069. @throw type_error.307 if called on a `null` value; example: `"cannot use
  9070. erase() with null"`
  9071. @throw invalid_iterator.203 if called on iterators which does not belong
  9072. to the current JSON value; example: `"iterators do not fit current value"`
  9073. @throw invalid_iterator.204 if called on a primitive type with invalid
  9074. iterators (i.e., if `first != begin()` and `last != end()`); example:
  9075. `"iterators out of range"`
  9076. @complexity The complexity depends on the type:
  9077. - objects: `log(size()) + std::distance(first, last)`
  9078. - arrays: linear in the distance between @a first and @a last, plus linear
  9079. in the distance between @a last and end of the container
  9080. - strings: linear in the length of the string
  9081. - other types: constant
  9082. @liveexample{The example shows the result of `erase()` for different JSON
  9083. types.,erase__IteratorType_IteratorType}
  9084. @sa @ref erase(IteratorType) -- removes the element at a given position
  9085. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  9086. from an object at the given key
  9087. @sa @ref erase(const size_type) -- removes the element from an array at
  9088. the given index
  9089. @since version 1.0.0
  9090. */
  9091. template<class IteratorType, typename std::enable_if<
  9092. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  9093. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  9094. = 0>
  9095. IteratorType erase(IteratorType first, IteratorType last)
  9096. {
  9097. // make sure iterator fits the current value
  9098. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  9099. {
  9100. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  9101. }
  9102. IteratorType result = end();
  9103. switch (m_type)
  9104. {
  9105. case value_t::boolean:
  9106. case value_t::number_float:
  9107. case value_t::number_integer:
  9108. case value_t::number_unsigned:
  9109. case value_t::string:
  9110. {
  9111. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  9112. or not last.m_it.primitive_iterator.is_end()))
  9113. {
  9114. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  9115. }
  9116. if (is_string())
  9117. {
  9118. AllocatorType<string_t> alloc;
  9119. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  9120. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  9121. m_value.string = nullptr;
  9122. }
  9123. m_type = value_t::null;
  9124. assert_invariant();
  9125. break;
  9126. }
  9127. case value_t::object:
  9128. {
  9129. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  9130. last.m_it.object_iterator);
  9131. break;
  9132. }
  9133. case value_t::array:
  9134. {
  9135. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  9136. last.m_it.array_iterator);
  9137. break;
  9138. }
  9139. default:
  9140. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9141. }
  9142. return result;
  9143. }
  9144. /*!
  9145. @brief remove element from a JSON object given a key
  9146. Removes elements from a JSON object with the key value @a key.
  9147. @param[in] key value of the elements to remove
  9148. @return Number of elements removed. If @a ObjectType is the default
  9149. `std::map` type, the return value will always be `0` (@a key was not
  9150. found) or `1` (@a key was found).
  9151. @post References and iterators to the erased elements are invalidated.
  9152. Other references and iterators are not affected.
  9153. @throw type_error.307 when called on a type other than JSON object;
  9154. example: `"cannot use erase() with null"`
  9155. @complexity `log(size()) + count(key)`
  9156. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  9157. @sa @ref erase(IteratorType) -- removes the element at a given position
  9158. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  9159. the given range
  9160. @sa @ref erase(const size_type) -- removes the element from an array at
  9161. the given index
  9162. @since version 1.0.0
  9163. */
  9164. size_type erase(const typename object_t::key_type& key)
  9165. {
  9166. // this erase only works for objects
  9167. if (JSON_LIKELY(is_object()))
  9168. {
  9169. return m_value.object->erase(key);
  9170. }
  9171. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9172. }
  9173. /*!
  9174. @brief remove element from a JSON array given an index
  9175. Removes element from a JSON array at the index @a idx.
  9176. @param[in] idx index of the element to remove
  9177. @throw type_error.307 when called on a type other than JSON object;
  9178. example: `"cannot use erase() with null"`
  9179. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  9180. is out of range"`
  9181. @complexity Linear in distance between @a idx and the end of the container.
  9182. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  9183. @sa @ref erase(IteratorType) -- removes the element at a given position
  9184. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  9185. the given range
  9186. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  9187. from an object at the given key
  9188. @since version 1.0.0
  9189. */
  9190. void erase(const size_type idx)
  9191. {
  9192. // this erase only works for arrays
  9193. if (JSON_LIKELY(is_array()))
  9194. {
  9195. if (JSON_UNLIKELY(idx >= size()))
  9196. {
  9197. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  9198. }
  9199. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  9200. }
  9201. else
  9202. {
  9203. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9204. }
  9205. }
  9206. /// @}
  9207. ////////////
  9208. // lookup //
  9209. ////////////
  9210. /// @name lookup
  9211. /// @{
  9212. /*!
  9213. @brief find an element in a JSON object
  9214. Finds an element in a JSON object with key equivalent to @a key. If the
  9215. element is not found or the JSON value is not an object, end() is
  9216. returned.
  9217. @note This method always returns @ref end() when executed on a JSON type
  9218. that is not an object.
  9219. @param[in] key key value of the element to search for.
  9220. @return Iterator to an element with key equivalent to @a key. If no such
  9221. element is found or the JSON value is not an object, past-the-end (see
  9222. @ref end()) iterator is returned.
  9223. @complexity Logarithmic in the size of the JSON object.
  9224. @liveexample{The example shows how `find()` is used.,find__key_type}
  9225. @since version 1.0.0
  9226. */
  9227. template<typename KeyT>
  9228. iterator find(KeyT&& key)
  9229. {
  9230. auto result = end();
  9231. if (is_object())
  9232. {
  9233. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  9234. }
  9235. return result;
  9236. }
  9237. /*!
  9238. @brief find an element in a JSON object
  9239. @copydoc find(KeyT&&)
  9240. */
  9241. template<typename KeyT>
  9242. const_iterator find(KeyT&& key) const
  9243. {
  9244. auto result = cend();
  9245. if (is_object())
  9246. {
  9247. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  9248. }
  9249. return result;
  9250. }
  9251. /*!
  9252. @brief returns the number of occurrences of a key in a JSON object
  9253. Returns the number of elements with key @a key. If ObjectType is the
  9254. default `std::map` type, the return value will always be `0` (@a key was
  9255. not found) or `1` (@a key was found).
  9256. @note This method always returns `0` when executed on a JSON type that is
  9257. not an object.
  9258. @param[in] key key value of the element to count
  9259. @return Number of elements with key @a key. If the JSON value is not an
  9260. object, the return value will be `0`.
  9261. @complexity Logarithmic in the size of the JSON object.
  9262. @liveexample{The example shows how `count()` is used.,count}
  9263. @since version 1.0.0
  9264. */
  9265. template<typename KeyT>
  9266. size_type count(KeyT&& key) const
  9267. {
  9268. // return 0 for all nonobject types
  9269. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  9270. }
  9271. /// @}
  9272. ///////////////
  9273. // iterators //
  9274. ///////////////
  9275. /// @name iterators
  9276. /// @{
  9277. /*!
  9278. @brief returns an iterator to the first element
  9279. Returns an iterator to the first element.
  9280. @image html range-begin-end.svg "Illustration from cppreference.com"
  9281. @return iterator to the first element
  9282. @complexity Constant.
  9283. @requirement This function helps `basic_json` satisfying the
  9284. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9285. requirements:
  9286. - The complexity is constant.
  9287. @liveexample{The following code shows an example for `begin()`.,begin}
  9288. @sa @ref cbegin() -- returns a const iterator to the beginning
  9289. @sa @ref end() -- returns an iterator to the end
  9290. @sa @ref cend() -- returns a const iterator to the end
  9291. @since version 1.0.0
  9292. */
  9293. iterator begin() noexcept
  9294. {
  9295. iterator result(this);
  9296. result.set_begin();
  9297. return result;
  9298. }
  9299. /*!
  9300. @copydoc basic_json::cbegin()
  9301. */
  9302. const_iterator begin() const noexcept
  9303. {
  9304. return cbegin();
  9305. }
  9306. /*!
  9307. @brief returns a const iterator to the first element
  9308. Returns a const iterator to the first element.
  9309. @image html range-begin-end.svg "Illustration from cppreference.com"
  9310. @return const iterator to the first element
  9311. @complexity Constant.
  9312. @requirement This function helps `basic_json` satisfying the
  9313. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9314. requirements:
  9315. - The complexity is constant.
  9316. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  9317. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  9318. @sa @ref begin() -- returns an iterator to the beginning
  9319. @sa @ref end() -- returns an iterator to the end
  9320. @sa @ref cend() -- returns a const iterator to the end
  9321. @since version 1.0.0
  9322. */
  9323. const_iterator cbegin() const noexcept
  9324. {
  9325. const_iterator result(this);
  9326. result.set_begin();
  9327. return result;
  9328. }
  9329. /*!
  9330. @brief returns an iterator to one past the last element
  9331. Returns an iterator to one past the last element.
  9332. @image html range-begin-end.svg "Illustration from cppreference.com"
  9333. @return iterator one past the last element
  9334. @complexity Constant.
  9335. @requirement This function helps `basic_json` satisfying the
  9336. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9337. requirements:
  9338. - The complexity is constant.
  9339. @liveexample{The following code shows an example for `end()`.,end}
  9340. @sa @ref cend() -- returns a const iterator to the end
  9341. @sa @ref begin() -- returns an iterator to the beginning
  9342. @sa @ref cbegin() -- returns a const iterator to the beginning
  9343. @since version 1.0.0
  9344. */
  9345. iterator end() noexcept
  9346. {
  9347. iterator result(this);
  9348. result.set_end();
  9349. return result;
  9350. }
  9351. /*!
  9352. @copydoc basic_json::cend()
  9353. */
  9354. const_iterator end() const noexcept
  9355. {
  9356. return cend();
  9357. }
  9358. /*!
  9359. @brief returns a const iterator to one past the last element
  9360. Returns a const iterator to one past the last element.
  9361. @image html range-begin-end.svg "Illustration from cppreference.com"
  9362. @return const iterator one past the last element
  9363. @complexity Constant.
  9364. @requirement This function helps `basic_json` satisfying the
  9365. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9366. requirements:
  9367. - The complexity is constant.
  9368. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  9369. @liveexample{The following code shows an example for `cend()`.,cend}
  9370. @sa @ref end() -- returns an iterator to the end
  9371. @sa @ref begin() -- returns an iterator to the beginning
  9372. @sa @ref cbegin() -- returns a const iterator to the beginning
  9373. @since version 1.0.0
  9374. */
  9375. const_iterator cend() const noexcept
  9376. {
  9377. const_iterator result(this);
  9378. result.set_end();
  9379. return result;
  9380. }
  9381. /*!
  9382. @brief returns an iterator to the reverse-beginning
  9383. Returns an iterator to the reverse-beginning; that is, the last element.
  9384. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9385. @complexity Constant.
  9386. @requirement This function helps `basic_json` satisfying the
  9387. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9388. requirements:
  9389. - The complexity is constant.
  9390. - Has the semantics of `reverse_iterator(end())`.
  9391. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  9392. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9393. @sa @ref rend() -- returns a reverse iterator to the end
  9394. @sa @ref crend() -- returns a const reverse iterator to the end
  9395. @since version 1.0.0
  9396. */
  9397. reverse_iterator rbegin() noexcept
  9398. {
  9399. return reverse_iterator(end());
  9400. }
  9401. /*!
  9402. @copydoc basic_json::crbegin()
  9403. */
  9404. const_reverse_iterator rbegin() const noexcept
  9405. {
  9406. return crbegin();
  9407. }
  9408. /*!
  9409. @brief returns an iterator to the reverse-end
  9410. Returns an iterator to the reverse-end; that is, one before the first
  9411. element.
  9412. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9413. @complexity Constant.
  9414. @requirement This function helps `basic_json` satisfying the
  9415. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9416. requirements:
  9417. - The complexity is constant.
  9418. - Has the semantics of `reverse_iterator(begin())`.
  9419. @liveexample{The following code shows an example for `rend()`.,rend}
  9420. @sa @ref crend() -- returns a const reverse iterator to the end
  9421. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9422. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9423. @since version 1.0.0
  9424. */
  9425. reverse_iterator rend() noexcept
  9426. {
  9427. return reverse_iterator(begin());
  9428. }
  9429. /*!
  9430. @copydoc basic_json::crend()
  9431. */
  9432. const_reverse_iterator rend() const noexcept
  9433. {
  9434. return crend();
  9435. }
  9436. /*!
  9437. @brief returns a const reverse iterator to the last element
  9438. Returns a const iterator to the reverse-beginning; that is, the last
  9439. element.
  9440. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9441. @complexity Constant.
  9442. @requirement This function helps `basic_json` satisfying the
  9443. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9444. requirements:
  9445. - The complexity is constant.
  9446. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  9447. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  9448. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9449. @sa @ref rend() -- returns a reverse iterator to the end
  9450. @sa @ref crend() -- returns a const reverse iterator to the end
  9451. @since version 1.0.0
  9452. */
  9453. const_reverse_iterator crbegin() const noexcept
  9454. {
  9455. return const_reverse_iterator(cend());
  9456. }
  9457. /*!
  9458. @brief returns a const reverse iterator to one before the first
  9459. Returns a const reverse iterator to the reverse-end; that is, one before
  9460. the first element.
  9461. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9462. @complexity Constant.
  9463. @requirement This function helps `basic_json` satisfying the
  9464. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9465. requirements:
  9466. - The complexity is constant.
  9467. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  9468. @liveexample{The following code shows an example for `crend()`.,crend}
  9469. @sa @ref rend() -- returns a reverse iterator to the end
  9470. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9471. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9472. @since version 1.0.0
  9473. */
  9474. const_reverse_iterator crend() const noexcept
  9475. {
  9476. return const_reverse_iterator(cbegin());
  9477. }
  9478. public:
  9479. /*!
  9480. @brief wrapper to access iterator member functions in range-based for
  9481. This function allows to access @ref iterator::key() and @ref
  9482. iterator::value() during range-based for loops. In these loops, a
  9483. reference to the JSON values is returned, so there is no access to the
  9484. underlying iterator.
  9485. For loop without iterator_wrapper:
  9486. @code{cpp}
  9487. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  9488. {
  9489. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  9490. }
  9491. @endcode
  9492. Range-based for loop without iterator proxy:
  9493. @code{cpp}
  9494. for (auto it : j_object)
  9495. {
  9496. // "it" is of type json::reference and has no key() member
  9497. std::cout << "value: " << it << '\n';
  9498. }
  9499. @endcode
  9500. Range-based for loop with iterator proxy:
  9501. @code{cpp}
  9502. for (auto it : json::iterator_wrapper(j_object))
  9503. {
  9504. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  9505. }
  9506. @endcode
  9507. @note When iterating over an array, `key()` will return the index of the
  9508. element as string (see example).
  9509. @param[in] ref reference to a JSON value
  9510. @return iteration proxy object wrapping @a ref with an interface to use in
  9511. range-based for loops
  9512. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  9513. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9514. changes in the JSON value.
  9515. @complexity Constant.
  9516. @note The name of this function is not yet final and may change in the
  9517. future.
  9518. */
  9519. static iteration_proxy<iterator> iterator_wrapper(reference ref)
  9520. {
  9521. return iteration_proxy<iterator>(ref);
  9522. }
  9523. /*!
  9524. @copydoc iterator_wrapper(reference)
  9525. */
  9526. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref)
  9527. {
  9528. return iteration_proxy<const_iterator>(ref);
  9529. }
  9530. /// @}
  9531. //////////////
  9532. // capacity //
  9533. //////////////
  9534. /// @name capacity
  9535. /// @{
  9536. /*!
  9537. @brief checks whether the container is empty.
  9538. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  9539. @return The return value depends on the different types and is
  9540. defined as follows:
  9541. Value type | return value
  9542. ----------- | -------------
  9543. null | `true`
  9544. boolean | `false`
  9545. string | `false`
  9546. number | `false`
  9547. object | result of function `object_t::empty()`
  9548. array | result of function `array_t::empty()`
  9549. @liveexample{The following code uses `empty()` to check if a JSON
  9550. object contains any elements.,empty}
  9551. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9552. the Container concept; that is, their `empty()` functions have constant
  9553. complexity.
  9554. @iterators No changes.
  9555. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9556. @note This function does not return whether a string stored as JSON value
  9557. is empty - it returns whether the JSON container itself is empty which is
  9558. false in the case of a string.
  9559. @requirement This function helps `basic_json` satisfying the
  9560. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9561. requirements:
  9562. - The complexity is constant.
  9563. - Has the semantics of `begin() == end()`.
  9564. @sa @ref size() -- returns the number of elements
  9565. @since version 1.0.0
  9566. */
  9567. bool empty() const noexcept
  9568. {
  9569. switch (m_type)
  9570. {
  9571. case value_t::null:
  9572. {
  9573. // null values are empty
  9574. return true;
  9575. }
  9576. case value_t::array:
  9577. {
  9578. // delegate call to array_t::empty()
  9579. return m_value.array->empty();
  9580. }
  9581. case value_t::object:
  9582. {
  9583. // delegate call to object_t::empty()
  9584. return m_value.object->empty();
  9585. }
  9586. default:
  9587. {
  9588. // all other types are nonempty
  9589. return false;
  9590. }
  9591. }
  9592. }
  9593. /*!
  9594. @brief returns the number of elements
  9595. Returns the number of elements in a JSON value.
  9596. @return The return value depends on the different types and is
  9597. defined as follows:
  9598. Value type | return value
  9599. ----------- | -------------
  9600. null | `0`
  9601. boolean | `1`
  9602. string | `1`
  9603. number | `1`
  9604. object | result of function object_t::size()
  9605. array | result of function array_t::size()
  9606. @liveexample{The following code calls `size()` on the different value
  9607. types.,size}
  9608. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9609. the Container concept; that is, their size() functions have constant
  9610. complexity.
  9611. @iterators No changes.
  9612. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9613. @note This function does not return the length of a string stored as JSON
  9614. value - it returns the number of elements in the JSON value which is 1 in
  9615. the case of a string.
  9616. @requirement This function helps `basic_json` satisfying the
  9617. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9618. requirements:
  9619. - The complexity is constant.
  9620. - Has the semantics of `std::distance(begin(), end())`.
  9621. @sa @ref empty() -- checks whether the container is empty
  9622. @sa @ref max_size() -- returns the maximal number of elements
  9623. @since version 1.0.0
  9624. */
  9625. size_type size() const noexcept
  9626. {
  9627. switch (m_type)
  9628. {
  9629. case value_t::null:
  9630. {
  9631. // null values are empty
  9632. return 0;
  9633. }
  9634. case value_t::array:
  9635. {
  9636. // delegate call to array_t::size()
  9637. return m_value.array->size();
  9638. }
  9639. case value_t::object:
  9640. {
  9641. // delegate call to object_t::size()
  9642. return m_value.object->size();
  9643. }
  9644. default:
  9645. {
  9646. // all other types have size 1
  9647. return 1;
  9648. }
  9649. }
  9650. }
  9651. /*!
  9652. @brief returns the maximum possible number of elements
  9653. Returns the maximum number of elements a JSON value is able to hold due to
  9654. system or library implementation limitations, i.e. `std::distance(begin(),
  9655. end())` for the JSON value.
  9656. @return The return value depends on the different types and is
  9657. defined as follows:
  9658. Value type | return value
  9659. ----------- | -------------
  9660. null | `0` (same as `size()`)
  9661. boolean | `1` (same as `size()`)
  9662. string | `1` (same as `size()`)
  9663. number | `1` (same as `size()`)
  9664. object | result of function `object_t::max_size()`
  9665. array | result of function `array_t::max_size()`
  9666. @liveexample{The following code calls `max_size()` on the different value
  9667. types. Note the output is implementation specific.,max_size}
  9668. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9669. the Container concept; that is, their `max_size()` functions have constant
  9670. complexity.
  9671. @iterators No changes.
  9672. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9673. @requirement This function helps `basic_json` satisfying the
  9674. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9675. requirements:
  9676. - The complexity is constant.
  9677. - Has the semantics of returning `b.size()` where `b` is the largest
  9678. possible JSON value.
  9679. @sa @ref size() -- returns the number of elements
  9680. @since version 1.0.0
  9681. */
  9682. size_type max_size() const noexcept
  9683. {
  9684. switch (m_type)
  9685. {
  9686. case value_t::array:
  9687. {
  9688. // delegate call to array_t::max_size()
  9689. return m_value.array->max_size();
  9690. }
  9691. case value_t::object:
  9692. {
  9693. // delegate call to object_t::max_size()
  9694. return m_value.object->max_size();
  9695. }
  9696. default:
  9697. {
  9698. // all other types have max_size() == size()
  9699. return size();
  9700. }
  9701. }
  9702. }
  9703. /// @}
  9704. ///////////////
  9705. // modifiers //
  9706. ///////////////
  9707. /// @name modifiers
  9708. /// @{
  9709. /*!
  9710. @brief clears the contents
  9711. Clears the content of a JSON value and resets it to the default value as
  9712. if @ref basic_json(value_t) would have been called with the current value
  9713. type from @ref type():
  9714. Value type | initial value
  9715. ----------- | -------------
  9716. null | `null`
  9717. boolean | `false`
  9718. string | `""`
  9719. number | `0`
  9720. object | `{}`
  9721. array | `[]`
  9722. @post Has the same effect as calling
  9723. @code {.cpp}
  9724. *this = basic_json(type());
  9725. @endcode
  9726. @liveexample{The example below shows the effect of `clear()` to different
  9727. JSON types.,clear}
  9728. @complexity Linear in the size of the JSON value.
  9729. @iterators All iterators, pointers and references related to this container
  9730. are invalidated.
  9731. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9732. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  9733. same value than calling `clear()`
  9734. @since version 1.0.0
  9735. */
  9736. void clear() noexcept
  9737. {
  9738. switch (m_type)
  9739. {
  9740. case value_t::number_integer:
  9741. {
  9742. m_value.number_integer = 0;
  9743. break;
  9744. }
  9745. case value_t::number_unsigned:
  9746. {
  9747. m_value.number_unsigned = 0;
  9748. break;
  9749. }
  9750. case value_t::number_float:
  9751. {
  9752. m_value.number_float = 0.0;
  9753. break;
  9754. }
  9755. case value_t::boolean:
  9756. {
  9757. m_value.boolean = false;
  9758. break;
  9759. }
  9760. case value_t::string:
  9761. {
  9762. m_value.string->clear();
  9763. break;
  9764. }
  9765. case value_t::array:
  9766. {
  9767. m_value.array->clear();
  9768. break;
  9769. }
  9770. case value_t::object:
  9771. {
  9772. m_value.object->clear();
  9773. break;
  9774. }
  9775. default:
  9776. break;
  9777. }
  9778. }
  9779. /*!
  9780. @brief add an object to an array
  9781. Appends the given element @a val to the end of the JSON value. If the
  9782. function is called on a JSON null value, an empty array is created before
  9783. appending @a val.
  9784. @param[in] val the value to add to the JSON array
  9785. @throw type_error.308 when called on a type other than JSON array or
  9786. null; example: `"cannot use push_back() with number"`
  9787. @complexity Amortized constant.
  9788. @liveexample{The example shows how `push_back()` and `+=` can be used to
  9789. add elements to a JSON array. Note how the `null` value was silently
  9790. converted to a JSON array.,push_back}
  9791. @since version 1.0.0
  9792. */
  9793. void push_back(basic_json&& val)
  9794. {
  9795. // push_back only works for null objects or arrays
  9796. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9797. {
  9798. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9799. }
  9800. // transform null object into an array
  9801. if (is_null())
  9802. {
  9803. m_type = value_t::array;
  9804. m_value = value_t::array;
  9805. assert_invariant();
  9806. }
  9807. // add element to array (move semantics)
  9808. m_value.array->push_back(std::move(val));
  9809. // invalidate object
  9810. val.m_type = value_t::null;
  9811. }
  9812. /*!
  9813. @brief add an object to an array
  9814. @copydoc push_back(basic_json&&)
  9815. */
  9816. reference operator+=(basic_json&& val)
  9817. {
  9818. push_back(std::move(val));
  9819. return *this;
  9820. }
  9821. /*!
  9822. @brief add an object to an array
  9823. @copydoc push_back(basic_json&&)
  9824. */
  9825. void push_back(const basic_json& val)
  9826. {
  9827. // push_back only works for null objects or arrays
  9828. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9829. {
  9830. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9831. }
  9832. // transform null object into an array
  9833. if (is_null())
  9834. {
  9835. m_type = value_t::array;
  9836. m_value = value_t::array;
  9837. assert_invariant();
  9838. }
  9839. // add element to array
  9840. m_value.array->push_back(val);
  9841. }
  9842. /*!
  9843. @brief add an object to an array
  9844. @copydoc push_back(basic_json&&)
  9845. */
  9846. reference operator+=(const basic_json& val)
  9847. {
  9848. push_back(val);
  9849. return *this;
  9850. }
  9851. /*!
  9852. @brief add an object to an object
  9853. Inserts the given element @a val to the JSON object. If the function is
  9854. called on a JSON null value, an empty object is created before inserting
  9855. @a val.
  9856. @param[in] val the value to add to the JSON object
  9857. @throw type_error.308 when called on a type other than JSON object or
  9858. null; example: `"cannot use push_back() with number"`
  9859. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  9860. @liveexample{The example shows how `push_back()` and `+=` can be used to
  9861. add elements to a JSON object. Note how the `null` value was silently
  9862. converted to a JSON object.,push_back__object_t__value}
  9863. @since version 1.0.0
  9864. */
  9865. void push_back(const typename object_t::value_type& val)
  9866. {
  9867. // push_back only works for null objects or objects
  9868. if (JSON_UNLIKELY(not(is_null() or is_object())))
  9869. {
  9870. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9871. }
  9872. // transform null object into an object
  9873. if (is_null())
  9874. {
  9875. m_type = value_t::object;
  9876. m_value = value_t::object;
  9877. assert_invariant();
  9878. }
  9879. // add element to array
  9880. m_value.object->insert(val);
  9881. }
  9882. /*!
  9883. @brief add an object to an object
  9884. @copydoc push_back(const typename object_t::value_type&)
  9885. */
  9886. reference operator+=(const typename object_t::value_type& val)
  9887. {
  9888. push_back(val);
  9889. return *this;
  9890. }
  9891. /*!
  9892. @brief add an object to an object
  9893. This function allows to use `push_back` with an initializer list. In case
  9894. 1. the current value is an object,
  9895. 2. the initializer list @a init contains only two elements, and
  9896. 3. the first element of @a init is a string,
  9897. @a init is converted into an object element and added using
  9898. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  9899. is converted to a JSON value and added using @ref push_back(basic_json&&).
  9900. @param[in] init an initializer list
  9901. @complexity Linear in the size of the initializer list @a init.
  9902. @note This function is required to resolve an ambiguous overload error,
  9903. because pairs like `{"key", "value"}` can be both interpreted as
  9904. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  9905. https://github.com/nlohmann/json/issues/235 for more information.
  9906. @liveexample{The example shows how initializer lists are treated as
  9907. objects when possible.,push_back__initializer_list}
  9908. */
  9909. void push_back(initializer_list_t init)
  9910. {
  9911. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  9912. {
  9913. basic_json&& key = init.begin()->moved_or_copied();
  9914. push_back(typename object_t::value_type(
  9915. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  9916. }
  9917. else
  9918. {
  9919. push_back(basic_json(init));
  9920. }
  9921. }
  9922. /*!
  9923. @brief add an object to an object
  9924. @copydoc push_back(initializer_list_t)
  9925. */
  9926. reference operator+=(initializer_list_t init)
  9927. {
  9928. push_back(init);
  9929. return *this;
  9930. }
  9931. /*!
  9932. @brief add an object to an array
  9933. Creates a JSON value from the passed parameters @a args to the end of the
  9934. JSON value. If the function is called on a JSON null value, an empty array
  9935. is created before appending the value created from @a args.
  9936. @param[in] args arguments to forward to a constructor of @ref basic_json
  9937. @tparam Args compatible types to create a @ref basic_json object
  9938. @throw type_error.311 when called on a type other than JSON array or
  9939. null; example: `"cannot use emplace_back() with number"`
  9940. @complexity Amortized constant.
  9941. @liveexample{The example shows how `push_back()` can be used to add
  9942. elements to a JSON array. Note how the `null` value was silently converted
  9943. to a JSON array.,emplace_back}
  9944. @since version 2.0.8
  9945. */
  9946. template<class... Args>
  9947. void emplace_back(Args&& ... args)
  9948. {
  9949. // emplace_back only works for null objects or arrays
  9950. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9951. {
  9952. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  9953. }
  9954. // transform null object into an array
  9955. if (is_null())
  9956. {
  9957. m_type = value_t::array;
  9958. m_value = value_t::array;
  9959. assert_invariant();
  9960. }
  9961. // add element to array (perfect forwarding)
  9962. m_value.array->emplace_back(std::forward<Args>(args)...);
  9963. }
  9964. /*!
  9965. @brief add an object to an object if key does not exist
  9966. Inserts a new element into a JSON object constructed in-place with the
  9967. given @a args if there is no element with the key in the container. If the
  9968. function is called on a JSON null value, an empty object is created before
  9969. appending the value created from @a args.
  9970. @param[in] args arguments to forward to a constructor of @ref basic_json
  9971. @tparam Args compatible types to create a @ref basic_json object
  9972. @return a pair consisting of an iterator to the inserted element, or the
  9973. already-existing element if no insertion happened, and a bool
  9974. denoting whether the insertion took place.
  9975. @throw type_error.311 when called on a type other than JSON object or
  9976. null; example: `"cannot use emplace() with number"`
  9977. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  9978. @liveexample{The example shows how `emplace()` can be used to add elements
  9979. to a JSON object. Note how the `null` value was silently converted to a
  9980. JSON object. Further note how no value is added if there was already one
  9981. value stored with the same key.,emplace}
  9982. @since version 2.0.8
  9983. */
  9984. template<class... Args>
  9985. std::pair<iterator, bool> emplace(Args&& ... args)
  9986. {
  9987. // emplace only works for null objects or arrays
  9988. if (JSON_UNLIKELY(not(is_null() or is_object())))
  9989. {
  9990. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  9991. }
  9992. // transform null object into an object
  9993. if (is_null())
  9994. {
  9995. m_type = value_t::object;
  9996. m_value = value_t::object;
  9997. assert_invariant();
  9998. }
  9999. // add element to array (perfect forwarding)
  10000. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  10001. // create result iterator and set iterator to the result of emplace
  10002. auto it = begin();
  10003. it.m_it.object_iterator = res.first;
  10004. // return pair of iterator and boolean
  10005. return {it, res.second};
  10006. }
  10007. /*!
  10008. @brief inserts element
  10009. Inserts element @a val before iterator @a pos.
  10010. @param[in] pos iterator before which the content will be inserted; may be
  10011. the end() iterator
  10012. @param[in] val element to insert
  10013. @return iterator pointing to the inserted @a val.
  10014. @throw type_error.309 if called on JSON values other than arrays;
  10015. example: `"cannot use insert() with string"`
  10016. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  10017. example: `"iterator does not fit current value"`
  10018. @complexity Constant plus linear in the distance between @a pos and end of
  10019. the container.
  10020. @liveexample{The example shows how `insert()` is used.,insert}
  10021. @since version 1.0.0
  10022. */
  10023. iterator insert(const_iterator pos, const basic_json& val)
  10024. {
  10025. // insert only works for arrays
  10026. if (JSON_LIKELY(is_array()))
  10027. {
  10028. // check if iterator pos fits to this JSON value
  10029. if (JSON_UNLIKELY(pos.m_object != this))
  10030. {
  10031. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10032. }
  10033. // insert to array and return iterator
  10034. iterator result(this);
  10035. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  10036. return result;
  10037. }
  10038. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10039. }
  10040. /*!
  10041. @brief inserts element
  10042. @copydoc insert(const_iterator, const basic_json&)
  10043. */
  10044. iterator insert(const_iterator pos, basic_json&& val)
  10045. {
  10046. return insert(pos, val);
  10047. }
  10048. /*!
  10049. @brief inserts elements
  10050. Inserts @a cnt copies of @a val before iterator @a pos.
  10051. @param[in] pos iterator before which the content will be inserted; may be
  10052. the end() iterator
  10053. @param[in] cnt number of copies of @a val to insert
  10054. @param[in] val element to insert
  10055. @return iterator pointing to the first element inserted, or @a pos if
  10056. `cnt==0`
  10057. @throw type_error.309 if called on JSON values other than arrays; example:
  10058. `"cannot use insert() with string"`
  10059. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  10060. example: `"iterator does not fit current value"`
  10061. @complexity Linear in @a cnt plus linear in the distance between @a pos
  10062. and end of the container.
  10063. @liveexample{The example shows how `insert()` is used.,insert__count}
  10064. @since version 1.0.0
  10065. */
  10066. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  10067. {
  10068. // insert only works for arrays
  10069. if (JSON_LIKELY(is_array()))
  10070. {
  10071. // check if iterator pos fits to this JSON value
  10072. if (JSON_UNLIKELY(pos.m_object != this))
  10073. {
  10074. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10075. }
  10076. // insert to array and return iterator
  10077. iterator result(this);
  10078. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  10079. return result;
  10080. }
  10081. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10082. }
  10083. /*!
  10084. @brief inserts elements
  10085. Inserts elements from range `[first, last)` before iterator @a pos.
  10086. @param[in] pos iterator before which the content will be inserted; may be
  10087. the end() iterator
  10088. @param[in] first begin of the range of elements to insert
  10089. @param[in] last end of the range of elements to insert
  10090. @throw type_error.309 if called on JSON values other than arrays; example:
  10091. `"cannot use insert() with string"`
  10092. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  10093. example: `"iterator does not fit current value"`
  10094. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  10095. same JSON value; example: `"iterators do not fit"`
  10096. @throw invalid_iterator.211 if @a first or @a last are iterators into
  10097. container for which insert is called; example: `"passed iterators may not
  10098. belong to container"`
  10099. @return iterator pointing to the first element inserted, or @a pos if
  10100. `first==last`
  10101. @complexity Linear in `std::distance(first, last)` plus linear in the
  10102. distance between @a pos and end of the container.
  10103. @liveexample{The example shows how `insert()` is used.,insert__range}
  10104. @since version 1.0.0
  10105. */
  10106. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  10107. {
  10108. // insert only works for arrays
  10109. if (JSON_UNLIKELY(not is_array()))
  10110. {
  10111. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10112. }
  10113. // check if iterator pos fits to this JSON value
  10114. if (JSON_UNLIKELY(pos.m_object != this))
  10115. {
  10116. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10117. }
  10118. // check if range iterators belong to the same JSON object
  10119. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10120. {
  10121. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10122. }
  10123. if (JSON_UNLIKELY(first.m_object == this))
  10124. {
  10125. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  10126. }
  10127. // insert to array and return iterator
  10128. iterator result(this);
  10129. result.m_it.array_iterator = m_value.array->insert(
  10130. pos.m_it.array_iterator,
  10131. first.m_it.array_iterator,
  10132. last.m_it.array_iterator);
  10133. return result;
  10134. }
  10135. /*!
  10136. @brief inserts elements
  10137. Inserts elements from initializer list @a ilist before iterator @a pos.
  10138. @param[in] pos iterator before which the content will be inserted; may be
  10139. the end() iterator
  10140. @param[in] ilist initializer list to insert the values from
  10141. @throw type_error.309 if called on JSON values other than arrays; example:
  10142. `"cannot use insert() with string"`
  10143. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  10144. example: `"iterator does not fit current value"`
  10145. @return iterator pointing to the first element inserted, or @a pos if
  10146. `ilist` is empty
  10147. @complexity Linear in `ilist.size()` plus linear in the distance between
  10148. @a pos and end of the container.
  10149. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  10150. @since version 1.0.0
  10151. */
  10152. iterator insert(const_iterator pos, initializer_list_t ilist)
  10153. {
  10154. // insert only works for arrays
  10155. if (JSON_UNLIKELY(not is_array()))
  10156. {
  10157. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10158. }
  10159. // check if iterator pos fits to this JSON value
  10160. if (JSON_UNLIKELY(pos.m_object != this))
  10161. {
  10162. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10163. }
  10164. // insert to array and return iterator
  10165. iterator result(this);
  10166. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
  10167. return result;
  10168. }
  10169. /*!
  10170. @brief inserts elements
  10171. Inserts elements from range `[first, last)`.
  10172. @param[in] first begin of the range of elements to insert
  10173. @param[in] last end of the range of elements to insert
  10174. @throw type_error.309 if called on JSON values other than objects; example:
  10175. `"cannot use insert() with string"`
  10176. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  10177. point to an object; example: `"iterators first and last must point to
  10178. objects"`
  10179. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  10180. same JSON value; example: `"iterators do not fit"`
  10181. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  10182. of elements to insert.
  10183. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  10184. @since version 3.0.0
  10185. */
  10186. void insert(const_iterator first, const_iterator last)
  10187. {
  10188. // insert only works for objects
  10189. if (JSON_UNLIKELY(not is_object()))
  10190. {
  10191. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10192. }
  10193. // check if range iterators belong to the same JSON object
  10194. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10195. {
  10196. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10197. }
  10198. // passed iterators must belong to objects
  10199. if (JSON_UNLIKELY(not first.m_object->is_object()))
  10200. {
  10201. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  10202. }
  10203. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  10204. }
  10205. /*!
  10206. @brief updates a JSON object from another object, overwriting existing keys
  10207. Inserts all values from JSON object @a j and overwrites existing keys.
  10208. @param[in] j JSON object to read values from
  10209. @throw type_error.312 if called on JSON values other than objects; example:
  10210. `"cannot use update() with string"`
  10211. @complexity O(N*log(size() + N)), where N is the number of elements to
  10212. insert.
  10213. @liveexample{The example shows how `update()` is used.,update}
  10214. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  10215. @since version 3.0.0
  10216. */
  10217. void update(const_reference j)
  10218. {
  10219. // implicitly convert null value to an empty object
  10220. if (is_null())
  10221. {
  10222. m_type = value_t::object;
  10223. m_value.object = create<object_t>();
  10224. assert_invariant();
  10225. }
  10226. if (JSON_UNLIKELY(not is_object()))
  10227. {
  10228. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  10229. }
  10230. if (JSON_UNLIKELY(not j.is_object()))
  10231. {
  10232. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  10233. }
  10234. for (auto it = j.cbegin(); it != j.cend(); ++it)
  10235. {
  10236. m_value.object->operator[](it.key()) = it.value();
  10237. }
  10238. }
  10239. /*!
  10240. @brief updates a JSON object from another object, overwriting existing keys
  10241. Inserts all values from from range `[first, last)` and overwrites existing
  10242. keys.
  10243. @param[in] first begin of the range of elements to insert
  10244. @param[in] last end of the range of elements to insert
  10245. @throw type_error.312 if called on JSON values other than objects; example:
  10246. `"cannot use update() with string"`
  10247. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  10248. point to an object; example: `"iterators first and last must point to
  10249. objects"`
  10250. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  10251. same JSON value; example: `"iterators do not fit"`
  10252. @complexity O(N*log(size() + N)), where N is the number of elements to
  10253. insert.
  10254. @liveexample{The example shows how `update()` is used__range.,update}
  10255. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  10256. @since version 3.0.0
  10257. */
  10258. void update(const_iterator first, const_iterator last)
  10259. {
  10260. // implicitly convert null value to an empty object
  10261. if (is_null())
  10262. {
  10263. m_type = value_t::object;
  10264. m_value.object = create<object_t>();
  10265. assert_invariant();
  10266. }
  10267. if (JSON_UNLIKELY(not is_object()))
  10268. {
  10269. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  10270. }
  10271. // check if range iterators belong to the same JSON object
  10272. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10273. {
  10274. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10275. }
  10276. // passed iterators must belong to objects
  10277. if (JSON_UNLIKELY(not first.m_object->is_object()
  10278. or not first.m_object->is_object()))
  10279. {
  10280. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  10281. }
  10282. for (auto it = first; it != last; ++it)
  10283. {
  10284. m_value.object->operator[](it.key()) = it.value();
  10285. }
  10286. }
  10287. /*!
  10288. @brief exchanges the values
  10289. Exchanges the contents of the JSON value with those of @a other. Does not
  10290. invoke any move, copy, or swap operations on individual elements. All
  10291. iterators and references remain valid. The past-the-end iterator is
  10292. invalidated.
  10293. @param[in,out] other JSON value to exchange the contents with
  10294. @complexity Constant.
  10295. @liveexample{The example below shows how JSON values can be swapped with
  10296. `swap()`.,swap__reference}
  10297. @since version 1.0.0
  10298. */
  10299. void swap(reference other) noexcept (
  10300. std::is_nothrow_move_constructible<value_t>::value and
  10301. std::is_nothrow_move_assignable<value_t>::value and
  10302. std::is_nothrow_move_constructible<json_value>::value and
  10303. std::is_nothrow_move_assignable<json_value>::value
  10304. )
  10305. {
  10306. std::swap(m_type, other.m_type);
  10307. std::swap(m_value, other.m_value);
  10308. assert_invariant();
  10309. }
  10310. /*!
  10311. @brief exchanges the values
  10312. Exchanges the contents of a JSON array with those of @a other. Does not
  10313. invoke any move, copy, or swap operations on individual elements. All
  10314. iterators and references remain valid. The past-the-end iterator is
  10315. invalidated.
  10316. @param[in,out] other array to exchange the contents with
  10317. @throw type_error.310 when JSON value is not an array; example: `"cannot
  10318. use swap() with string"`
  10319. @complexity Constant.
  10320. @liveexample{The example below shows how arrays can be swapped with
  10321. `swap()`.,swap__array_t}
  10322. @since version 1.0.0
  10323. */
  10324. void swap(array_t& other)
  10325. {
  10326. // swap only works for arrays
  10327. if (JSON_LIKELY(is_array()))
  10328. {
  10329. std::swap(*(m_value.array), other);
  10330. }
  10331. else
  10332. {
  10333. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10334. }
  10335. }
  10336. /*!
  10337. @brief exchanges the values
  10338. Exchanges the contents of a JSON object with those of @a other. Does not
  10339. invoke any move, copy, or swap operations on individual elements. All
  10340. iterators and references remain valid. The past-the-end iterator is
  10341. invalidated.
  10342. @param[in,out] other object to exchange the contents with
  10343. @throw type_error.310 when JSON value is not an object; example:
  10344. `"cannot use swap() with string"`
  10345. @complexity Constant.
  10346. @liveexample{The example below shows how objects can be swapped with
  10347. `swap()`.,swap__object_t}
  10348. @since version 1.0.0
  10349. */
  10350. void swap(object_t& other)
  10351. {
  10352. // swap only works for objects
  10353. if (JSON_LIKELY(is_object()))
  10354. {
  10355. std::swap(*(m_value.object), other);
  10356. }
  10357. else
  10358. {
  10359. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10360. }
  10361. }
  10362. /*!
  10363. @brief exchanges the values
  10364. Exchanges the contents of a JSON string with those of @a other. Does not
  10365. invoke any move, copy, or swap operations on individual elements. All
  10366. iterators and references remain valid. The past-the-end iterator is
  10367. invalidated.
  10368. @param[in,out] other string to exchange the contents with
  10369. @throw type_error.310 when JSON value is not a string; example: `"cannot
  10370. use swap() with boolean"`
  10371. @complexity Constant.
  10372. @liveexample{The example below shows how strings can be swapped with
  10373. `swap()`.,swap__string_t}
  10374. @since version 1.0.0
  10375. */
  10376. void swap(string_t& other)
  10377. {
  10378. // swap only works for strings
  10379. if (JSON_LIKELY(is_string()))
  10380. {
  10381. std::swap(*(m_value.string), other);
  10382. }
  10383. else
  10384. {
  10385. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10386. }
  10387. }
  10388. /// @}
  10389. public:
  10390. //////////////////////////////////////////
  10391. // lexicographical comparison operators //
  10392. //////////////////////////////////////////
  10393. /// @name lexicographical comparison operators
  10394. /// @{
  10395. /*!
  10396. @brief comparison: equal
  10397. Compares two JSON values for equality according to the following rules:
  10398. - Two JSON values are equal if (1) they are from the same type and (2)
  10399. their stored values are the same according to their respective
  10400. `operator==`.
  10401. - Integer and floating-point numbers are automatically converted before
  10402. comparison. Note than two NaN values are always treated as unequal.
  10403. - Two JSON null values are equal.
  10404. @note Floating-point inside JSON values numbers are compared with
  10405. `json::number_float_t::operator==` which is `double::operator==` by
  10406. default. To compare floating-point while respecting an epsilon, an alternative
  10407. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  10408. could be used, for instance
  10409. @code {.cpp}
  10410. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  10411. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  10412. {
  10413. return std::abs(a - b) <= epsilon;
  10414. }
  10415. @endcode
  10416. @note NaN values never compare equal to themselves or to other NaN values.
  10417. @param[in] lhs first JSON value to consider
  10418. @param[in] rhs second JSON value to consider
  10419. @return whether the values @a lhs and @a rhs are equal
  10420. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10421. @complexity Linear.
  10422. @liveexample{The example demonstrates comparing several JSON
  10423. types.,operator__equal}
  10424. @since version 1.0.0
  10425. */
  10426. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  10427. {
  10428. const auto lhs_type = lhs.type();
  10429. const auto rhs_type = rhs.type();
  10430. if (lhs_type == rhs_type)
  10431. {
  10432. switch (lhs_type)
  10433. {
  10434. case value_t::array:
  10435. return (*lhs.m_value.array == *rhs.m_value.array);
  10436. case value_t::object:
  10437. return (*lhs.m_value.object == *rhs.m_value.object);
  10438. case value_t::null:
  10439. return true;
  10440. case value_t::string:
  10441. return (*lhs.m_value.string == *rhs.m_value.string);
  10442. case value_t::boolean:
  10443. return (lhs.m_value.boolean == rhs.m_value.boolean);
  10444. case value_t::number_integer:
  10445. return (lhs.m_value.number_integer == rhs.m_value.number_integer);
  10446. case value_t::number_unsigned:
  10447. return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
  10448. case value_t::number_float:
  10449. return (lhs.m_value.number_float == rhs.m_value.number_float);
  10450. default:
  10451. return false;
  10452. }
  10453. }
  10454. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  10455. {
  10456. return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
  10457. }
  10458. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  10459. {
  10460. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
  10461. }
  10462. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  10463. {
  10464. return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
  10465. }
  10466. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  10467. {
  10468. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
  10469. }
  10470. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  10471. {
  10472. return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
  10473. }
  10474. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  10475. {
  10476. return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
  10477. }
  10478. return false;
  10479. }
  10480. /*!
  10481. @brief comparison: equal
  10482. @copydoc operator==(const_reference, const_reference)
  10483. */
  10484. template<typename ScalarType, typename std::enable_if<
  10485. std::is_scalar<ScalarType>::value, int>::type = 0>
  10486. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  10487. {
  10488. return (lhs == basic_json(rhs));
  10489. }
  10490. /*!
  10491. @brief comparison: equal
  10492. @copydoc operator==(const_reference, const_reference)
  10493. */
  10494. template<typename ScalarType, typename std::enable_if<
  10495. std::is_scalar<ScalarType>::value, int>::type = 0>
  10496. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  10497. {
  10498. return (basic_json(lhs) == rhs);
  10499. }
  10500. /*!
  10501. @brief comparison: not equal
  10502. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  10503. @param[in] lhs first JSON value to consider
  10504. @param[in] rhs second JSON value to consider
  10505. @return whether the values @a lhs and @a rhs are not equal
  10506. @complexity Linear.
  10507. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10508. @liveexample{The example demonstrates comparing several JSON
  10509. types.,operator__notequal}
  10510. @since version 1.0.0
  10511. */
  10512. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  10513. {
  10514. return not (lhs == rhs);
  10515. }
  10516. /*!
  10517. @brief comparison: not equal
  10518. @copydoc operator!=(const_reference, const_reference)
  10519. */
  10520. template<typename ScalarType, typename std::enable_if<
  10521. std::is_scalar<ScalarType>::value, int>::type = 0>
  10522. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  10523. {
  10524. return (lhs != basic_json(rhs));
  10525. }
  10526. /*!
  10527. @brief comparison: not equal
  10528. @copydoc operator!=(const_reference, const_reference)
  10529. */
  10530. template<typename ScalarType, typename std::enable_if<
  10531. std::is_scalar<ScalarType>::value, int>::type = 0>
  10532. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  10533. {
  10534. return (basic_json(lhs) != rhs);
  10535. }
  10536. /*!
  10537. @brief comparison: less than
  10538. Compares whether one JSON value @a lhs is less than another JSON value @a
  10539. rhs according to the following rules:
  10540. - If @a lhs and @a rhs have the same type, the values are compared using
  10541. the default `<` operator.
  10542. - Integer and floating-point numbers are automatically converted before
  10543. comparison
  10544. - In case @a lhs and @a rhs have different types, the values are ignored
  10545. and the order of the types is considered, see
  10546. @ref operator<(const value_t, const value_t).
  10547. @param[in] lhs first JSON value to consider
  10548. @param[in] rhs second JSON value to consider
  10549. @return whether @a lhs is less than @a rhs
  10550. @complexity Linear.
  10551. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10552. @liveexample{The example demonstrates comparing several JSON
  10553. types.,operator__less}
  10554. @since version 1.0.0
  10555. */
  10556. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  10557. {
  10558. const auto lhs_type = lhs.type();
  10559. const auto rhs_type = rhs.type();
  10560. if (lhs_type == rhs_type)
  10561. {
  10562. switch (lhs_type)
  10563. {
  10564. case value_t::array:
  10565. return (*lhs.m_value.array) < (*rhs.m_value.array);
  10566. case value_t::object:
  10567. return *lhs.m_value.object < *rhs.m_value.object;
  10568. case value_t::null:
  10569. return false;
  10570. case value_t::string:
  10571. return *lhs.m_value.string < *rhs.m_value.string;
  10572. case value_t::boolean:
  10573. return lhs.m_value.boolean < rhs.m_value.boolean;
  10574. case value_t::number_integer:
  10575. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  10576. case value_t::number_unsigned:
  10577. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  10578. case value_t::number_float:
  10579. return lhs.m_value.number_float < rhs.m_value.number_float;
  10580. default:
  10581. return false;
  10582. }
  10583. }
  10584. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  10585. {
  10586. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  10587. }
  10588. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  10589. {
  10590. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  10591. }
  10592. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  10593. {
  10594. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  10595. }
  10596. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  10597. {
  10598. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  10599. }
  10600. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  10601. {
  10602. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  10603. }
  10604. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  10605. {
  10606. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  10607. }
  10608. // We only reach this line if we cannot compare values. In that case,
  10609. // we compare types. Note we have to call the operator explicitly,
  10610. // because MSVC has problems otherwise.
  10611. return operator<(lhs_type, rhs_type);
  10612. }
  10613. /*!
  10614. @brief comparison: less than
  10615. @copydoc operator<(const_reference, const_reference)
  10616. */
  10617. template<typename ScalarType, typename std::enable_if<
  10618. std::is_scalar<ScalarType>::value, int>::type = 0>
  10619. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  10620. {
  10621. return (lhs < basic_json(rhs));
  10622. }
  10623. /*!
  10624. @brief comparison: less than
  10625. @copydoc operator<(const_reference, const_reference)
  10626. */
  10627. template<typename ScalarType, typename std::enable_if<
  10628. std::is_scalar<ScalarType>::value, int>::type = 0>
  10629. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  10630. {
  10631. return (basic_json(lhs) < rhs);
  10632. }
  10633. /*!
  10634. @brief comparison: less than or equal
  10635. Compares whether one JSON value @a lhs is less than or equal to another
  10636. JSON value by calculating `not (rhs < lhs)`.
  10637. @param[in] lhs first JSON value to consider
  10638. @param[in] rhs second JSON value to consider
  10639. @return whether @a lhs is less than or equal to @a rhs
  10640. @complexity Linear.
  10641. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10642. @liveexample{The example demonstrates comparing several JSON
  10643. types.,operator__greater}
  10644. @since version 1.0.0
  10645. */
  10646. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  10647. {
  10648. return not (rhs < lhs);
  10649. }
  10650. /*!
  10651. @brief comparison: less than or equal
  10652. @copydoc operator<=(const_reference, const_reference)
  10653. */
  10654. template<typename ScalarType, typename std::enable_if<
  10655. std::is_scalar<ScalarType>::value, int>::type = 0>
  10656. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  10657. {
  10658. return (lhs <= basic_json(rhs));
  10659. }
  10660. /*!
  10661. @brief comparison: less than or equal
  10662. @copydoc operator<=(const_reference, const_reference)
  10663. */
  10664. template<typename ScalarType, typename std::enable_if<
  10665. std::is_scalar<ScalarType>::value, int>::type = 0>
  10666. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  10667. {
  10668. return (basic_json(lhs) <= rhs);
  10669. }
  10670. /*!
  10671. @brief comparison: greater than
  10672. Compares whether one JSON value @a lhs is greater than another
  10673. JSON value by calculating `not (lhs <= rhs)`.
  10674. @param[in] lhs first JSON value to consider
  10675. @param[in] rhs second JSON value to consider
  10676. @return whether @a lhs is greater than to @a rhs
  10677. @complexity Linear.
  10678. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10679. @liveexample{The example demonstrates comparing several JSON
  10680. types.,operator__lessequal}
  10681. @since version 1.0.0
  10682. */
  10683. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  10684. {
  10685. return not (lhs <= rhs);
  10686. }
  10687. /*!
  10688. @brief comparison: greater than
  10689. @copydoc operator>(const_reference, const_reference)
  10690. */
  10691. template<typename ScalarType, typename std::enable_if<
  10692. std::is_scalar<ScalarType>::value, int>::type = 0>
  10693. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  10694. {
  10695. return (lhs > basic_json(rhs));
  10696. }
  10697. /*!
  10698. @brief comparison: greater than
  10699. @copydoc operator>(const_reference, const_reference)
  10700. */
  10701. template<typename ScalarType, typename std::enable_if<
  10702. std::is_scalar<ScalarType>::value, int>::type = 0>
  10703. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  10704. {
  10705. return (basic_json(lhs) > rhs);
  10706. }
  10707. /*!
  10708. @brief comparison: greater than or equal
  10709. Compares whether one JSON value @a lhs is greater than or equal to another
  10710. JSON value by calculating `not (lhs < rhs)`.
  10711. @param[in] lhs first JSON value to consider
  10712. @param[in] rhs second JSON value to consider
  10713. @return whether @a lhs is greater than or equal to @a rhs
  10714. @complexity Linear.
  10715. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10716. @liveexample{The example demonstrates comparing several JSON
  10717. types.,operator__greaterequal}
  10718. @since version 1.0.0
  10719. */
  10720. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  10721. {
  10722. return not (lhs < rhs);
  10723. }
  10724. /*!
  10725. @brief comparison: greater than or equal
  10726. @copydoc operator>=(const_reference, const_reference)
  10727. */
  10728. template<typename ScalarType, typename std::enable_if<
  10729. std::is_scalar<ScalarType>::value, int>::type = 0>
  10730. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  10731. {
  10732. return (lhs >= basic_json(rhs));
  10733. }
  10734. /*!
  10735. @brief comparison: greater than or equal
  10736. @copydoc operator>=(const_reference, const_reference)
  10737. */
  10738. template<typename ScalarType, typename std::enable_if<
  10739. std::is_scalar<ScalarType>::value, int>::type = 0>
  10740. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  10741. {
  10742. return (basic_json(lhs) >= rhs);
  10743. }
  10744. /// @}
  10745. ///////////////////
  10746. // serialization //
  10747. ///////////////////
  10748. /// @name serialization
  10749. /// @{
  10750. /*!
  10751. @brief serialize to stream
  10752. Serialize the given JSON value @a j to the output stream @a o. The JSON
  10753. value will be serialized using the @ref dump member function.
  10754. - The indentation of the output can be controlled with the member variable
  10755. `width` of the output stream @a o. For instance, using the manipulator
  10756. `std::setw(4)` on @a o sets the indentation level to `4` and the
  10757. serialization result is the same as calling `dump(4)`.
  10758. - The indentation character can be controlled with the member variable
  10759. `fill` of the output stream @a o. For instance, the manipulator
  10760. `std::setfill('\\t')` sets indentation to use a tab character rather than
  10761. the default space character.
  10762. @param[in,out] o stream to serialize to
  10763. @param[in] j JSON value to serialize
  10764. @return the stream @a o
  10765. @throw type_error.316 if a string stored inside the JSON value is not
  10766. UTF-8 encoded
  10767. @complexity Linear.
  10768. @liveexample{The example below shows the serialization with different
  10769. parameters to `width` to adjust the indentation level.,operator_serialize}
  10770. @since version 1.0.0; indentation character added in version 3.0.0
  10771. */
  10772. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  10773. {
  10774. // read width member and use it as indentation parameter if nonzero
  10775. const bool pretty_print = (o.width() > 0);
  10776. const auto indentation = (pretty_print ? o.width() : 0);
  10777. // reset width to 0 for subsequent calls to this stream
  10778. o.width(0);
  10779. // do the actual serialization
  10780. serializer s(detail::output_adapter<char>(o), o.fill());
  10781. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  10782. return o;
  10783. }
  10784. /*!
  10785. @brief serialize to stream
  10786. @deprecated This stream operator is deprecated and will be removed in a
  10787. future version of the library. Please use
  10788. @ref operator<<(std::ostream&, const basic_json&)
  10789. instead; that is, replace calls like `j >> o;` with `o << j;`.
  10790. @since version 1.0.0; deprecated since version 3.0.0
  10791. */
  10792. JSON_DEPRECATED
  10793. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  10794. {
  10795. return o << j;
  10796. }
  10797. /// @}
  10798. /////////////////////
  10799. // deserialization //
  10800. /////////////////////
  10801. /// @name deserialization
  10802. /// @{
  10803. /*!
  10804. @brief deserialize from a compatible input
  10805. This function reads from a compatible input. Examples are:
  10806. - an array of 1-byte values
  10807. - strings with character/literal type with size of 1 byte
  10808. - input streams
  10809. - container with contiguous storage of 1-byte values. Compatible container
  10810. types include `std::vector`, `std::string`, `std::array`,
  10811. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  10812. arrays can be used with `std::begin()`/`std::end()`. User-defined
  10813. containers can be used as long as they implement random-access iterators
  10814. and a contiguous storage.
  10815. @pre Each element of the container has a size of 1 byte. Violating this
  10816. precondition yields undefined behavior. **This precondition is enforced
  10817. with a static assertion.**
  10818. @pre The container storage is contiguous. Violating this precondition
  10819. yields undefined behavior. **This precondition is enforced with an
  10820. assertion.**
  10821. @pre Each element of the container has a size of 1 byte. Violating this
  10822. precondition yields undefined behavior. **This precondition is enforced
  10823. with a static assertion.**
  10824. @warning There is no way to enforce all preconditions at compile-time. If
  10825. the function is called with a noncompliant container and with
  10826. assertions switched off, the behavior is undefined and will most
  10827. likely yield segmentation violation.
  10828. @param[in] i input to read from
  10829. @param[in] cb a parser callback function of type @ref parser_callback_t
  10830. which is used to control the deserialization by filtering unwanted values
  10831. (optional)
  10832. @return result of the deserialization
  10833. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  10834. of input; expected string literal""`
  10835. @throw parse_error.102 if to_unicode fails or surrogate error
  10836. @throw parse_error.103 if to_unicode fails
  10837. @complexity Linear in the length of the input. The parser is a predictive
  10838. LL(1) parser. The complexity can be higher if the parser callback function
  10839. @a cb has a super-linear complexity.
  10840. @note A UTF-8 byte order mark is silently ignored.
  10841. @liveexample{The example below demonstrates the `parse()` function reading
  10842. from an array.,parse__array__parser_callback_t}
  10843. @liveexample{The example below demonstrates the `parse()` function with
  10844. and without callback function.,parse__string__parser_callback_t}
  10845. @liveexample{The example below demonstrates the `parse()` function with
  10846. and without callback function.,parse__istream__parser_callback_t}
  10847. @liveexample{The example below demonstrates the `parse()` function reading
  10848. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  10849. @since version 2.0.3 (contiguous containers)
  10850. */
  10851. static basic_json parse(detail::input_adapter i,
  10852. const parser_callback_t cb = nullptr,
  10853. const bool allow_exceptions = true)
  10854. {
  10855. basic_json result;
  10856. parser(i, cb, allow_exceptions).parse(true, result);
  10857. return result;
  10858. }
  10859. /*!
  10860. @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
  10861. */
  10862. static basic_json parse(detail::input_adapter& i,
  10863. const parser_callback_t cb = nullptr,
  10864. const bool allow_exceptions = true)
  10865. {
  10866. basic_json result;
  10867. parser(i, cb, allow_exceptions).parse(true, result);
  10868. return result;
  10869. }
  10870. static bool accept(detail::input_adapter i)
  10871. {
  10872. return parser(i).accept(true);
  10873. }
  10874. static bool accept(detail::input_adapter& i)
  10875. {
  10876. return parser(i).accept(true);
  10877. }
  10878. /*!
  10879. @brief deserialize from an iterator range with contiguous storage
  10880. This function reads from an iterator range of a container with contiguous
  10881. storage of 1-byte values. Compatible container types include
  10882. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  10883. `std::initializer_list`. Furthermore, C-style arrays can be used with
  10884. `std::begin()`/`std::end()`. User-defined containers can be used as long
  10885. as they implement random-access iterators and a contiguous storage.
  10886. @pre The iterator range is contiguous. Violating this precondition yields
  10887. undefined behavior. **This precondition is enforced with an assertion.**
  10888. @pre Each element in the range has a size of 1 byte. Violating this
  10889. precondition yields undefined behavior. **This precondition is enforced
  10890. with a static assertion.**
  10891. @warning There is no way to enforce all preconditions at compile-time. If
  10892. the function is called with noncompliant iterators and with
  10893. assertions switched off, the behavior is undefined and will most
  10894. likely yield segmentation violation.
  10895. @tparam IteratorType iterator of container with contiguous storage
  10896. @param[in] first begin of the range to parse (included)
  10897. @param[in] last end of the range to parse (excluded)
  10898. @param[in] cb a parser callback function of type @ref parser_callback_t
  10899. which is used to control the deserialization by filtering unwanted values
  10900. (optional)
  10901. @param[in] allow_exceptions whether to throw exceptions in case of a
  10902. parse error (optional, true by default)
  10903. @return result of the deserialization
  10904. @throw parse_error.101 in case of an unexpected token
  10905. @throw parse_error.102 if to_unicode fails or surrogate error
  10906. @throw parse_error.103 if to_unicode fails
  10907. @complexity Linear in the length of the input. The parser is a predictive
  10908. LL(1) parser. The complexity can be higher if the parser callback function
  10909. @a cb has a super-linear complexity.
  10910. @note A UTF-8 byte order mark is silently ignored.
  10911. @liveexample{The example below demonstrates the `parse()` function reading
  10912. from an iterator range.,parse__iteratortype__parser_callback_t}
  10913. @since version 2.0.3
  10914. */
  10915. template<class IteratorType, typename std::enable_if<
  10916. std::is_base_of<
  10917. std::random_access_iterator_tag,
  10918. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  10919. static basic_json parse(IteratorType first, IteratorType last,
  10920. const parser_callback_t cb = nullptr,
  10921. const bool allow_exceptions = true)
  10922. {
  10923. basic_json result;
  10924. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  10925. return result;
  10926. }
  10927. template<class IteratorType, typename std::enable_if<
  10928. std::is_base_of<
  10929. std::random_access_iterator_tag,
  10930. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  10931. static bool accept(IteratorType first, IteratorType last)
  10932. {
  10933. return parser(detail::input_adapter(first, last)).accept(true);
  10934. }
  10935. /*!
  10936. @brief deserialize from stream
  10937. @deprecated This stream operator is deprecated and will be removed in a
  10938. future version of the library. Please use
  10939. @ref operator>>(std::istream&, basic_json&)
  10940. instead; that is, replace calls like `j << i;` with `i >> j;`.
  10941. @since version 1.0.0; deprecated since version 3.0.0
  10942. */
  10943. JSON_DEPRECATED
  10944. friend std::istream& operator<<(basic_json& j, std::istream& i)
  10945. {
  10946. return operator>>(i, j);
  10947. }
  10948. /*!
  10949. @brief deserialize from stream
  10950. Deserializes an input stream to a JSON value.
  10951. @param[in,out] i input stream to read a serialized JSON value from
  10952. @param[in,out] j JSON value to write the deserialized input to
  10953. @throw parse_error.101 in case of an unexpected token
  10954. @throw parse_error.102 if to_unicode fails or surrogate error
  10955. @throw parse_error.103 if to_unicode fails
  10956. @complexity Linear in the length of the input. The parser is a predictive
  10957. LL(1) parser.
  10958. @note A UTF-8 byte order mark is silently ignored.
  10959. @liveexample{The example below shows how a JSON value is constructed by
  10960. reading a serialization from a stream.,operator_deserialize}
  10961. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  10962. parser callback function to filter values while parsing
  10963. @since version 1.0.0
  10964. */
  10965. friend std::istream& operator>>(std::istream& i, basic_json& j)
  10966. {
  10967. parser(detail::input_adapter(i)).parse(false, j);
  10968. return i;
  10969. }
  10970. /// @}
  10971. ///////////////////////////
  10972. // convenience functions //
  10973. ///////////////////////////
  10974. /*!
  10975. @brief return the type as string
  10976. Returns the type name as string to be used in error messages - usually to
  10977. indicate that a function was called on a wrong JSON type.
  10978. @return a string representation of a the @a m_type member:
  10979. Value type | return value
  10980. ----------- | -------------
  10981. null | `"null"`
  10982. boolean | `"boolean"`
  10983. string | `"string"`
  10984. number | `"number"` (for all number types)
  10985. object | `"object"`
  10986. array | `"array"`
  10987. discarded | `"discarded"`
  10988. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10989. @complexity Constant.
  10990. @liveexample{The following code exemplifies `type_name()` for all JSON
  10991. types.,type_name}
  10992. @sa @ref type() -- return the type of the JSON value
  10993. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  10994. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  10995. since 3.0.0
  10996. */
  10997. const char* type_name() const noexcept
  10998. {
  10999. {
  11000. switch (m_type)
  11001. {
  11002. case value_t::null:
  11003. return "null";
  11004. case value_t::object:
  11005. return "object";
  11006. case value_t::array:
  11007. return "array";
  11008. case value_t::string:
  11009. return "string";
  11010. case value_t::boolean:
  11011. return "boolean";
  11012. case value_t::discarded:
  11013. return "discarded";
  11014. default:
  11015. return "number";
  11016. }
  11017. }
  11018. }
  11019. private:
  11020. //////////////////////
  11021. // member variables //
  11022. //////////////////////
  11023. /// the type of the current element
  11024. value_t m_type = value_t::null;
  11025. /// the value of the current element
  11026. json_value m_value = {};
  11027. //////////////////////////////////////////
  11028. // binary serialization/deserialization //
  11029. //////////////////////////////////////////
  11030. /// @name binary serialization/deserialization support
  11031. /// @{
  11032. public:
  11033. /*!
  11034. @brief create a CBOR serialization of a given JSON value
  11035. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  11036. Binary Object Representation) serialization format. CBOR is a binary
  11037. serialization format which aims to be more compact than JSON itself, yet
  11038. more efficient to parse.
  11039. The library uses the following mapping from JSON values types to
  11040. CBOR types according to the CBOR specification (RFC 7049):
  11041. JSON value type | value/range | CBOR type | first byte
  11042. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  11043. null | `null` | Null | 0xF6
  11044. boolean | `true` | True | 0xF5
  11045. boolean | `false` | False | 0xF4
  11046. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  11047. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  11048. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  11049. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  11050. number_integer | -24..-1 | Negative integer | 0x20..0x37
  11051. number_integer | 0..23 | Integer | 0x00..0x17
  11052. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  11053. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  11054. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  11055. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  11056. number_unsigned | 0..23 | Integer | 0x00..0x17
  11057. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  11058. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  11059. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  11060. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  11061. number_float | *any value* | Double-Precision Float | 0xFB
  11062. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  11063. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  11064. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  11065. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  11066. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  11067. array | *size*: 0..23 | array | 0x80..0x97
  11068. array | *size*: 23..255 | array (1 byte follow) | 0x98
  11069. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  11070. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  11071. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  11072. object | *size*: 0..23 | map | 0xA0..0xB7
  11073. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  11074. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  11075. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  11076. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  11077. @note The mapping is **complete** in the sense that any JSON value type
  11078. can be converted to a CBOR value.
  11079. @note If NaN or Infinity are stored inside a JSON number, they are
  11080. serialized properly. This behavior differs from the @ref dump()
  11081. function which serializes NaN or Infinity to `null`.
  11082. @note The following CBOR types are not used in the conversion:
  11083. - byte strings (0x40..0x5F)
  11084. - UTF-8 strings terminated by "break" (0x7F)
  11085. - arrays terminated by "break" (0x9F)
  11086. - maps terminated by "break" (0xBF)
  11087. - date/time (0xC0..0xC1)
  11088. - bignum (0xC2..0xC3)
  11089. - decimal fraction (0xC4)
  11090. - bigfloat (0xC5)
  11091. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  11092. - expected conversions (0xD5..0xD7)
  11093. - simple values (0xE0..0xF3, 0xF8)
  11094. - undefined (0xF7)
  11095. - half and single-precision floats (0xF9-0xFA)
  11096. - break (0xFF)
  11097. @param[in] j JSON value to serialize
  11098. @return MessagePack serialization as byte vector
  11099. @complexity Linear in the size of the JSON value @a j.
  11100. @liveexample{The example shows the serialization of a JSON value to a byte
  11101. vector in CBOR format.,to_cbor}
  11102. @sa http://cbor.io
  11103. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  11104. analogous deserialization
  11105. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  11106. @since version 2.0.9
  11107. */
  11108. static std::vector<uint8_t> to_cbor(const basic_json& j)
  11109. {
  11110. std::vector<uint8_t> result;
  11111. to_cbor(j, result);
  11112. return result;
  11113. }
  11114. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  11115. {
  11116. binary_writer<uint8_t>(o).write_cbor(j);
  11117. }
  11118. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  11119. {
  11120. binary_writer<char>(o).write_cbor(j);
  11121. }
  11122. /*!
  11123. @brief create a MessagePack serialization of a given JSON value
  11124. Serializes a given JSON value @a j to a byte vector using the MessagePack
  11125. serialization format. MessagePack is a binary serialization format which
  11126. aims to be more compact than JSON itself, yet more efficient to parse.
  11127. The library uses the following mapping from JSON values types to
  11128. MessagePack types according to the MessagePack specification:
  11129. JSON value type | value/range | MessagePack type | first byte
  11130. --------------- | --------------------------------- | ---------------- | ----------
  11131. null | `null` | nil | 0xC0
  11132. boolean | `true` | true | 0xC3
  11133. boolean | `false` | false | 0xC2
  11134. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  11135. number_integer | -2147483648..-32769 | int32 | 0xD2
  11136. number_integer | -32768..-129 | int16 | 0xD1
  11137. number_integer | -128..-33 | int8 | 0xD0
  11138. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  11139. number_integer | 0..127 | positive fixint | 0x00..0x7F
  11140. number_integer | 128..255 | uint 8 | 0xCC
  11141. number_integer | 256..65535 | uint 16 | 0xCD
  11142. number_integer | 65536..4294967295 | uint 32 | 0xCE
  11143. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  11144. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  11145. number_unsigned | 128..255 | uint 8 | 0xCC
  11146. number_unsigned | 256..65535 | uint 16 | 0xCD
  11147. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  11148. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  11149. number_float | *any value* | float 64 | 0xCB
  11150. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  11151. string | *length*: 32..255 | str 8 | 0xD9
  11152. string | *length*: 256..65535 | str 16 | 0xDA
  11153. string | *length*: 65536..4294967295 | str 32 | 0xDB
  11154. array | *size*: 0..15 | fixarray | 0x90..0x9F
  11155. array | *size*: 16..65535 | array 16 | 0xDC
  11156. array | *size*: 65536..4294967295 | array 32 | 0xDD
  11157. object | *size*: 0..15 | fix map | 0x80..0x8F
  11158. object | *size*: 16..65535 | map 16 | 0xDE
  11159. object | *size*: 65536..4294967295 | map 32 | 0xDF
  11160. @note The mapping is **complete** in the sense that any JSON value type
  11161. can be converted to a MessagePack value.
  11162. @note The following values can **not** be converted to a MessagePack value:
  11163. - strings with more than 4294967295 bytes
  11164. - arrays with more than 4294967295 elements
  11165. - objects with more than 4294967295 elements
  11166. @note The following MessagePack types are not used in the conversion:
  11167. - bin 8 - bin 32 (0xC4..0xC6)
  11168. - ext 8 - ext 32 (0xC7..0xC9)
  11169. - float 32 (0xCA)
  11170. - fixext 1 - fixext 16 (0xD4..0xD8)
  11171. @note Any MessagePack output created @ref to_msgpack can be successfully
  11172. parsed by @ref from_msgpack.
  11173. @note If NaN or Infinity are stored inside a JSON number, they are
  11174. serialized properly. This behavior differs from the @ref dump()
  11175. function which serializes NaN or Infinity to `null`.
  11176. @param[in] j JSON value to serialize
  11177. @return MessagePack serialization as byte vector
  11178. @complexity Linear in the size of the JSON value @a j.
  11179. @liveexample{The example shows the serialization of a JSON value to a byte
  11180. vector in MessagePack format.,to_msgpack}
  11181. @sa http://msgpack.org
  11182. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  11183. analogous deserialization
  11184. @sa @ref to_cbor(const basic_json& for the related CBOR format
  11185. @since version 2.0.9
  11186. */
  11187. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  11188. {
  11189. std::vector<uint8_t> result;
  11190. to_msgpack(j, result);
  11191. return result;
  11192. }
  11193. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  11194. {
  11195. binary_writer<uint8_t>(o).write_msgpack(j);
  11196. }
  11197. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  11198. {
  11199. binary_writer<char>(o).write_msgpack(j);
  11200. }
  11201. /*!
  11202. @brief create a JSON value from an input in CBOR format
  11203. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  11204. Binary Object Representation) serialization format.
  11205. The library maps CBOR types to JSON value types as follows:
  11206. CBOR type | JSON value type | first byte
  11207. ---------------------- | --------------- | ----------
  11208. Integer | number_unsigned | 0x00..0x17
  11209. Unsigned integer | number_unsigned | 0x18
  11210. Unsigned integer | number_unsigned | 0x19
  11211. Unsigned integer | number_unsigned | 0x1A
  11212. Unsigned integer | number_unsigned | 0x1B
  11213. Negative integer | number_integer | 0x20..0x37
  11214. Negative integer | number_integer | 0x38
  11215. Negative integer | number_integer | 0x39
  11216. Negative integer | number_integer | 0x3A
  11217. Negative integer | number_integer | 0x3B
  11218. Negative integer | number_integer | 0x40..0x57
  11219. UTF-8 string | string | 0x60..0x77
  11220. UTF-8 string | string | 0x78
  11221. UTF-8 string | string | 0x79
  11222. UTF-8 string | string | 0x7A
  11223. UTF-8 string | string | 0x7B
  11224. UTF-8 string | string | 0x7F
  11225. array | array | 0x80..0x97
  11226. array | array | 0x98
  11227. array | array | 0x99
  11228. array | array | 0x9A
  11229. array | array | 0x9B
  11230. array | array | 0x9F
  11231. map | object | 0xA0..0xB7
  11232. map | object | 0xB8
  11233. map | object | 0xB9
  11234. map | object | 0xBA
  11235. map | object | 0xBB
  11236. map | object | 0xBF
  11237. False | `false` | 0xF4
  11238. True | `true` | 0xF5
  11239. Nill | `null` | 0xF6
  11240. Half-Precision Float | number_float | 0xF9
  11241. Single-Precision Float | number_float | 0xFA
  11242. Double-Precision Float | number_float | 0xFB
  11243. @warning The mapping is **incomplete** in the sense that not all CBOR
  11244. types can be converted to a JSON value. The following CBOR types
  11245. are not supported and will yield parse errors (parse_error.112):
  11246. - byte strings (0x40..0x5F)
  11247. - date/time (0xC0..0xC1)
  11248. - bignum (0xC2..0xC3)
  11249. - decimal fraction (0xC4)
  11250. - bigfloat (0xC5)
  11251. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  11252. - expected conversions (0xD5..0xD7)
  11253. - simple values (0xE0..0xF3, 0xF8)
  11254. - undefined (0xF7)
  11255. @warning CBOR allows map keys of any type, whereas JSON only allows
  11256. strings as keys in object values. Therefore, CBOR maps with keys
  11257. other than UTF-8 strings are rejected (parse_error.113).
  11258. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  11259. @ref from_cbor.
  11260. @param[in] i an input in CBOR format convertible to an input adapter
  11261. @param[in] strict whether to expect the input to be consumed until EOF
  11262. (true by default)
  11263. @return deserialized JSON value
  11264. @throw parse_error.110 if the given input ends prematurely or the end of
  11265. file was not reached when @a strict was set to true
  11266. @throw parse_error.112 if unsupported features from CBOR were
  11267. used in the given input @a v or if the input is not valid CBOR
  11268. @throw parse_error.113 if a string was expected as map key, but not found
  11269. @complexity Linear in the size of the input @a i.
  11270. @liveexample{The example shows the deserialization of a byte vector in CBOR
  11271. format to a JSON value.,from_cbor}
  11272. @sa http://cbor.io
  11273. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  11274. @sa @ref from_msgpack(detail::input_adapter, const bool) for the
  11275. related MessagePack format
  11276. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  11277. consume input adapters, removed start_index parameter, and added
  11278. @a strict parameter since 3.0.0
  11279. */
  11280. static basic_json from_cbor(detail::input_adapter i,
  11281. const bool strict = true)
  11282. {
  11283. return binary_reader(i).parse_cbor(strict);
  11284. }
  11285. /*!
  11286. @copydoc from_cbor(detail::input_adapter, const bool)
  11287. */
  11288. template<typename A1, typename A2,
  11289. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  11290. static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
  11291. {
  11292. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
  11293. }
  11294. /*!
  11295. @brief create a JSON value from an input in MessagePack format
  11296. Deserializes a given input @a i to a JSON value using the MessagePack
  11297. serialization format.
  11298. The library maps MessagePack types to JSON value types as follows:
  11299. MessagePack type | JSON value type | first byte
  11300. ---------------- | --------------- | ----------
  11301. positive fixint | number_unsigned | 0x00..0x7F
  11302. fixmap | object | 0x80..0x8F
  11303. fixarray | array | 0x90..0x9F
  11304. fixstr | string | 0xA0..0xBF
  11305. nil | `null` | 0xC0
  11306. false | `false` | 0xC2
  11307. true | `true` | 0xC3
  11308. float 32 | number_float | 0xCA
  11309. float 64 | number_float | 0xCB
  11310. uint 8 | number_unsigned | 0xCC
  11311. uint 16 | number_unsigned | 0xCD
  11312. uint 32 | number_unsigned | 0xCE
  11313. uint 64 | number_unsigned | 0xCF
  11314. int 8 | number_integer | 0xD0
  11315. int 16 | number_integer | 0xD1
  11316. int 32 | number_integer | 0xD2
  11317. int 64 | number_integer | 0xD3
  11318. str 8 | string | 0xD9
  11319. str 16 | string | 0xDA
  11320. str 32 | string | 0xDB
  11321. array 16 | array | 0xDC
  11322. array 32 | array | 0xDD
  11323. map 16 | object | 0xDE
  11324. map 32 | object | 0xDF
  11325. negative fixint | number_integer | 0xE0-0xFF
  11326. @warning The mapping is **incomplete** in the sense that not all
  11327. MessagePack types can be converted to a JSON value. The following
  11328. MessagePack types are not supported and will yield parse errors:
  11329. - bin 8 - bin 32 (0xC4..0xC6)
  11330. - ext 8 - ext 32 (0xC7..0xC9)
  11331. - fixext 1 - fixext 16 (0xD4..0xD8)
  11332. @note Any MessagePack output created @ref to_msgpack can be successfully
  11333. parsed by @ref from_msgpack.
  11334. @param[in] i an input in MessagePack format convertible to an input
  11335. adapter
  11336. @param[in] strict whether to expect the input to be consumed until EOF
  11337. (true by default)
  11338. @throw parse_error.110 if the given input ends prematurely or the end of
  11339. file was not reached when @a strict was set to true
  11340. @throw parse_error.112 if unsupported features from MessagePack were
  11341. used in the given input @a i or if the input is not valid MessagePack
  11342. @throw parse_error.113 if a string was expected as map key, but not found
  11343. @complexity Linear in the size of the input @a i.
  11344. @liveexample{The example shows the deserialization of a byte vector in
  11345. MessagePack format to a JSON value.,from_msgpack}
  11346. @sa http://msgpack.org
  11347. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  11348. @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
  11349. format
  11350. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  11351. consume input adapters, removed start_index parameter, and added
  11352. @a strict parameter since 3.0.0
  11353. */
  11354. static basic_json from_msgpack(detail::input_adapter i,
  11355. const bool strict = true)
  11356. {
  11357. return binary_reader(i).parse_msgpack(strict);
  11358. }
  11359. /*!
  11360. @copydoc from_msgpack(detail::input_adapter, const bool)
  11361. */
  11362. template<typename A1, typename A2,
  11363. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  11364. static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
  11365. {
  11366. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
  11367. }
  11368. /// @}
  11369. //////////////////////////
  11370. // JSON Pointer support //
  11371. //////////////////////////
  11372. /// @name JSON Pointer functions
  11373. /// @{
  11374. /*!
  11375. @brief access specified element via JSON Pointer
  11376. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11377. No bound checking is performed. Similar to @ref operator[](const typename
  11378. object_t::key_type&), `null` values are created in arrays and objects if
  11379. necessary.
  11380. In particular:
  11381. - If the JSON pointer points to an object key that does not exist, it
  11382. is created an filled with a `null` value before a reference to it
  11383. is returned.
  11384. - If the JSON pointer points to an array index that does not exist, it
  11385. is created an filled with a `null` value before a reference to it
  11386. is returned. All indices between the current maximum and the given
  11387. index are also filled with `null`.
  11388. - The special value `-` is treated as a synonym for the index past the
  11389. end.
  11390. @param[in] ptr a JSON pointer
  11391. @return reference to the element pointed to by @a ptr
  11392. @complexity Constant.
  11393. @throw parse_error.106 if an array index begins with '0'
  11394. @throw parse_error.109 if an array index was not a number
  11395. @throw out_of_range.404 if the JSON pointer can not be resolved
  11396. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  11397. @since version 2.0.0
  11398. */
  11399. reference operator[](const json_pointer& ptr)
  11400. {
  11401. return ptr.get_unchecked(this);
  11402. }
  11403. /*!
  11404. @brief access specified element via JSON Pointer
  11405. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11406. No bound checking is performed. The function does not change the JSON
  11407. value; no `null` values are created. In particular, the the special value
  11408. `-` yields an exception.
  11409. @param[in] ptr JSON pointer to the desired element
  11410. @return const reference to the element pointed to by @a ptr
  11411. @complexity Constant.
  11412. @throw parse_error.106 if an array index begins with '0'
  11413. @throw parse_error.109 if an array index was not a number
  11414. @throw out_of_range.402 if the array index '-' is used
  11415. @throw out_of_range.404 if the JSON pointer can not be resolved
  11416. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  11417. @since version 2.0.0
  11418. */
  11419. const_reference operator[](const json_pointer& ptr) const
  11420. {
  11421. return ptr.get_unchecked(this);
  11422. }
  11423. /*!
  11424. @brief access specified element via JSON Pointer
  11425. Returns a reference to the element at with specified JSON pointer @a ptr,
  11426. with bounds checking.
  11427. @param[in] ptr JSON pointer to the desired element
  11428. @return reference to the element pointed to by @a ptr
  11429. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11430. begins with '0'. See example below.
  11431. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11432. is not a number. See example below.
  11433. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11434. is out of range. See example below.
  11435. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11436. pointer @a ptr. As `at` provides checked access (and no elements are
  11437. implicitly inserted), the index '-' is always invalid. See example below.
  11438. @throw out_of_range.403 if the JSON pointer describes a key of an object
  11439. which cannot be found. See example below.
  11440. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11441. See example below.
  11442. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11443. changes in the JSON value.
  11444. @complexity Constant.
  11445. @since version 2.0.0
  11446. @liveexample{The behavior is shown in the example.,at_json_pointer}
  11447. */
  11448. reference at(const json_pointer& ptr)
  11449. {
  11450. return ptr.get_checked(this);
  11451. }
  11452. /*!
  11453. @brief access specified element via JSON Pointer
  11454. Returns a const reference to the element at with specified JSON pointer @a
  11455. ptr, with bounds checking.
  11456. @param[in] ptr JSON pointer to the desired element
  11457. @return reference to the element pointed to by @a ptr
  11458. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11459. begins with '0'. See example below.
  11460. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11461. is not a number. See example below.
  11462. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11463. is out of range. See example below.
  11464. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11465. pointer @a ptr. As `at` provides checked access (and no elements are
  11466. implicitly inserted), the index '-' is always invalid. See example below.
  11467. @throw out_of_range.403 if the JSON pointer describes a key of an object
  11468. which cannot be found. See example below.
  11469. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11470. See example below.
  11471. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11472. changes in the JSON value.
  11473. @complexity Constant.
  11474. @since version 2.0.0
  11475. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  11476. */
  11477. const_reference at(const json_pointer& ptr) const
  11478. {
  11479. return ptr.get_checked(this);
  11480. }
  11481. /*!
  11482. @brief return flattened JSON value
  11483. The function creates a JSON object whose keys are JSON pointers (see [RFC
  11484. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  11485. primitive. The original JSON value can be restored using the @ref
  11486. unflatten() function.
  11487. @return an object that maps JSON pointers to primitive values
  11488. @note Empty objects and arrays are flattened to `null` and will not be
  11489. reconstructed correctly by the @ref unflatten() function.
  11490. @complexity Linear in the size the JSON value.
  11491. @liveexample{The following code shows how a JSON object is flattened to an
  11492. object whose keys consist of JSON pointers.,flatten}
  11493. @sa @ref unflatten() for the reverse function
  11494. @since version 2.0.0
  11495. */
  11496. basic_json flatten() const
  11497. {
  11498. basic_json result(value_t::object);
  11499. json_pointer::flatten("", *this, result);
  11500. return result;
  11501. }
  11502. /*!
  11503. @brief unflatten a previously flattened JSON value
  11504. The function restores the arbitrary nesting of a JSON value that has been
  11505. flattened before using the @ref flatten() function. The JSON value must
  11506. meet certain constraints:
  11507. 1. The value must be an object.
  11508. 2. The keys must be JSON pointers (see
  11509. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  11510. 3. The mapped values must be primitive JSON types.
  11511. @return the original JSON from a flattened version
  11512. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  11513. values and can not unflattened to their original type. Apart from
  11514. this example, for a JSON value `j`, the following is always true:
  11515. `j == j.flatten().unflatten()`.
  11516. @complexity Linear in the size the JSON value.
  11517. @throw type_error.314 if value is not an object
  11518. @throw type_error.315 if object values are not primitive
  11519. @liveexample{The following code shows how a flattened JSON object is
  11520. unflattened into the original nested JSON object.,unflatten}
  11521. @sa @ref flatten() for the reverse function
  11522. @since version 2.0.0
  11523. */
  11524. basic_json unflatten() const
  11525. {
  11526. return json_pointer::unflatten(*this);
  11527. }
  11528. /// @}
  11529. //////////////////////////
  11530. // JSON Patch functions //
  11531. //////////////////////////
  11532. /// @name JSON Patch functions
  11533. /// @{
  11534. /*!
  11535. @brief applies a JSON patch
  11536. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  11537. expressing a sequence of operations to apply to a JSON) document. With
  11538. this function, a JSON Patch is applied to the current JSON value by
  11539. executing all operations from the patch.
  11540. @param[in] json_patch JSON patch document
  11541. @return patched document
  11542. @note The application of a patch is atomic: Either all operations succeed
  11543. and the patched document is returned or an exception is thrown. In
  11544. any case, the original value is not changed: the patch is applied
  11545. to a copy of the value.
  11546. @throw parse_error.104 if the JSON patch does not consist of an array of
  11547. objects
  11548. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  11549. attributes are missing); example: `"operation add must have member path"`
  11550. @throw out_of_range.401 if an array index is out of range.
  11551. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  11552. resolved successfully in the current JSON value; example: `"key baz not
  11553. found"`
  11554. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  11555. "move")
  11556. @throw other_error.501 if "test" operation was unsuccessful
  11557. @complexity Linear in the size of the JSON value and the length of the
  11558. JSON patch. As usually only a fraction of the JSON value is affected by
  11559. the patch, the complexity can usually be neglected.
  11560. @liveexample{The following code shows how a JSON patch is applied to a
  11561. value.,patch}
  11562. @sa @ref diff -- create a JSON patch by comparing two JSON values
  11563. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11564. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  11565. @since version 2.0.0
  11566. */
  11567. basic_json patch(const basic_json& json_patch) const
  11568. {
  11569. // make a working copy to apply the patch to
  11570. basic_json result = *this;
  11571. // the valid JSON Patch operations
  11572. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  11573. const auto get_op = [](const std::string & op)
  11574. {
  11575. if (op == "add")
  11576. {
  11577. return patch_operations::add;
  11578. }
  11579. if (op == "remove")
  11580. {
  11581. return patch_operations::remove;
  11582. }
  11583. if (op == "replace")
  11584. {
  11585. return patch_operations::replace;
  11586. }
  11587. if (op == "move")
  11588. {
  11589. return patch_operations::move;
  11590. }
  11591. if (op == "copy")
  11592. {
  11593. return patch_operations::copy;
  11594. }
  11595. if (op == "test")
  11596. {
  11597. return patch_operations::test;
  11598. }
  11599. return patch_operations::invalid;
  11600. };
  11601. // wrapper for "add" operation; add value at ptr
  11602. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  11603. {
  11604. // adding to the root of the target document means replacing it
  11605. if (ptr.is_root())
  11606. {
  11607. result = val;
  11608. }
  11609. else
  11610. {
  11611. // make sure the top element of the pointer exists
  11612. json_pointer top_pointer = ptr.top();
  11613. if (top_pointer != ptr)
  11614. {
  11615. result.at(top_pointer);
  11616. }
  11617. // get reference to parent of JSON pointer ptr
  11618. const auto last_path = ptr.pop_back();
  11619. basic_json& parent = result[ptr];
  11620. switch (parent.m_type)
  11621. {
  11622. case value_t::null:
  11623. case value_t::object:
  11624. {
  11625. // use operator[] to add value
  11626. parent[last_path] = val;
  11627. break;
  11628. }
  11629. case value_t::array:
  11630. {
  11631. if (last_path == "-")
  11632. {
  11633. // special case: append to back
  11634. parent.push_back(val);
  11635. }
  11636. else
  11637. {
  11638. const auto idx = json_pointer::array_index(last_path);
  11639. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  11640. {
  11641. // avoid undefined behavior
  11642. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11643. }
  11644. else
  11645. {
  11646. // default case: insert add offset
  11647. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  11648. }
  11649. }
  11650. break;
  11651. }
  11652. default:
  11653. {
  11654. // if there exists a parent it cannot be primitive
  11655. assert(false); // LCOV_EXCL_LINE
  11656. }
  11657. }
  11658. }
  11659. };
  11660. // wrapper for "remove" operation; remove value at ptr
  11661. const auto operation_remove = [&result](json_pointer & ptr)
  11662. {
  11663. // get reference to parent of JSON pointer ptr
  11664. const auto last_path = ptr.pop_back();
  11665. basic_json& parent = result.at(ptr);
  11666. // remove child
  11667. if (parent.is_object())
  11668. {
  11669. // perform range check
  11670. auto it = parent.find(last_path);
  11671. if (JSON_LIKELY(it != parent.end()))
  11672. {
  11673. parent.erase(it);
  11674. }
  11675. else
  11676. {
  11677. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  11678. }
  11679. }
  11680. else if (parent.is_array())
  11681. {
  11682. // note erase performs range check
  11683. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  11684. }
  11685. };
  11686. // type check: top level value must be an array
  11687. if (JSON_UNLIKELY(not json_patch.is_array()))
  11688. {
  11689. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11690. }
  11691. // iterate and apply the operations
  11692. for (const auto& val : json_patch)
  11693. {
  11694. // wrapper to get a value for an operation
  11695. const auto get_value = [&val](const std::string & op,
  11696. const std::string & member,
  11697. bool string_type) -> basic_json&
  11698. {
  11699. // find value
  11700. auto it = val.m_value.object->find(member);
  11701. // context-sensitive error message
  11702. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  11703. // check if desired value is present
  11704. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  11705. {
  11706. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  11707. }
  11708. // check if result is of type string
  11709. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  11710. {
  11711. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  11712. }
  11713. // no error: return value
  11714. return it->second;
  11715. };
  11716. // type check: every element of the array must be an object
  11717. if (JSON_UNLIKELY(not val.is_object()))
  11718. {
  11719. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11720. }
  11721. // collect mandatory members
  11722. const std::string op = get_value("op", "op", true);
  11723. const std::string path = get_value(op, "path", true);
  11724. json_pointer ptr(path);
  11725. switch (get_op(op))
  11726. {
  11727. case patch_operations::add:
  11728. {
  11729. operation_add(ptr, get_value("add", "value", false));
  11730. break;
  11731. }
  11732. case patch_operations::remove:
  11733. {
  11734. operation_remove(ptr);
  11735. break;
  11736. }
  11737. case patch_operations::replace:
  11738. {
  11739. // the "path" location must exist - use at()
  11740. result.at(ptr) = get_value("replace", "value", false);
  11741. break;
  11742. }
  11743. case patch_operations::move:
  11744. {
  11745. const std::string from_path = get_value("move", "from", true);
  11746. json_pointer from_ptr(from_path);
  11747. // the "from" location must exist - use at()
  11748. basic_json v = result.at(from_ptr);
  11749. // The move operation is functionally identical to a
  11750. // "remove" operation on the "from" location, followed
  11751. // immediately by an "add" operation at the target
  11752. // location with the value that was just removed.
  11753. operation_remove(from_ptr);
  11754. operation_add(ptr, v);
  11755. break;
  11756. }
  11757. case patch_operations::copy:
  11758. {
  11759. const std::string from_path = get_value("copy", "from", true);
  11760. const json_pointer from_ptr(from_path);
  11761. // the "from" location must exist - use at()
  11762. basic_json v = result.at(from_ptr);
  11763. // The copy is functionally identical to an "add"
  11764. // operation at the target location using the value
  11765. // specified in the "from" member.
  11766. operation_add(ptr, v);
  11767. break;
  11768. }
  11769. case patch_operations::test:
  11770. {
  11771. bool success = false;
  11772. JSON_TRY
  11773. {
  11774. // check if "value" matches the one at "path"
  11775. // the "path" location must exist - use at()
  11776. success = (result.at(ptr) == get_value("test", "value", false));
  11777. }
  11778. JSON_CATCH (out_of_range&)
  11779. {
  11780. // ignore out of range errors: success remains false
  11781. }
  11782. // throw an exception if test fails
  11783. if (JSON_UNLIKELY(not success))
  11784. {
  11785. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  11786. }
  11787. break;
  11788. }
  11789. case patch_operations::invalid:
  11790. {
  11791. // op must be "add", "remove", "replace", "move", "copy", or
  11792. // "test"
  11793. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  11794. }
  11795. }
  11796. }
  11797. return result;
  11798. }
  11799. /*!
  11800. @brief creates a diff as a JSON patch
  11801. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  11802. be changed into the value @a target by calling @ref patch function.
  11803. @invariant For two JSON values @a source and @a target, the following code
  11804. yields always `true`:
  11805. @code {.cpp}
  11806. source.patch(diff(source, target)) == target;
  11807. @endcode
  11808. @note Currently, only `remove`, `add`, and `replace` operations are
  11809. generated.
  11810. @param[in] source JSON value to compare from
  11811. @param[in] target JSON value to compare against
  11812. @param[in] path helper value to create JSON pointers
  11813. @return a JSON patch to convert the @a source to @a target
  11814. @complexity Linear in the lengths of @a source and @a target.
  11815. @liveexample{The following code shows how a JSON patch is created as a
  11816. diff for two JSON values.,diff}
  11817. @sa @ref patch -- apply a JSON patch
  11818. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11819. @since version 2.0.0
  11820. */
  11821. static basic_json diff(const basic_json& source, const basic_json& target,
  11822. const std::string& path = "")
  11823. {
  11824. // the patch
  11825. basic_json result(value_t::array);
  11826. // if the values are the same, return empty patch
  11827. if (source == target)
  11828. {
  11829. return result;
  11830. }
  11831. if (source.type() != target.type())
  11832. {
  11833. // different types: replace value
  11834. result.push_back(
  11835. {
  11836. {"op", "replace"}, {"path", path}, {"value", target}
  11837. });
  11838. }
  11839. else
  11840. {
  11841. switch (source.type())
  11842. {
  11843. case value_t::array:
  11844. {
  11845. // first pass: traverse common elements
  11846. std::size_t i = 0;
  11847. while (i < source.size() and i < target.size())
  11848. {
  11849. // recursive call to compare array values at index i
  11850. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  11851. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11852. ++i;
  11853. }
  11854. // i now reached the end of at least one array
  11855. // in a second pass, traverse the remaining elements
  11856. // remove my remaining elements
  11857. const auto end_index = static_cast<difference_type>(result.size());
  11858. while (i < source.size())
  11859. {
  11860. // add operations in reverse order to avoid invalid
  11861. // indices
  11862. result.insert(result.begin() + end_index, object(
  11863. {
  11864. {"op", "remove"},
  11865. {"path", path + "/" + std::to_string(i)}
  11866. }));
  11867. ++i;
  11868. }
  11869. // add other remaining elements
  11870. while (i < target.size())
  11871. {
  11872. result.push_back(
  11873. {
  11874. {"op", "add"},
  11875. {"path", path + "/" + std::to_string(i)},
  11876. {"value", target[i]}
  11877. });
  11878. ++i;
  11879. }
  11880. break;
  11881. }
  11882. case value_t::object:
  11883. {
  11884. // first pass: traverse this object's elements
  11885. for (auto it = source.cbegin(); it != source.cend(); ++it)
  11886. {
  11887. // escape the key name to be used in a JSON patch
  11888. const auto key = json_pointer::escape(it.key());
  11889. if (target.find(it.key()) != target.end())
  11890. {
  11891. // recursive call to compare object values at key it
  11892. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  11893. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11894. }
  11895. else
  11896. {
  11897. // found a key that is not in o -> remove it
  11898. result.push_back(object(
  11899. {
  11900. {"op", "remove"}, {"path", path + "/" + key}
  11901. }));
  11902. }
  11903. }
  11904. // second pass: traverse other object's elements
  11905. for (auto it = target.cbegin(); it != target.cend(); ++it)
  11906. {
  11907. if (source.find(it.key()) == source.end())
  11908. {
  11909. // found a key that is not in this -> add it
  11910. const auto key = json_pointer::escape(it.key());
  11911. result.push_back(
  11912. {
  11913. {"op", "add"}, {"path", path + "/" + key},
  11914. {"value", it.value()}
  11915. });
  11916. }
  11917. }
  11918. break;
  11919. }
  11920. default:
  11921. {
  11922. // both primitive type: replace value
  11923. result.push_back(
  11924. {
  11925. {"op", "replace"}, {"path", path}, {"value", target}
  11926. });
  11927. break;
  11928. }
  11929. }
  11930. }
  11931. return result;
  11932. }
  11933. /// @}
  11934. };
  11935. /////////////
  11936. // presets //
  11937. /////////////
  11938. /*!
  11939. @brief default JSON class
  11940. This type is the default specialization of the @ref basic_json class which
  11941. uses the standard template types.
  11942. @since version 1.0.0
  11943. */
  11944. using json = basic_json<>;
  11945. //////////////////
  11946. // json_pointer //
  11947. //////////////////
  11948. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11949. NLOHMANN_BASIC_JSON_TPL&
  11950. json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const
  11951. {
  11952. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  11953. auto result = &j;
  11954. // in case no reference tokens exist, return a reference to the JSON value
  11955. // j which will be overwritten by a primitive value
  11956. for (const auto& reference_token : reference_tokens)
  11957. {
  11958. switch (result->m_type)
  11959. {
  11960. case detail::value_t::null:
  11961. {
  11962. if (reference_token == "0")
  11963. {
  11964. // start a new array if reference token is 0
  11965. result = &result->operator[](0);
  11966. }
  11967. else
  11968. {
  11969. // start a new object otherwise
  11970. result = &result->operator[](reference_token);
  11971. }
  11972. break;
  11973. }
  11974. case detail::value_t::object:
  11975. {
  11976. // create an entry in the object
  11977. result = &result->operator[](reference_token);
  11978. break;
  11979. }
  11980. case detail::value_t::array:
  11981. {
  11982. // create an entry in the array
  11983. JSON_TRY
  11984. {
  11985. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  11986. }
  11987. JSON_CATCH(std::invalid_argument&)
  11988. {
  11989. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11990. }
  11991. break;
  11992. }
  11993. /*
  11994. The following code is only reached if there exists a reference
  11995. token _and_ the current value is primitive. In this case, we have
  11996. an error situation, because primitive values may only occur as
  11997. single value; that is, with an empty list of reference tokens.
  11998. */
  11999. default:
  12000. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  12001. }
  12002. }
  12003. return *result;
  12004. }
  12005. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12006. NLOHMANN_BASIC_JSON_TPL&
  12007. json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const
  12008. {
  12009. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12010. for (const auto& reference_token : reference_tokens)
  12011. {
  12012. // convert null values to arrays or objects before continuing
  12013. if (ptr->m_type == detail::value_t::null)
  12014. {
  12015. // check if reference token is a number
  12016. const bool nums =
  12017. std::all_of(reference_token.begin(), reference_token.end(),
  12018. [](const char x)
  12019. {
  12020. return (x >= '0' and x <= '9');
  12021. });
  12022. // change value to array for numbers or "-" or to object otherwise
  12023. *ptr = (nums or reference_token == "-")
  12024. ? detail::value_t::array
  12025. : detail::value_t::object;
  12026. }
  12027. switch (ptr->m_type)
  12028. {
  12029. case detail::value_t::object:
  12030. {
  12031. // use unchecked object access
  12032. ptr = &ptr->operator[](reference_token);
  12033. break;
  12034. }
  12035. case detail::value_t::array:
  12036. {
  12037. // error condition (cf. RFC 6901, Sect. 4)
  12038. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12039. {
  12040. JSON_THROW(detail::parse_error::create(106, 0,
  12041. "array index '" + reference_token +
  12042. "' must not begin with '0'"));
  12043. }
  12044. if (reference_token == "-")
  12045. {
  12046. // explicitly treat "-" as index beyond the end
  12047. ptr = &ptr->operator[](ptr->m_value.array->size());
  12048. }
  12049. else
  12050. {
  12051. // convert array index to number; unchecked access
  12052. JSON_TRY
  12053. {
  12054. ptr = &ptr->operator[](
  12055. static_cast<size_type>(array_index(reference_token)));
  12056. }
  12057. JSON_CATCH(std::invalid_argument&)
  12058. {
  12059. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12060. }
  12061. }
  12062. break;
  12063. }
  12064. default:
  12065. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12066. }
  12067. }
  12068. return *ptr;
  12069. }
  12070. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12071. NLOHMANN_BASIC_JSON_TPL&
  12072. json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const
  12073. {
  12074. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12075. for (const auto& reference_token : reference_tokens)
  12076. {
  12077. switch (ptr->m_type)
  12078. {
  12079. case detail::value_t::object:
  12080. {
  12081. // note: at performs range check
  12082. ptr = &ptr->at(reference_token);
  12083. break;
  12084. }
  12085. case detail::value_t::array:
  12086. {
  12087. if (JSON_UNLIKELY(reference_token == "-"))
  12088. {
  12089. // "-" always fails the range check
  12090. JSON_THROW(detail::out_of_range::create(402,
  12091. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  12092. ") is out of range"));
  12093. }
  12094. // error condition (cf. RFC 6901, Sect. 4)
  12095. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12096. {
  12097. JSON_THROW(detail::parse_error::create(106, 0,
  12098. "array index '" + reference_token +
  12099. "' must not begin with '0'"));
  12100. }
  12101. // note: at performs range check
  12102. JSON_TRY
  12103. {
  12104. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  12105. }
  12106. JSON_CATCH(std::invalid_argument&)
  12107. {
  12108. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12109. }
  12110. break;
  12111. }
  12112. default:
  12113. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12114. }
  12115. }
  12116. return *ptr;
  12117. }
  12118. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12119. const NLOHMANN_BASIC_JSON_TPL&
  12120. json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
  12121. {
  12122. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12123. for (const auto& reference_token : reference_tokens)
  12124. {
  12125. switch (ptr->m_type)
  12126. {
  12127. case detail::value_t::object:
  12128. {
  12129. // use unchecked object access
  12130. ptr = &ptr->operator[](reference_token);
  12131. break;
  12132. }
  12133. case detail::value_t::array:
  12134. {
  12135. if (JSON_UNLIKELY(reference_token == "-"))
  12136. {
  12137. // "-" cannot be used for const access
  12138. JSON_THROW(detail::out_of_range::create(402,
  12139. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  12140. ") is out of range"));
  12141. }
  12142. // error condition (cf. RFC 6901, Sect. 4)
  12143. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12144. {
  12145. JSON_THROW(detail::parse_error::create(106, 0,
  12146. "array index '" + reference_token +
  12147. "' must not begin with '0'"));
  12148. }
  12149. // use unchecked array access
  12150. JSON_TRY
  12151. {
  12152. ptr = &ptr->operator[](
  12153. static_cast<size_type>(array_index(reference_token)));
  12154. }
  12155. JSON_CATCH(std::invalid_argument&)
  12156. {
  12157. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12158. }
  12159. break;
  12160. }
  12161. default:
  12162. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12163. }
  12164. }
  12165. return *ptr;
  12166. }
  12167. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12168. const NLOHMANN_BASIC_JSON_TPL&
  12169. json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
  12170. {
  12171. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12172. for (const auto& reference_token : reference_tokens)
  12173. {
  12174. switch (ptr->m_type)
  12175. {
  12176. case detail::value_t::object:
  12177. {
  12178. // note: at performs range check
  12179. ptr = &ptr->at(reference_token);
  12180. break;
  12181. }
  12182. case detail::value_t::array:
  12183. {
  12184. if (JSON_UNLIKELY(reference_token == "-"))
  12185. {
  12186. // "-" always fails the range check
  12187. JSON_THROW(detail::out_of_range::create(402,
  12188. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  12189. ") is out of range"));
  12190. }
  12191. // error condition (cf. RFC 6901, Sect. 4)
  12192. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12193. {
  12194. JSON_THROW(detail::parse_error::create(106, 0,
  12195. "array index '" + reference_token +
  12196. "' must not begin with '0'"));
  12197. }
  12198. // note: at performs range check
  12199. JSON_TRY
  12200. {
  12201. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  12202. }
  12203. JSON_CATCH(std::invalid_argument&)
  12204. {
  12205. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12206. }
  12207. break;
  12208. }
  12209. default:
  12210. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12211. }
  12212. }
  12213. return *ptr;
  12214. }
  12215. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12216. void json_pointer::flatten(const std::string& reference_string,
  12217. const NLOHMANN_BASIC_JSON_TPL& value,
  12218. NLOHMANN_BASIC_JSON_TPL& result)
  12219. {
  12220. switch (value.m_type)
  12221. {
  12222. case detail::value_t::array:
  12223. {
  12224. if (value.m_value.array->empty())
  12225. {
  12226. // flatten empty array as null
  12227. result[reference_string] = nullptr;
  12228. }
  12229. else
  12230. {
  12231. // iterate array and use index as reference string
  12232. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  12233. {
  12234. flatten(reference_string + "/" + std::to_string(i),
  12235. value.m_value.array->operator[](i), result);
  12236. }
  12237. }
  12238. break;
  12239. }
  12240. case detail::value_t::object:
  12241. {
  12242. if (value.m_value.object->empty())
  12243. {
  12244. // flatten empty object as null
  12245. result[reference_string] = nullptr;
  12246. }
  12247. else
  12248. {
  12249. // iterate object and use keys as reference string
  12250. for (const auto& element : *value.m_value.object)
  12251. {
  12252. flatten(reference_string + "/" + escape(element.first), element.second, result);
  12253. }
  12254. }
  12255. break;
  12256. }
  12257. default:
  12258. {
  12259. // add primitive value with its reference string
  12260. result[reference_string] = value;
  12261. break;
  12262. }
  12263. }
  12264. }
  12265. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12266. NLOHMANN_BASIC_JSON_TPL
  12267. json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)
  12268. {
  12269. if (JSON_UNLIKELY(not value.is_object()))
  12270. {
  12271. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  12272. }
  12273. NLOHMANN_BASIC_JSON_TPL result;
  12274. // iterate the JSON object values
  12275. for (const auto& element : *value.m_value.object)
  12276. {
  12277. if (JSON_UNLIKELY(not element.second.is_primitive()))
  12278. {
  12279. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  12280. }
  12281. // assign value to reference pointed to by JSON pointer; Note that if
  12282. // the JSON pointer is "" (i.e., points to the whole value), function
  12283. // get_and_create returns a reference to result itself. An assignment
  12284. // will then create a primitive value.
  12285. json_pointer(element.first).get_and_create(result) = element.second;
  12286. }
  12287. return result;
  12288. }
  12289. inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept
  12290. {
  12291. return (lhs.reference_tokens == rhs.reference_tokens);
  12292. }
  12293. inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept
  12294. {
  12295. return not (lhs == rhs);
  12296. }
  12297. } // namespace nlohmann
  12298. ///////////////////////
  12299. // nonmember support //
  12300. ///////////////////////
  12301. // specialization of std::swap, and std::hash
  12302. namespace std
  12303. {
  12304. /*!
  12305. @brief exchanges the values of two JSON objects
  12306. @since version 1.0.0
  12307. */
  12308. template<>
  12309. inline void swap(nlohmann::json& j1,
  12310. nlohmann::json& j2) noexcept(
  12311. is_nothrow_move_constructible<nlohmann::json>::value and
  12312. is_nothrow_move_assignable<nlohmann::json>::value
  12313. )
  12314. {
  12315. j1.swap(j2);
  12316. }
  12317. /// hash value for JSON objects
  12318. template<>
  12319. struct hash<nlohmann::json>
  12320. {
  12321. /*!
  12322. @brief return a hash value for a JSON object
  12323. @since version 1.0.0
  12324. */
  12325. std::size_t operator()(const nlohmann::json& j) const
  12326. {
  12327. // a naive hashing via the string representation
  12328. const auto& h = hash<nlohmann::json::string_t>();
  12329. return h(j.dump());
  12330. }
  12331. };
  12332. /// specialization for std::less<value_t>
  12333. /// @note: do not remove the space after '<',
  12334. /// see https://github.com/nlohmann/json/pull/679
  12335. template<>
  12336. struct less< ::nlohmann::detail::value_t>
  12337. {
  12338. /*!
  12339. @brief compare two value_t enum values
  12340. @since version 3.0.0
  12341. */
  12342. bool operator()(nlohmann::detail::value_t lhs,
  12343. nlohmann::detail::value_t rhs) const noexcept
  12344. {
  12345. return nlohmann::detail::operator<(lhs, rhs);
  12346. }
  12347. };
  12348. } // namespace std
  12349. /*!
  12350. @brief user-defined string literal for JSON values
  12351. This operator implements a user-defined string literal for JSON objects. It
  12352. can be used by adding `"_json"` to a string literal and returns a JSON object
  12353. if no parse error occurred.
  12354. @param[in] s a string representation of a JSON object
  12355. @param[in] n the length of string @a s
  12356. @return a JSON object
  12357. @since version 1.0.0
  12358. */
  12359. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  12360. {
  12361. return nlohmann::json::parse(s, s + n);
  12362. }
  12363. /*!
  12364. @brief user-defined string literal for JSON pointer
  12365. This operator implements a user-defined string literal for JSON Pointers. It
  12366. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  12367. object if no parse error occurred.
  12368. @param[in] s a string representation of a JSON Pointer
  12369. @param[in] n the length of string @a s
  12370. @return a JSON pointer object
  12371. @since version 2.0.0
  12372. */
  12373. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  12374. {
  12375. return nlohmann::json::json_pointer(std::string(s, n));
  12376. }
  12377. // restore GCC/clang diagnostic settings
  12378. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  12379. #pragma GCC diagnostic pop
  12380. #endif
  12381. #if defined(__clang__)
  12382. #pragma GCC diagnostic pop
  12383. #endif
  12384. // clean up
  12385. #undef JSON_CATCH
  12386. #undef JSON_THROW
  12387. #undef JSON_TRY
  12388. #undef JSON_LIKELY
  12389. #undef JSON_UNLIKELY
  12390. #undef JSON_DEPRECATED
  12391. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12392. #undef NLOHMANN_BASIC_JSON_TPL
  12393. #endif