You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

json.hpp 789KB

5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
5 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.7.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 7
  29. #define NLOHMANN_JSON_VERSION_PATCH 1
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <utility>
  45. // #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <algorithm> // transform
  47. #include <array> // array
  48. #include <ciso646> // and, not
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. // #include <nlohmann/detail/input/position_t.hpp>
  63. #include <cstddef> // size_t
  64. namespace nlohmann
  65. {
  66. namespace detail
  67. {
  68. /// struct to capture the start position of the current token
  69. struct position_t
  70. {
  71. /// the total number of characters read
  72. std::size_t chars_read_total = 0;
  73. /// the number of characters read in the current line
  74. std::size_t chars_read_current_line = 0;
  75. /// the number of lines read
  76. std::size_t lines_read = 0;
  77. /// conversion to size_t to preserve SAX interface
  78. constexpr operator size_t() const
  79. {
  80. return chars_read_total;
  81. }
  82. };
  83. } // namespace detail
  84. } // namespace nlohmann
  85. // #include <nlohmann/detail/macro_scope.hpp>
  86. #include <utility> // pair
  87. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  88. /* Hedley - https://nemequ.github.io/hedley
  89. * Created by Evan Nemerson <evan@nemerson.com>
  90. *
  91. * To the extent possible under law, the author(s) have dedicated all
  92. * copyright and related and neighboring rights to this software to
  93. * the public domain worldwide. This software is distributed without
  94. * any warranty.
  95. *
  96. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  97. * SPDX-License-Identifier: CC0-1.0
  98. */
  99. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 11)
  100. #if defined(JSON_HEDLEY_VERSION)
  101. #undef JSON_HEDLEY_VERSION
  102. #endif
  103. #define JSON_HEDLEY_VERSION 11
  104. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  105. #undef JSON_HEDLEY_STRINGIFY_EX
  106. #endif
  107. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  108. #if defined(JSON_HEDLEY_STRINGIFY)
  109. #undef JSON_HEDLEY_STRINGIFY
  110. #endif
  111. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  112. #if defined(JSON_HEDLEY_CONCAT_EX)
  113. #undef JSON_HEDLEY_CONCAT_EX
  114. #endif
  115. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  116. #if defined(JSON_HEDLEY_CONCAT)
  117. #undef JSON_HEDLEY_CONCAT
  118. #endif
  119. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  120. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  121. #undef JSON_HEDLEY_VERSION_ENCODE
  122. #endif
  123. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  124. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  125. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  126. #endif
  127. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  128. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  129. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  130. #endif
  131. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  132. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  133. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  134. #endif
  135. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  136. #if defined(JSON_HEDLEY_GNUC_VERSION)
  137. #undef JSON_HEDLEY_GNUC_VERSION
  138. #endif
  139. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  140. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  141. #elif defined(__GNUC__)
  142. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  143. #endif
  144. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  145. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  146. #endif
  147. #if defined(JSON_HEDLEY_GNUC_VERSION)
  148. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  149. #else
  150. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  151. #endif
  152. #if defined(JSON_HEDLEY_MSVC_VERSION)
  153. #undef JSON_HEDLEY_MSVC_VERSION
  154. #endif
  155. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  156. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  157. #elif defined(_MSC_FULL_VER)
  158. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  159. #elif defined(_MSC_VER)
  160. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  161. #endif
  162. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  163. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  164. #endif
  165. #if !defined(_MSC_VER)
  166. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  167. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  168. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  169. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  170. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  171. #else
  172. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  173. #endif
  174. #if defined(JSON_HEDLEY_INTEL_VERSION)
  175. #undef JSON_HEDLEY_INTEL_VERSION
  176. #endif
  177. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  178. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  179. #elif defined(__INTEL_COMPILER)
  180. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  181. #endif
  182. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  183. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  184. #endif
  185. #if defined(JSON_HEDLEY_INTEL_VERSION)
  186. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  187. #else
  188. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  189. #endif
  190. #if defined(JSON_HEDLEY_PGI_VERSION)
  191. #undef JSON_HEDLEY_PGI_VERSION
  192. #endif
  193. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  194. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  195. #endif
  196. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  197. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  198. #endif
  199. #if defined(JSON_HEDLEY_PGI_VERSION)
  200. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  201. #else
  202. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  203. #endif
  204. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  205. #undef JSON_HEDLEY_SUNPRO_VERSION
  206. #endif
  207. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  208. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10)
  209. #elif defined(__SUNPRO_C)
  210. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  211. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  212. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10)
  213. #elif defined(__SUNPRO_CC)
  214. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  215. #endif
  216. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  217. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  218. #endif
  219. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  220. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  221. #else
  222. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  223. #endif
  224. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  225. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  226. #endif
  227. #if defined(__EMSCRIPTEN__)
  228. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  229. #endif
  230. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  231. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  232. #endif
  233. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  234. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  235. #else
  236. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  237. #endif
  238. #if defined(JSON_HEDLEY_ARM_VERSION)
  239. #undef JSON_HEDLEY_ARM_VERSION
  240. #endif
  241. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  242. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  243. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  244. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  245. #endif
  246. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  247. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  248. #endif
  249. #if defined(JSON_HEDLEY_ARM_VERSION)
  250. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  251. #else
  252. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  253. #endif
  254. #if defined(JSON_HEDLEY_IBM_VERSION)
  255. #undef JSON_HEDLEY_IBM_VERSION
  256. #endif
  257. #if defined(__ibmxl__)
  258. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  259. #elif defined(__xlC__) && defined(__xlC_ver__)
  260. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  261. #elif defined(__xlC__)
  262. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  263. #endif
  264. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  265. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  266. #endif
  267. #if defined(JSON_HEDLEY_IBM_VERSION)
  268. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  269. #else
  270. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  271. #endif
  272. #if defined(JSON_HEDLEY_TI_VERSION)
  273. #undef JSON_HEDLEY_TI_VERSION
  274. #endif
  275. #if defined(__TI_COMPILER_VERSION__)
  276. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  277. #endif
  278. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  279. #undef JSON_HEDLEY_TI_VERSION_CHECK
  280. #endif
  281. #if defined(JSON_HEDLEY_TI_VERSION)
  282. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  283. #else
  284. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  285. #endif
  286. #if defined(JSON_HEDLEY_CRAY_VERSION)
  287. #undef JSON_HEDLEY_CRAY_VERSION
  288. #endif
  289. #if defined(_CRAYC)
  290. #if defined(_RELEASE_PATCHLEVEL)
  291. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  292. #else
  293. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  294. #endif
  295. #endif
  296. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  297. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  298. #endif
  299. #if defined(JSON_HEDLEY_CRAY_VERSION)
  300. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  301. #else
  302. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  303. #endif
  304. #if defined(JSON_HEDLEY_IAR_VERSION)
  305. #undef JSON_HEDLEY_IAR_VERSION
  306. #endif
  307. #if defined(__IAR_SYSTEMS_ICC__)
  308. #if __VER__ > 1000
  309. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  310. #else
  311. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  312. #endif
  313. #endif
  314. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  315. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  316. #endif
  317. #if defined(JSON_HEDLEY_IAR_VERSION)
  318. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  319. #else
  320. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  321. #endif
  322. #if defined(JSON_HEDLEY_TINYC_VERSION)
  323. #undef JSON_HEDLEY_TINYC_VERSION
  324. #endif
  325. #if defined(__TINYC__)
  326. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  327. #endif
  328. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  329. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  330. #endif
  331. #if defined(JSON_HEDLEY_TINYC_VERSION)
  332. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  333. #else
  334. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  335. #endif
  336. #if defined(JSON_HEDLEY_DMC_VERSION)
  337. #undef JSON_HEDLEY_DMC_VERSION
  338. #endif
  339. #if defined(__DMC__)
  340. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  341. #endif
  342. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  343. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  344. #endif
  345. #if defined(JSON_HEDLEY_DMC_VERSION)
  346. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  347. #else
  348. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  349. #endif
  350. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  351. #undef JSON_HEDLEY_COMPCERT_VERSION
  352. #endif
  353. #if defined(__COMPCERT_VERSION__)
  354. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  355. #endif
  356. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  357. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  358. #endif
  359. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  360. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  361. #else
  362. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  363. #endif
  364. #if defined(JSON_HEDLEY_PELLES_VERSION)
  365. #undef JSON_HEDLEY_PELLES_VERSION
  366. #endif
  367. #if defined(__POCC__)
  368. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  369. #endif
  370. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  371. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  372. #endif
  373. #if defined(JSON_HEDLEY_PELLES_VERSION)
  374. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  375. #else
  376. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  377. #endif
  378. #if defined(JSON_HEDLEY_GCC_VERSION)
  379. #undef JSON_HEDLEY_GCC_VERSION
  380. #endif
  381. #if \
  382. defined(JSON_HEDLEY_GNUC_VERSION) && \
  383. !defined(__clang__) && \
  384. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  385. !defined(JSON_HEDLEY_PGI_VERSION) && \
  386. !defined(JSON_HEDLEY_ARM_VERSION) && \
  387. !defined(JSON_HEDLEY_TI_VERSION) && \
  388. !defined(__COMPCERT__)
  389. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  390. #endif
  391. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  392. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  393. #endif
  394. #if defined(JSON_HEDLEY_GCC_VERSION)
  395. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  396. #else
  397. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  398. #endif
  399. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  400. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  401. #endif
  402. #if defined(__has_attribute)
  403. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  404. #else
  405. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  406. #endif
  407. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  408. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  409. #endif
  410. #if defined(__has_attribute)
  411. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  412. #else
  413. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  414. #endif
  415. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  416. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  417. #endif
  418. #if defined(__has_attribute)
  419. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  420. #else
  421. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  422. #endif
  423. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  424. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  425. #endif
  426. #if \
  427. defined(__has_cpp_attribute) && \
  428. defined(__cplusplus) && \
  429. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  430. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  431. #else
  432. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  433. #endif
  434. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  435. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  436. #endif
  437. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  438. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  439. #elif \
  440. !defined(JSON_HEDLEY_PGI_VERSION) && \
  441. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  442. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  443. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  444. #else
  445. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  446. #endif
  447. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  448. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  449. #endif
  450. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  451. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  452. #else
  453. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  454. #endif
  455. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  456. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  457. #endif
  458. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  459. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  460. #else
  461. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  462. #endif
  463. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  464. #undef JSON_HEDLEY_HAS_BUILTIN
  465. #endif
  466. #if defined(__has_builtin)
  467. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  468. #else
  469. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  470. #endif
  471. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  472. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  473. #endif
  474. #if defined(__has_builtin)
  475. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  476. #else
  477. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  478. #endif
  479. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  480. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  481. #endif
  482. #if defined(__has_builtin)
  483. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  484. #else
  485. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  486. #endif
  487. #if defined(JSON_HEDLEY_HAS_FEATURE)
  488. #undef JSON_HEDLEY_HAS_FEATURE
  489. #endif
  490. #if defined(__has_feature)
  491. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  492. #else
  493. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  494. #endif
  495. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  496. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  497. #endif
  498. #if defined(__has_feature)
  499. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  500. #else
  501. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  502. #endif
  503. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  504. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  505. #endif
  506. #if defined(__has_feature)
  507. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  508. #else
  509. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  510. #endif
  511. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  512. #undef JSON_HEDLEY_HAS_EXTENSION
  513. #endif
  514. #if defined(__has_extension)
  515. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  516. #else
  517. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  518. #endif
  519. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  520. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  521. #endif
  522. #if defined(__has_extension)
  523. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  524. #else
  525. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  526. #endif
  527. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  528. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  529. #endif
  530. #if defined(__has_extension)
  531. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  532. #else
  533. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  534. #endif
  535. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  536. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  537. #endif
  538. #if defined(__has_declspec_attribute)
  539. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  540. #else
  541. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  542. #endif
  543. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  544. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  545. #endif
  546. #if defined(__has_declspec_attribute)
  547. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  548. #else
  549. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  550. #endif
  551. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  552. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  553. #endif
  554. #if defined(__has_declspec_attribute)
  555. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  556. #else
  557. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_HAS_WARNING)
  560. #undef JSON_HEDLEY_HAS_WARNING
  561. #endif
  562. #if defined(__has_warning)
  563. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  564. #else
  565. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  566. #endif
  567. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  568. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  569. #endif
  570. #if defined(__has_warning)
  571. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  572. #else
  573. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  574. #endif
  575. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  576. #undef JSON_HEDLEY_GCC_HAS_WARNING
  577. #endif
  578. #if defined(__has_warning)
  579. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  580. #else
  581. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  582. #endif
  583. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  584. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  585. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  586. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  587. #endif
  588. #if defined(__cplusplus) && JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  589. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  590. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  591. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  592. xpr \
  593. JSON_HEDLEY_DIAGNOSTIC_POP
  594. #else
  595. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  596. #endif
  597. #if \
  598. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  599. defined(__clang__) || \
  600. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  601. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  602. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  603. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  604. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  605. JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) || \
  606. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  607. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  608. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  609. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  610. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  611. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  612. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  613. #else
  614. #define JSON_HEDLEY_PRAGMA(value)
  615. #endif
  616. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  617. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  618. #endif
  619. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  620. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  621. #endif
  622. #if defined(__clang__)
  623. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  624. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  625. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  626. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  627. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  628. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  629. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  630. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  631. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  632. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  633. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  634. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  635. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  636. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  637. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,1,0)
  638. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  639. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  640. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  641. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  642. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  643. #else
  644. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  645. #define JSON_HEDLEY_DIAGNOSTIC_POP
  646. #endif
  647. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  648. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  649. #endif
  650. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  651. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  652. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  653. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  654. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  655. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  656. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  657. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  658. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  659. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  660. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  661. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  662. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  663. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  664. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  665. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  666. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  667. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  668. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  669. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  670. #else
  671. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  672. #endif
  673. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  674. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  675. #endif
  676. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  677. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  678. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  679. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  680. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  681. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  682. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  683. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  684. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  685. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  686. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  687. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  688. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  689. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  690. #else
  691. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  692. #endif
  693. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  694. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  695. #endif
  696. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  697. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  698. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  699. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  700. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  701. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  702. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  703. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  704. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  705. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  706. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  707. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  708. #elif JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  709. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  710. #else
  711. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  712. #endif
  713. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  714. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  715. #endif
  716. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  717. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  718. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  719. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  720. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  721. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  722. #else
  723. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  724. #endif
  725. #if defined(JSON_HEDLEY_DEPRECATED)
  726. #undef JSON_HEDLEY_DEPRECATED
  727. #endif
  728. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  729. #undef JSON_HEDLEY_DEPRECATED_FOR
  730. #endif
  731. #if defined(__cplusplus) && (__cplusplus >= 201402L)
  732. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  733. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  734. #elif \
  735. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  736. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  737. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  738. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  739. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  740. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  741. JSON_HEDLEY_TI_VERSION_CHECK(8,3,0)
  742. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  743. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  744. #elif \
  745. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  746. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  747. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  748. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  749. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  750. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  751. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  752. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  753. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  754. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  755. #elif \
  756. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  757. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  758. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  759. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  760. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  761. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  762. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  763. #else
  764. #define JSON_HEDLEY_DEPRECATED(since)
  765. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  766. #endif
  767. #if defined(JSON_HEDLEY_UNAVAILABLE)
  768. #undef JSON_HEDLEY_UNAVAILABLE
  769. #endif
  770. #if \
  771. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  772. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  773. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  774. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  775. #else
  776. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  777. #endif
  778. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  779. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  780. #endif
  781. #if defined(__cplusplus) && (__cplusplus >= 201703L)
  782. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  783. #elif \
  784. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  785. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  786. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  787. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  788. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  789. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  790. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  791. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  792. #elif defined(_Check_return_) /* SAL */
  793. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  794. #else
  795. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  796. #endif
  797. #if defined(JSON_HEDLEY_SENTINEL)
  798. #undef JSON_HEDLEY_SENTINEL
  799. #endif
  800. #if \
  801. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  802. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  803. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  804. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  805. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  806. #else
  807. #define JSON_HEDLEY_SENTINEL(position)
  808. #endif
  809. #if defined(JSON_HEDLEY_NO_RETURN)
  810. #undef JSON_HEDLEY_NO_RETURN
  811. #endif
  812. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  813. #define JSON_HEDLEY_NO_RETURN __noreturn
  814. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  815. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  816. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  817. #define JSON_HEDLEY_NO_RETURN _Noreturn
  818. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  819. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  820. #elif \
  821. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  822. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  823. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  824. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  825. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  826. JSON_HEDLEY_TI_VERSION_CHECK(18,0,0) || \
  827. (JSON_HEDLEY_TI_VERSION_CHECK(17,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  828. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  829. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  830. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  831. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  832. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  833. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  834. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  835. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  836. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  837. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  838. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  839. #else
  840. #define JSON_HEDLEY_NO_RETURN
  841. #endif
  842. #if defined(JSON_HEDLEY_NO_ESCAPE)
  843. #undef JSON_HEDLEY_NO_ESCAPE
  844. #endif
  845. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  846. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  847. #else
  848. #define JSON_HEDLEY_NO_ESCAPE
  849. #endif
  850. #if defined(JSON_HEDLEY_UNREACHABLE)
  851. #undef JSON_HEDLEY_UNREACHABLE
  852. #endif
  853. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  854. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  855. #endif
  856. #if \
  857. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  858. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  859. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  860. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  861. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  862. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  863. #define JSON_HEDLEY_UNREACHABLE() __assume(0)
  864. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  865. #if defined(__cplusplus)
  866. #define JSON_HEDLEY_UNREACHABLE() std::_nassert(0)
  867. #else
  868. #define JSON_HEDLEY_UNREACHABLE() _nassert(0)
  869. #endif
  870. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  871. #elif defined(EXIT_FAILURE)
  872. #define JSON_HEDLEY_UNREACHABLE() abort()
  873. #else
  874. #define JSON_HEDLEY_UNREACHABLE()
  875. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return value
  876. #endif
  877. #if !defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  878. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  879. #endif
  880. #if defined(JSON_HEDLEY_ASSUME)
  881. #undef JSON_HEDLEY_ASSUME
  882. #endif
  883. #if \
  884. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  885. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  886. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  887. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  888. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  889. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0)
  890. #if defined(__cplusplus)
  891. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  892. #else
  893. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  894. #endif
  895. #elif \
  896. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && !defined(JSON_HEDLEY_ARM_VERSION)) || \
  897. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  898. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  899. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  900. #define JSON_HEDLEY_ASSUME(expr) ((void) ((expr) ? 1 : (__builtin_unreachable(), 1)))
  901. #else
  902. #define JSON_HEDLEY_ASSUME(expr) ((void) (expr))
  903. #endif
  904. JSON_HEDLEY_DIAGNOSTIC_PUSH
  905. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  906. #pragma clang diagnostic ignored "-Wpedantic"
  907. #endif
  908. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  909. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  910. #endif
  911. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  912. #if defined(__clang__)
  913. #pragma clang diagnostic ignored "-Wvariadic-macros"
  914. #elif defined(JSON_HEDLEY_GCC_VERSION)
  915. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  916. #endif
  917. #endif
  918. #if defined(JSON_HEDLEY_NON_NULL)
  919. #undef JSON_HEDLEY_NON_NULL
  920. #endif
  921. #if \
  922. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  923. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  924. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  925. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  926. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  927. #else
  928. #define JSON_HEDLEY_NON_NULL(...)
  929. #endif
  930. JSON_HEDLEY_DIAGNOSTIC_POP
  931. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  932. #undef JSON_HEDLEY_PRINTF_FORMAT
  933. #endif
  934. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  935. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  936. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  937. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  938. #elif \
  939. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  940. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  941. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  942. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  943. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  944. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  945. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  946. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  947. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  948. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  949. #else
  950. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  951. #endif
  952. #if defined(JSON_HEDLEY_CONSTEXPR)
  953. #undef JSON_HEDLEY_CONSTEXPR
  954. #endif
  955. #if defined(__cplusplus)
  956. #if __cplusplus >= 201103L
  957. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  958. #endif
  959. #endif
  960. #if !defined(JSON_HEDLEY_CONSTEXPR)
  961. #define JSON_HEDLEY_CONSTEXPR
  962. #endif
  963. #if defined(JSON_HEDLEY_PREDICT)
  964. #undef JSON_HEDLEY_PREDICT
  965. #endif
  966. #if defined(JSON_HEDLEY_LIKELY)
  967. #undef JSON_HEDLEY_LIKELY
  968. #endif
  969. #if defined(JSON_HEDLEY_UNLIKELY)
  970. #undef JSON_HEDLEY_UNLIKELY
  971. #endif
  972. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  973. #undef JSON_HEDLEY_UNPREDICTABLE
  974. #endif
  975. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  976. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable(!!(expr))
  977. #endif
  978. #if \
  979. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  980. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  981. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability(expr, value, probability)
  982. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1, probability)
  983. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0, probability)
  984. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  985. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  986. #if !defined(JSON_HEDLEY_BUILTIN_UNPREDICTABLE)
  987. #define JSON_HEDLEY_BUILTIN_UNPREDICTABLE(expr) __builtin_expect_with_probability(!!(expr), 1, 0.5)
  988. #endif
  989. #elif \
  990. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  991. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  992. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  993. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  994. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  995. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  996. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  997. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27)
  998. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  999. (((probability) >= 0.9) ? __builtin_expect(!!(expr), (expected)) : (((void) (expected)), !!(expr)))
  1000. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1001. (__extension__ ({ \
  1002. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  1003. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1004. }))
  1005. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1006. (__extension__ ({ \
  1007. JSON_HEDLEY_CONSTEXPR double hedley_probability_ = (probability); \
  1008. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1009. }))
  1010. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1011. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1012. #else
  1013. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (((void) (expected)), !!(expr))
  1014. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1015. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1016. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1017. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1018. #endif
  1019. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1020. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1021. #endif
  1022. #if defined(JSON_HEDLEY_MALLOC)
  1023. #undef JSON_HEDLEY_MALLOC
  1024. #endif
  1025. #if \
  1026. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1027. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1028. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1029. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1030. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1031. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1032. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1033. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1034. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1035. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1036. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1037. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1038. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1039. #else
  1040. #define JSON_HEDLEY_MALLOC
  1041. #endif
  1042. #if defined(JSON_HEDLEY_PURE)
  1043. #undef JSON_HEDLEY_PURE
  1044. #endif
  1045. #if \
  1046. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1047. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1048. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1049. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1050. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1051. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1052. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1053. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1054. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1055. #define JSON_HEDLEY_PURE __attribute__((__pure__))
  1056. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1057. #define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1058. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1059. #define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1060. #else
  1061. #define JSON_HEDLEY_PURE
  1062. #endif
  1063. #if defined(JSON_HEDLEY_CONST)
  1064. #undef JSON_HEDLEY_CONST
  1065. #endif
  1066. #if \
  1067. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1068. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1069. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1070. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1071. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1072. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1073. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1074. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1075. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1076. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1077. #elif \
  1078. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1079. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1080. #else
  1081. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1082. #endif
  1083. #if defined(JSON_HEDLEY_RESTRICT)
  1084. #undef JSON_HEDLEY_RESTRICT
  1085. #endif
  1086. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1087. #define JSON_HEDLEY_RESTRICT restrict
  1088. #elif \
  1089. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1090. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1091. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1092. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1093. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1094. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1095. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1096. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1097. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1098. defined(__clang__)
  1099. #define JSON_HEDLEY_RESTRICT __restrict
  1100. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1101. #define JSON_HEDLEY_RESTRICT _Restrict
  1102. #else
  1103. #define JSON_HEDLEY_RESTRICT
  1104. #endif
  1105. #if defined(JSON_HEDLEY_INLINE)
  1106. #undef JSON_HEDLEY_INLINE
  1107. #endif
  1108. #if \
  1109. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1110. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1111. #define JSON_HEDLEY_INLINE inline
  1112. #elif \
  1113. defined(JSON_HEDLEY_GCC_VERSION) || \
  1114. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1115. #define JSON_HEDLEY_INLINE __inline__
  1116. #elif \
  1117. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1118. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1119. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0)
  1120. #define JSON_HEDLEY_INLINE __inline
  1121. #else
  1122. #define JSON_HEDLEY_INLINE
  1123. #endif
  1124. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1125. #undef JSON_HEDLEY_ALWAYS_INLINE
  1126. #endif
  1127. #if \
  1128. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1129. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1130. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1131. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1132. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1133. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1134. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1135. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1136. #define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1137. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1138. #define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1139. #elif JSON_HEDLEY_TI_VERSION_CHECK(7,0,0) && defined(__cplusplus)
  1140. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1141. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1142. #define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1143. #else
  1144. #define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1145. #endif
  1146. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1147. #undef JSON_HEDLEY_NEVER_INLINE
  1148. #endif
  1149. #if \
  1150. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1151. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1152. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1153. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1154. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1155. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1156. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1157. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1158. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1159. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1160. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1161. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1162. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1163. #elif JSON_HEDLEY_TI_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1164. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1165. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1166. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1167. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1168. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1169. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1170. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1171. #else
  1172. #define JSON_HEDLEY_NEVER_INLINE
  1173. #endif
  1174. #if defined(JSON_HEDLEY_PRIVATE)
  1175. #undef JSON_HEDLEY_PRIVATE
  1176. #endif
  1177. #if defined(JSON_HEDLEY_PUBLIC)
  1178. #undef JSON_HEDLEY_PUBLIC
  1179. #endif
  1180. #if defined(JSON_HEDLEY_IMPORT)
  1181. #undef JSON_HEDLEY_IMPORT
  1182. #endif
  1183. #if defined(_WIN32) || defined(__CYGWIN__)
  1184. #define JSON_HEDLEY_PRIVATE
  1185. #define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1186. #define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1187. #else
  1188. #if \
  1189. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1190. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1191. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1192. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1193. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1194. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1195. JSON_HEDLEY_TI_VERSION_CHECK(8,0,0) || \
  1196. (JSON_HEDLEY_TI_VERSION_CHECK(7,3,0) && defined(__TI_EABI__) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__))
  1197. #define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1198. #define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1199. #else
  1200. #define JSON_HEDLEY_PRIVATE
  1201. #define JSON_HEDLEY_PUBLIC
  1202. #endif
  1203. #define JSON_HEDLEY_IMPORT extern
  1204. #endif
  1205. #if defined(JSON_HEDLEY_NO_THROW)
  1206. #undef JSON_HEDLEY_NO_THROW
  1207. #endif
  1208. #if \
  1209. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1210. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1211. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1212. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1213. #elif \
  1214. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1215. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1216. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1217. #else
  1218. #define JSON_HEDLEY_NO_THROW
  1219. #endif
  1220. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1221. #undef JSON_HEDLEY_FALL_THROUGH
  1222. #endif
  1223. #if JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(fallthrough,7,0,0) && !defined(JSON_HEDLEY_PGI_VERSION)
  1224. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1225. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1226. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1227. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1228. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1229. #elif defined(__fallthrough) /* SAL */
  1230. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1231. #else
  1232. #define JSON_HEDLEY_FALL_THROUGH
  1233. #endif
  1234. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1235. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1236. #endif
  1237. #if \
  1238. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1239. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1240. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1241. #elif defined(_Ret_notnull_) /* SAL */
  1242. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1243. #else
  1244. #define JSON_HEDLEY_RETURNS_NON_NULL
  1245. #endif
  1246. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1247. #undef JSON_HEDLEY_ARRAY_PARAM
  1248. #endif
  1249. #if \
  1250. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1251. !defined(__STDC_NO_VLA__) && \
  1252. !defined(__cplusplus) && \
  1253. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1254. !defined(JSON_HEDLEY_TINYC_VERSION)
  1255. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1256. #else
  1257. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1258. #endif
  1259. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1260. #undef JSON_HEDLEY_IS_CONSTANT
  1261. #endif
  1262. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1263. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1264. #endif
  1265. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1266. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1267. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1268. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1269. #endif
  1270. #if \
  1271. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1272. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1273. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1274. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1275. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1276. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1277. JSON_HEDLEY_TI_VERSION_CHECK(6,1,0) || \
  1278. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1279. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1280. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1281. #endif
  1282. #if !defined(__cplusplus)
  1283. # if \
  1284. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1285. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1286. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1287. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1288. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1289. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1290. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1291. #if defined(__INTPTR_TYPE__)
  1292. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1293. #else
  1294. #include <stdint.h>
  1295. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1296. #endif
  1297. # elif \
  1298. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(JSON_HEDLEY_SUNPRO_VERSION) && !defined(JSON_HEDLEY_PGI_VERSION)) || \
  1299. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1300. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1301. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1302. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1303. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1304. #if defined(__INTPTR_TYPE__)
  1305. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1306. #else
  1307. #include <stdint.h>
  1308. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1309. #endif
  1310. # elif \
  1311. defined(JSON_HEDLEY_GCC_VERSION) || \
  1312. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1313. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1314. defined(JSON_HEDLEY_TI_VERSION) || \
  1315. defined(__clang__)
  1316. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1317. sizeof(void) != \
  1318. sizeof(*( \
  1319. 1 ? \
  1320. ((void*) ((expr) * 0L) ) : \
  1321. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1322. ) \
  1323. ) \
  1324. )
  1325. # endif
  1326. #endif
  1327. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1328. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1329. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1330. #endif
  1331. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1332. #else
  1333. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1334. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1335. #endif
  1336. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1337. #endif
  1338. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1339. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1340. #endif
  1341. #if defined(JSON_HEDLEY_END_C_DECLS)
  1342. #undef JSON_HEDLEY_END_C_DECLS
  1343. #endif
  1344. #if defined(JSON_HEDLEY_C_DECL)
  1345. #undef JSON_HEDLEY_C_DECL
  1346. #endif
  1347. #if defined(__cplusplus)
  1348. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1349. #define JSON_HEDLEY_END_C_DECLS }
  1350. #define JSON_HEDLEY_C_DECL extern "C"
  1351. #else
  1352. #define JSON_HEDLEY_BEGIN_C_DECLS
  1353. #define JSON_HEDLEY_END_C_DECLS
  1354. #define JSON_HEDLEY_C_DECL
  1355. #endif
  1356. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1357. #undef JSON_HEDLEY_STATIC_ASSERT
  1358. #endif
  1359. #if \
  1360. !defined(__cplusplus) && ( \
  1361. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1362. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1363. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1364. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1365. defined(_Static_assert) \
  1366. )
  1367. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1368. #elif \
  1369. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1370. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \
  1371. (defined(__cplusplus) && JSON_HEDLEY_TI_VERSION_CHECK(8,3,0))
  1372. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1373. #else
  1374. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1375. #endif
  1376. #if defined(JSON_HEDLEY_CONST_CAST)
  1377. #undef JSON_HEDLEY_CONST_CAST
  1378. #endif
  1379. #if defined(__cplusplus)
  1380. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  1381. #elif \
  1382. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  1383. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  1384. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1385. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  1386. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1387. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  1388. ((T) (expr)); \
  1389. JSON_HEDLEY_DIAGNOSTIC_POP \
  1390. }))
  1391. #else
  1392. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  1393. #endif
  1394. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  1395. #undef JSON_HEDLEY_REINTERPRET_CAST
  1396. #endif
  1397. #if defined(__cplusplus)
  1398. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  1399. #else
  1400. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (*((T*) &(expr)))
  1401. #endif
  1402. #if defined(JSON_HEDLEY_STATIC_CAST)
  1403. #undef JSON_HEDLEY_STATIC_CAST
  1404. #endif
  1405. #if defined(__cplusplus)
  1406. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  1407. #else
  1408. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  1409. #endif
  1410. #if defined(JSON_HEDLEY_CPP_CAST)
  1411. #undef JSON_HEDLEY_CPP_CAST
  1412. #endif
  1413. #if defined(__cplusplus)
  1414. #define JSON_HEDLEY_CPP_CAST(T, expr) static_cast<T>(expr)
  1415. #else
  1416. #define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  1417. #endif
  1418. #if defined(JSON_HEDLEY_NULL)
  1419. #undef JSON_HEDLEY_NULL
  1420. #endif
  1421. #if defined(__cplusplus)
  1422. #if __cplusplus >= 201103L
  1423. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1424. #elif defined(NULL)
  1425. #define JSON_HEDLEY_NULL NULL
  1426. #else
  1427. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1428. #endif
  1429. #elif defined(NULL)
  1430. #define JSON_HEDLEY_NULL NULL
  1431. #else
  1432. #define JSON_HEDLEY_NULL ((void*) 0)
  1433. #endif
  1434. #if defined(JSON_HEDLEY_MESSAGE)
  1435. #undef JSON_HEDLEY_MESSAGE
  1436. #endif
  1437. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1438. # define JSON_HEDLEY_MESSAGE(msg) \
  1439. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1440. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1441. JSON_HEDLEY_PRAGMA(message msg) \
  1442. JSON_HEDLEY_DIAGNOSTIC_POP
  1443. #elif \
  1444. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1445. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1446. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1447. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1448. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1449. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1450. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1451. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1452. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1453. #else
  1454. # define JSON_HEDLEY_MESSAGE(msg)
  1455. #endif
  1456. #if defined(JSON_HEDLEY_WARNING)
  1457. #undef JSON_HEDLEY_WARNING
  1458. #endif
  1459. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1460. # define JSON_HEDLEY_WARNING(msg) \
  1461. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1462. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1463. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1464. JSON_HEDLEY_DIAGNOSTIC_POP
  1465. #elif \
  1466. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1467. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0)
  1468. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1469. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1470. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1471. #else
  1472. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1473. #endif
  1474. #if defined(JSON_HEDLEY_REQUIRE)
  1475. #undef JSON_HEDLEY_REQUIRE
  1476. #endif
  1477. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1478. #undef JSON_HEDLEY_REQUIRE_MSG
  1479. #endif
  1480. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1481. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1482. # define JSON_HEDLEY_REQUIRE(expr) \
  1483. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1484. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1485. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1486. JSON_HEDLEY_DIAGNOSTIC_POP
  1487. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1488. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1489. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1490. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1491. JSON_HEDLEY_DIAGNOSTIC_POP
  1492. # else
  1493. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1494. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1495. # endif
  1496. #else
  1497. # define JSON_HEDLEY_REQUIRE(expr)
  1498. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1499. #endif
  1500. #if defined(JSON_HEDLEY_FLAGS)
  1501. #undef JSON_HEDLEY_FLAGS
  1502. #endif
  1503. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1504. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1505. #endif
  1506. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1507. #undef JSON_HEDLEY_FLAGS_CAST
  1508. #endif
  1509. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1510. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1511. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1512. _Pragma("warning(disable:188)") \
  1513. ((T) (expr)); \
  1514. JSON_HEDLEY_DIAGNOSTIC_POP \
  1515. }))
  1516. #else
  1517. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1518. #endif
  1519. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1520. #undef JSON_HEDLEY_EMPTY_BASES
  1521. #endif
  1522. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1523. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1524. #else
  1525. #define JSON_HEDLEY_EMPTY_BASES
  1526. #endif
  1527. /* Remaining macros are deprecated. */
  1528. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1529. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1530. #endif
  1531. #if defined(__clang__)
  1532. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1533. #else
  1534. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1535. #endif
  1536. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1537. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1538. #endif
  1539. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1540. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1541. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1542. #endif
  1543. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1544. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1545. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1546. #endif
  1547. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1548. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1549. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1550. #endif
  1551. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1552. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1553. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1554. #endif
  1555. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1556. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1557. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1558. #endif
  1559. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1560. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1561. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1562. #endif
  1563. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1564. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1565. // This file contains all internal macro definitions
  1566. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1567. // exclude unsupported compilers
  1568. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1569. #if defined(__clang__)
  1570. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1571. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1572. #endif
  1573. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1574. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1575. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1576. #endif
  1577. #endif
  1578. #endif
  1579. // C++ language standard detection
  1580. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1581. #define JSON_HAS_CPP_17
  1582. #define JSON_HAS_CPP_14
  1583. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1584. #define JSON_HAS_CPP_14
  1585. #endif
  1586. // disable float-equal warnings on GCC/clang
  1587. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1588. #pragma GCC diagnostic push
  1589. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1590. #endif
  1591. // disable documentation warnings on clang
  1592. #if defined(__clang__)
  1593. #pragma GCC diagnostic push
  1594. #pragma GCC diagnostic ignored "-Wdocumentation"
  1595. #endif
  1596. // allow to disable exceptions
  1597. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1598. #define JSON_THROW(exception) throw exception
  1599. #define JSON_TRY try
  1600. #define JSON_CATCH(exception) catch(exception)
  1601. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1602. #else
  1603. #include <cstdlib>
  1604. #define JSON_THROW(exception) std::abort()
  1605. #define JSON_TRY if(true)
  1606. #define JSON_CATCH(exception) if(false)
  1607. #define JSON_INTERNAL_CATCH(exception) if(false)
  1608. #endif
  1609. // override exception macros
  1610. #if defined(JSON_THROW_USER)
  1611. #undef JSON_THROW
  1612. #define JSON_THROW JSON_THROW_USER
  1613. #endif
  1614. #if defined(JSON_TRY_USER)
  1615. #undef JSON_TRY
  1616. #define JSON_TRY JSON_TRY_USER
  1617. #endif
  1618. #if defined(JSON_CATCH_USER)
  1619. #undef JSON_CATCH
  1620. #define JSON_CATCH JSON_CATCH_USER
  1621. #undef JSON_INTERNAL_CATCH
  1622. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1623. #endif
  1624. #if defined(JSON_INTERNAL_CATCH_USER)
  1625. #undef JSON_INTERNAL_CATCH
  1626. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1627. #endif
  1628. /*!
  1629. @brief macro to briefly define a mapping between an enum and JSON
  1630. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1631. @since version 3.4.0
  1632. */
  1633. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1634. template<typename BasicJsonType> \
  1635. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1636. { \
  1637. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1638. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1639. auto it = std::find_if(std::begin(m), std::end(m), \
  1640. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1641. { \
  1642. return ej_pair.first == e; \
  1643. }); \
  1644. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1645. } \
  1646. template<typename BasicJsonType> \
  1647. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1648. { \
  1649. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1650. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1651. auto it = std::find_if(std::begin(m), std::end(m), \
  1652. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1653. { \
  1654. return ej_pair.second == j; \
  1655. }); \
  1656. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1657. }
  1658. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1659. // may be removed in the future once the class is split.
  1660. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1661. template<template<typename, typename, typename...> class ObjectType, \
  1662. template<typename, typename...> class ArrayType, \
  1663. class StringType, class BooleanType, class NumberIntegerType, \
  1664. class NumberUnsignedType, class NumberFloatType, \
  1665. template<typename> class AllocatorType, \
  1666. template<typename, typename = void> class JSONSerializer>
  1667. #define NLOHMANN_BASIC_JSON_TPL \
  1668. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1669. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1670. AllocatorType, JSONSerializer>
  1671. namespace nlohmann
  1672. {
  1673. namespace detail
  1674. {
  1675. ////////////////
  1676. // exceptions //
  1677. ////////////////
  1678. /*!
  1679. @brief general exception of the @ref basic_json class
  1680. This class is an extension of `std::exception` objects with a member @a id for
  1681. exception ids. It is used as the base class for all exceptions thrown by the
  1682. @ref basic_json class. This class can hence be used as "wildcard" to catch
  1683. exceptions.
  1684. Subclasses:
  1685. - @ref parse_error for exceptions indicating a parse error
  1686. - @ref invalid_iterator for exceptions indicating errors with iterators
  1687. - @ref type_error for exceptions indicating executing a member function with
  1688. a wrong type
  1689. - @ref out_of_range for exceptions indicating access out of the defined range
  1690. - @ref other_error for exceptions indicating other library errors
  1691. @internal
  1692. @note To have nothrow-copy-constructible exceptions, we internally use
  1693. `std::runtime_error` which can cope with arbitrary-length error messages.
  1694. Intermediate strings are built with static functions and then passed to
  1695. the actual constructor.
  1696. @endinternal
  1697. @liveexample{The following code shows how arbitrary library exceptions can be
  1698. caught.,exception}
  1699. @since version 3.0.0
  1700. */
  1701. class exception : public std::exception
  1702. {
  1703. public:
  1704. /// returns the explanatory string
  1705. JSON_HEDLEY_RETURNS_NON_NULL
  1706. const char* what() const noexcept override
  1707. {
  1708. return m.what();
  1709. }
  1710. /// the id of the exception
  1711. const int id;
  1712. protected:
  1713. JSON_HEDLEY_NON_NULL(3)
  1714. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  1715. static std::string name(const std::string& ename, int id_)
  1716. {
  1717. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  1718. }
  1719. private:
  1720. /// an exception object as storage for error messages
  1721. std::runtime_error m;
  1722. };
  1723. /*!
  1724. @brief exception indicating a parse error
  1725. This exception is thrown by the library when a parse error occurs. Parse errors
  1726. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  1727. as when using JSON Patch.
  1728. Member @a byte holds the byte index of the last read character in the input
  1729. file.
  1730. Exceptions have ids 1xx.
  1731. name / id | example message | description
  1732. ------------------------------ | --------------- | -------------------------
  1733. 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.
  1734. 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.
  1735. 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.
  1736. 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.
  1737. 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.
  1738. 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`.
  1739. 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.
  1740. 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.
  1741. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  1742. 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.
  1743. 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.
  1744. 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.
  1745. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  1746. @note For an input with n bytes, 1 is the index of the first character and n+1
  1747. is the index of the terminating null byte or the end of file. This also
  1748. holds true when reading a byte vector (CBOR or MessagePack).
  1749. @liveexample{The following code shows how a `parse_error` exception can be
  1750. caught.,parse_error}
  1751. @sa - @ref exception for the base class of the library exceptions
  1752. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1753. @sa - @ref type_error for exceptions indicating executing a member function with
  1754. a wrong type
  1755. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1756. @sa - @ref other_error for exceptions indicating other library errors
  1757. @since version 3.0.0
  1758. */
  1759. class parse_error : public exception
  1760. {
  1761. public:
  1762. /*!
  1763. @brief create a parse error exception
  1764. @param[in] id_ the id of the exception
  1765. @param[in] pos the position where the error occurred (or with
  1766. chars_read_total=0 if the position cannot be
  1767. determined)
  1768. @param[in] what_arg the explanatory string
  1769. @return parse_error object
  1770. */
  1771. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  1772. {
  1773. std::string w = exception::name("parse_error", id_) + "parse error" +
  1774. position_string(pos) + ": " + what_arg;
  1775. return parse_error(id_, pos.chars_read_total, w.c_str());
  1776. }
  1777. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  1778. {
  1779. std::string w = exception::name("parse_error", id_) + "parse error" +
  1780. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  1781. ": " + what_arg;
  1782. return parse_error(id_, byte_, w.c_str());
  1783. }
  1784. /*!
  1785. @brief byte index of the parse error
  1786. The byte index of the last read character in the input file.
  1787. @note For an input with n bytes, 1 is the index of the first character and
  1788. n+1 is the index of the terminating null byte or the end of file.
  1789. This also holds true when reading a byte vector (CBOR or MessagePack).
  1790. */
  1791. const std::size_t byte;
  1792. private:
  1793. parse_error(int id_, std::size_t byte_, const char* what_arg)
  1794. : exception(id_, what_arg), byte(byte_) {}
  1795. static std::string position_string(const position_t& pos)
  1796. {
  1797. return " at line " + std::to_string(pos.lines_read + 1) +
  1798. ", column " + std::to_string(pos.chars_read_current_line);
  1799. }
  1800. };
  1801. /*!
  1802. @brief exception indicating errors with iterators
  1803. This exception is thrown if iterators passed to a library function do not match
  1804. the expected semantics.
  1805. Exceptions have ids 2xx.
  1806. name / id | example message | description
  1807. ----------------------------------- | --------------- | -------------------------
  1808. 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.
  1809. 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.
  1810. 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.
  1811. 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.
  1812. 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.
  1813. 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.
  1814. 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.
  1815. 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.
  1816. 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.
  1817. 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.
  1818. 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.
  1819. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  1820. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  1821. 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().
  1822. @liveexample{The following code shows how an `invalid_iterator` exception can be
  1823. caught.,invalid_iterator}
  1824. @sa - @ref exception for the base class of the library exceptions
  1825. @sa - @ref parse_error for exceptions indicating a parse error
  1826. @sa - @ref type_error for exceptions indicating executing a member function with
  1827. a wrong type
  1828. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1829. @sa - @ref other_error for exceptions indicating other library errors
  1830. @since version 3.0.0
  1831. */
  1832. class invalid_iterator : public exception
  1833. {
  1834. public:
  1835. static invalid_iterator create(int id_, const std::string& what_arg)
  1836. {
  1837. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  1838. return invalid_iterator(id_, w.c_str());
  1839. }
  1840. private:
  1841. JSON_HEDLEY_NON_NULL(3)
  1842. invalid_iterator(int id_, const char* what_arg)
  1843. : exception(id_, what_arg) {}
  1844. };
  1845. /*!
  1846. @brief exception indicating executing a member function with a wrong type
  1847. This exception is thrown in case of a type error; that is, a library function is
  1848. executed on a JSON value whose type does not match the expected semantics.
  1849. Exceptions have ids 3xx.
  1850. name / id | example message | description
  1851. ----------------------------- | --------------- | -------------------------
  1852. 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.
  1853. 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.
  1854. 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 &.
  1855. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  1856. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  1857. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  1858. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  1859. 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.
  1860. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  1861. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  1862. 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.
  1863. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  1864. 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.
  1865. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  1866. 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.
  1867. 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. |
  1868. json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) |
  1869. @liveexample{The following code shows how a `type_error` exception can be
  1870. caught.,type_error}
  1871. @sa - @ref exception for the base class of the library exceptions
  1872. @sa - @ref parse_error for exceptions indicating a parse error
  1873. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1874. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1875. @sa - @ref other_error for exceptions indicating other library errors
  1876. @since version 3.0.0
  1877. */
  1878. class type_error : public exception
  1879. {
  1880. public:
  1881. static type_error create(int id_, const std::string& what_arg)
  1882. {
  1883. std::string w = exception::name("type_error", id_) + what_arg;
  1884. return type_error(id_, w.c_str());
  1885. }
  1886. private:
  1887. JSON_HEDLEY_NON_NULL(3)
  1888. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1889. };
  1890. /*!
  1891. @brief exception indicating access out of the defined range
  1892. This exception is thrown in case a library function is called on an input
  1893. parameter that exceeds the expected range, for instance in case of array
  1894. indices or nonexisting object keys.
  1895. Exceptions have ids 4xx.
  1896. name / id | example message | description
  1897. ------------------------------- | --------------- | -------------------------
  1898. 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.
  1899. 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.
  1900. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  1901. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  1902. 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.
  1903. 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.
  1904. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  1905. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  1906. json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string |
  1907. @liveexample{The following code shows how an `out_of_range` exception can be
  1908. caught.,out_of_range}
  1909. @sa - @ref exception for the base class of the library exceptions
  1910. @sa - @ref parse_error for exceptions indicating a parse error
  1911. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1912. @sa - @ref type_error for exceptions indicating executing a member function with
  1913. a wrong type
  1914. @sa - @ref other_error for exceptions indicating other library errors
  1915. @since version 3.0.0
  1916. */
  1917. class out_of_range : public exception
  1918. {
  1919. public:
  1920. static out_of_range create(int id_, const std::string& what_arg)
  1921. {
  1922. std::string w = exception::name("out_of_range", id_) + what_arg;
  1923. return out_of_range(id_, w.c_str());
  1924. }
  1925. private:
  1926. JSON_HEDLEY_NON_NULL(3)
  1927. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1928. };
  1929. /*!
  1930. @brief exception indicating other library errors
  1931. This exception is thrown in case of errors that cannot be classified with the
  1932. other exception types.
  1933. Exceptions have ids 5xx.
  1934. name / id | example message | description
  1935. ------------------------------ | --------------- | -------------------------
  1936. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  1937. @sa - @ref exception for the base class of the library exceptions
  1938. @sa - @ref parse_error for exceptions indicating a parse error
  1939. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  1940. @sa - @ref type_error for exceptions indicating executing a member function with
  1941. a wrong type
  1942. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  1943. @liveexample{The following code shows how an `other_error` exception can be
  1944. caught.,other_error}
  1945. @since version 3.0.0
  1946. */
  1947. class other_error : public exception
  1948. {
  1949. public:
  1950. static other_error create(int id_, const std::string& what_arg)
  1951. {
  1952. std::string w = exception::name("other_error", id_) + what_arg;
  1953. return other_error(id_, w.c_str());
  1954. }
  1955. private:
  1956. JSON_HEDLEY_NON_NULL(3)
  1957. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  1958. };
  1959. } // namespace detail
  1960. } // namespace nlohmann
  1961. // #include <nlohmann/detail/macro_scope.hpp>
  1962. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1963. #include <ciso646> // not
  1964. #include <cstddef> // size_t
  1965. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  1966. namespace nlohmann
  1967. {
  1968. namespace detail
  1969. {
  1970. // alias templates to reduce boilerplate
  1971. template<bool B, typename T = void>
  1972. using enable_if_t = typename std::enable_if<B, T>::type;
  1973. template<typename T>
  1974. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  1975. // implementation of C++14 index_sequence and affiliates
  1976. // source: https://stackoverflow.com/a/32223343
  1977. template<std::size_t... Ints>
  1978. struct index_sequence
  1979. {
  1980. using type = index_sequence;
  1981. using value_type = std::size_t;
  1982. static constexpr std::size_t size() noexcept
  1983. {
  1984. return sizeof...(Ints);
  1985. }
  1986. };
  1987. template<class Sequence1, class Sequence2>
  1988. struct merge_and_renumber;
  1989. template<std::size_t... I1, std::size_t... I2>
  1990. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  1991. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  1992. template<std::size_t N>
  1993. struct make_index_sequence
  1994. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  1995. typename make_index_sequence < N - N / 2 >::type > {};
  1996. template<> struct make_index_sequence<0> : index_sequence<> {};
  1997. template<> struct make_index_sequence<1> : index_sequence<0> {};
  1998. template<typename... Ts>
  1999. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2000. // dispatch utility (taken from ranges-v3)
  2001. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2002. template<> struct priority_tag<0> {};
  2003. // taken from ranges-v3
  2004. template<typename T>
  2005. struct static_const
  2006. {
  2007. static constexpr T value{};
  2008. };
  2009. template<typename T>
  2010. constexpr T static_const<T>::value;
  2011. } // namespace detail
  2012. } // namespace nlohmann
  2013. // #include <nlohmann/detail/meta/type_traits.hpp>
  2014. #include <ciso646> // not
  2015. #include <limits> // numeric_limits
  2016. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2017. #include <utility> // declval
  2018. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2019. #include <iterator> // random_access_iterator_tag
  2020. // #include <nlohmann/detail/meta/void_t.hpp>
  2021. namespace nlohmann
  2022. {
  2023. namespace detail
  2024. {
  2025. template <typename ...Ts> struct make_void
  2026. {
  2027. using type = void;
  2028. };
  2029. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2030. } // namespace detail
  2031. } // namespace nlohmann
  2032. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2033. namespace nlohmann
  2034. {
  2035. namespace detail
  2036. {
  2037. template <typename It, typename = void>
  2038. struct iterator_types {};
  2039. template <typename It>
  2040. struct iterator_types <
  2041. It,
  2042. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2043. typename It::reference, typename It::iterator_category >>
  2044. {
  2045. using difference_type = typename It::difference_type;
  2046. using value_type = typename It::value_type;
  2047. using pointer = typename It::pointer;
  2048. using reference = typename It::reference;
  2049. using iterator_category = typename It::iterator_category;
  2050. };
  2051. // This is required as some compilers implement std::iterator_traits in a way that
  2052. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2053. template <typename T, typename = void>
  2054. struct iterator_traits
  2055. {
  2056. };
  2057. template <typename T>
  2058. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2059. : iterator_types<T>
  2060. {
  2061. };
  2062. template <typename T>
  2063. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2064. {
  2065. using iterator_category = std::random_access_iterator_tag;
  2066. using value_type = T;
  2067. using difference_type = ptrdiff_t;
  2068. using pointer = T*;
  2069. using reference = T&;
  2070. };
  2071. } // namespace detail
  2072. } // namespace nlohmann
  2073. // #include <nlohmann/detail/macro_scope.hpp>
  2074. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2075. // #include <nlohmann/detail/meta/detected.hpp>
  2076. #include <type_traits>
  2077. // #include <nlohmann/detail/meta/void_t.hpp>
  2078. // http://en.cppreference.com/w/cpp/experimental/is_detected
  2079. namespace nlohmann
  2080. {
  2081. namespace detail
  2082. {
  2083. struct nonesuch
  2084. {
  2085. nonesuch() = delete;
  2086. ~nonesuch() = delete;
  2087. nonesuch(nonesuch const&) = delete;
  2088. nonesuch(nonesuch const&&) = delete;
  2089. void operator=(nonesuch const&) = delete;
  2090. void operator=(nonesuch&&) = delete;
  2091. };
  2092. template <class Default,
  2093. class AlwaysVoid,
  2094. template <class...> class Op,
  2095. class... Args>
  2096. struct detector
  2097. {
  2098. using value_t = std::false_type;
  2099. using type = Default;
  2100. };
  2101. template <class Default, template <class...> class Op, class... Args>
  2102. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2103. {
  2104. using value_t = std::true_type;
  2105. using type = Op<Args...>;
  2106. };
  2107. template <template <class...> class Op, class... Args>
  2108. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2109. template <template <class...> class Op, class... Args>
  2110. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2111. template <class Default, template <class...> class Op, class... Args>
  2112. using detected_or = detector<Default, void, Op, Args...>;
  2113. template <class Default, template <class...> class Op, class... Args>
  2114. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2115. template <class Expected, template <class...> class Op, class... Args>
  2116. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2117. template <class To, template <class...> class Op, class... Args>
  2118. using is_detected_convertible =
  2119. std::is_convertible<detected_t<Op, Args...>, To>;
  2120. } // namespace detail
  2121. } // namespace nlohmann
  2122. // #include <nlohmann/json_fwd.hpp>
  2123. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2124. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2125. #include <cstdint> // int64_t, uint64_t
  2126. #include <map> // map
  2127. #include <memory> // allocator
  2128. #include <string> // string
  2129. #include <vector> // vector
  2130. /*!
  2131. @brief namespace for Niels Lohmann
  2132. @see https://github.com/nlohmann
  2133. @since version 1.0.0
  2134. */
  2135. namespace nlohmann
  2136. {
  2137. /*!
  2138. @brief default JSONSerializer template argument
  2139. This serializer ignores the template arguments and uses ADL
  2140. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2141. for serialization.
  2142. */
  2143. template<typename T = void, typename SFINAE = void>
  2144. struct adl_serializer;
  2145. template<template<typename U, typename V, typename... Args> class ObjectType =
  2146. std::map,
  2147. template<typename U, typename... Args> class ArrayType = std::vector,
  2148. class StringType = std::string, class BooleanType = bool,
  2149. class NumberIntegerType = std::int64_t,
  2150. class NumberUnsignedType = std::uint64_t,
  2151. class NumberFloatType = double,
  2152. template<typename U> class AllocatorType = std::allocator,
  2153. template<typename T, typename SFINAE = void> class JSONSerializer =
  2154. adl_serializer>
  2155. class basic_json;
  2156. /*!
  2157. @brief JSON Pointer
  2158. A JSON pointer defines a string syntax for identifying a specific value
  2159. within a JSON document. It can be used with functions `at` and
  2160. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2161. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2162. @since version 2.0.0
  2163. */
  2164. template<typename BasicJsonType>
  2165. class json_pointer;
  2166. /*!
  2167. @brief default JSON class
  2168. This type is the default specialization of the @ref basic_json class which
  2169. uses the standard template types.
  2170. @since version 1.0.0
  2171. */
  2172. using json = basic_json<>;
  2173. } // namespace nlohmann
  2174. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2175. namespace nlohmann
  2176. {
  2177. /*!
  2178. @brief detail namespace with internal helper functions
  2179. This namespace collects functions that should not be exposed,
  2180. implementations of some @ref basic_json methods, and meta-programming helpers.
  2181. @since version 2.1.0
  2182. */
  2183. namespace detail
  2184. {
  2185. /////////////
  2186. // helpers //
  2187. /////////////
  2188. // Note to maintainers:
  2189. //
  2190. // Every trait in this file expects a non CV-qualified type.
  2191. // The only exceptions are in the 'aliases for detected' section
  2192. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2193. //
  2194. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2195. // (e.g. to_json(BasicJsonType&, const T&))
  2196. template<typename> struct is_basic_json : std::false_type {};
  2197. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2198. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2199. //////////////////////////
  2200. // aliases for detected //
  2201. //////////////////////////
  2202. template <typename T>
  2203. using mapped_type_t = typename T::mapped_type;
  2204. template <typename T>
  2205. using key_type_t = typename T::key_type;
  2206. template <typename T>
  2207. using value_type_t = typename T::value_type;
  2208. template <typename T>
  2209. using difference_type_t = typename T::difference_type;
  2210. template <typename T>
  2211. using pointer_t = typename T::pointer;
  2212. template <typename T>
  2213. using reference_t = typename T::reference;
  2214. template <typename T>
  2215. using iterator_category_t = typename T::iterator_category;
  2216. template <typename T>
  2217. using iterator_t = typename T::iterator;
  2218. template <typename T, typename... Args>
  2219. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2220. template <typename T, typename... Args>
  2221. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2222. template <typename T, typename U>
  2223. using get_template_function = decltype(std::declval<T>().template get<U>());
  2224. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2225. template <typename BasicJsonType, typename T, typename = void>
  2226. struct has_from_json : std::false_type {};
  2227. template <typename BasicJsonType, typename T>
  2228. struct has_from_json<BasicJsonType, T,
  2229. enable_if_t<not is_basic_json<T>::value>>
  2230. {
  2231. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2232. static constexpr bool value =
  2233. is_detected_exact<void, from_json_function, serializer,
  2234. const BasicJsonType&, T&>::value;
  2235. };
  2236. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2237. // this overload is used for non-default-constructible user-defined-types
  2238. template <typename BasicJsonType, typename T, typename = void>
  2239. struct has_non_default_from_json : std::false_type {};
  2240. template<typename BasicJsonType, typename T>
  2241. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2242. {
  2243. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2244. static constexpr bool value =
  2245. is_detected_exact<T, from_json_function, serializer,
  2246. const BasicJsonType&>::value;
  2247. };
  2248. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2249. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2250. template <typename BasicJsonType, typename T, typename = void>
  2251. struct has_to_json : std::false_type {};
  2252. template <typename BasicJsonType, typename T>
  2253. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  2254. {
  2255. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2256. static constexpr bool value =
  2257. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2258. T>::value;
  2259. };
  2260. ///////////////////
  2261. // is_ functions //
  2262. ///////////////////
  2263. template <typename T, typename = void>
  2264. struct is_iterator_traits : std::false_type {};
  2265. template <typename T>
  2266. struct is_iterator_traits<iterator_traits<T>>
  2267. {
  2268. private:
  2269. using traits = iterator_traits<T>;
  2270. public:
  2271. static constexpr auto value =
  2272. is_detected<value_type_t, traits>::value &&
  2273. is_detected<difference_type_t, traits>::value &&
  2274. is_detected<pointer_t, traits>::value &&
  2275. is_detected<iterator_category_t, traits>::value &&
  2276. is_detected<reference_t, traits>::value;
  2277. };
  2278. // source: https://stackoverflow.com/a/37193089/4116453
  2279. template <typename T, typename = void>
  2280. struct is_complete_type : std::false_type {};
  2281. template <typename T>
  2282. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2283. template <typename BasicJsonType, typename CompatibleObjectType,
  2284. typename = void>
  2285. struct is_compatible_object_type_impl : std::false_type {};
  2286. template <typename BasicJsonType, typename CompatibleObjectType>
  2287. struct is_compatible_object_type_impl <
  2288. BasicJsonType, CompatibleObjectType,
  2289. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  2290. is_detected<key_type_t, CompatibleObjectType>::value >>
  2291. {
  2292. using object_t = typename BasicJsonType::object_t;
  2293. // macOS's is_constructible does not play well with nonesuch...
  2294. static constexpr bool value =
  2295. std::is_constructible<typename object_t::key_type,
  2296. typename CompatibleObjectType::key_type>::value and
  2297. std::is_constructible<typename object_t::mapped_type,
  2298. typename CompatibleObjectType::mapped_type>::value;
  2299. };
  2300. template <typename BasicJsonType, typename CompatibleObjectType>
  2301. struct is_compatible_object_type
  2302. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2303. template <typename BasicJsonType, typename ConstructibleObjectType,
  2304. typename = void>
  2305. struct is_constructible_object_type_impl : std::false_type {};
  2306. template <typename BasicJsonType, typename ConstructibleObjectType>
  2307. struct is_constructible_object_type_impl <
  2308. BasicJsonType, ConstructibleObjectType,
  2309. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  2310. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2311. {
  2312. using object_t = typename BasicJsonType::object_t;
  2313. static constexpr bool value =
  2314. (std::is_default_constructible<ConstructibleObjectType>::value and
  2315. (std::is_move_assignable<ConstructibleObjectType>::value or
  2316. std::is_copy_assignable<ConstructibleObjectType>::value) and
  2317. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2318. typename object_t::key_type>::value and
  2319. std::is_same <
  2320. typename object_t::mapped_type,
  2321. typename ConstructibleObjectType::mapped_type >::value)) or
  2322. (has_from_json<BasicJsonType,
  2323. typename ConstructibleObjectType::mapped_type>::value or
  2324. has_non_default_from_json <
  2325. BasicJsonType,
  2326. typename ConstructibleObjectType::mapped_type >::value);
  2327. };
  2328. template <typename BasicJsonType, typename ConstructibleObjectType>
  2329. struct is_constructible_object_type
  2330. : is_constructible_object_type_impl<BasicJsonType,
  2331. ConstructibleObjectType> {};
  2332. template <typename BasicJsonType, typename CompatibleStringType,
  2333. typename = void>
  2334. struct is_compatible_string_type_impl : std::false_type {};
  2335. template <typename BasicJsonType, typename CompatibleStringType>
  2336. struct is_compatible_string_type_impl <
  2337. BasicJsonType, CompatibleStringType,
  2338. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2339. value_type_t, CompatibleStringType>::value >>
  2340. {
  2341. static constexpr auto value =
  2342. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2343. };
  2344. template <typename BasicJsonType, typename ConstructibleStringType>
  2345. struct is_compatible_string_type
  2346. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2347. template <typename BasicJsonType, typename ConstructibleStringType,
  2348. typename = void>
  2349. struct is_constructible_string_type_impl : std::false_type {};
  2350. template <typename BasicJsonType, typename ConstructibleStringType>
  2351. struct is_constructible_string_type_impl <
  2352. BasicJsonType, ConstructibleStringType,
  2353. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2354. value_type_t, ConstructibleStringType>::value >>
  2355. {
  2356. static constexpr auto value =
  2357. std::is_constructible<ConstructibleStringType,
  2358. typename BasicJsonType::string_t>::value;
  2359. };
  2360. template <typename BasicJsonType, typename ConstructibleStringType>
  2361. struct is_constructible_string_type
  2362. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2363. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2364. struct is_compatible_array_type_impl : std::false_type {};
  2365. template <typename BasicJsonType, typename CompatibleArrayType>
  2366. struct is_compatible_array_type_impl <
  2367. BasicJsonType, CompatibleArrayType,
  2368. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  2369. is_detected<iterator_t, CompatibleArrayType>::value and
  2370. // This is needed because json_reverse_iterator has a ::iterator type...
  2371. // Therefore it is detected as a CompatibleArrayType.
  2372. // The real fix would be to have an Iterable concept.
  2373. not is_iterator_traits<
  2374. iterator_traits<CompatibleArrayType>>::value >>
  2375. {
  2376. static constexpr bool value =
  2377. std::is_constructible<BasicJsonType,
  2378. typename CompatibleArrayType::value_type>::value;
  2379. };
  2380. template <typename BasicJsonType, typename CompatibleArrayType>
  2381. struct is_compatible_array_type
  2382. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2383. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2384. struct is_constructible_array_type_impl : std::false_type {};
  2385. template <typename BasicJsonType, typename ConstructibleArrayType>
  2386. struct is_constructible_array_type_impl <
  2387. BasicJsonType, ConstructibleArrayType,
  2388. enable_if_t<std::is_same<ConstructibleArrayType,
  2389. typename BasicJsonType::value_type>::value >>
  2390. : std::true_type {};
  2391. template <typename BasicJsonType, typename ConstructibleArrayType>
  2392. struct is_constructible_array_type_impl <
  2393. BasicJsonType, ConstructibleArrayType,
  2394. enable_if_t<not std::is_same<ConstructibleArrayType,
  2395. typename BasicJsonType::value_type>::value and
  2396. std::is_default_constructible<ConstructibleArrayType>::value and
  2397. (std::is_move_assignable<ConstructibleArrayType>::value or
  2398. std::is_copy_assignable<ConstructibleArrayType>::value) and
  2399. is_detected<value_type_t, ConstructibleArrayType>::value and
  2400. is_detected<iterator_t, ConstructibleArrayType>::value and
  2401. is_complete_type<
  2402. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  2403. {
  2404. static constexpr bool value =
  2405. // This is needed because json_reverse_iterator has a ::iterator type,
  2406. // furthermore, std::back_insert_iterator (and other iterators) have a
  2407. // base class `iterator`... Therefore it is detected as a
  2408. // ConstructibleArrayType. The real fix would be to have an Iterable
  2409. // concept.
  2410. not is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value and
  2411. (std::is_same<typename ConstructibleArrayType::value_type,
  2412. typename BasicJsonType::array_t::value_type>::value or
  2413. has_from_json<BasicJsonType,
  2414. typename ConstructibleArrayType::value_type>::value or
  2415. has_non_default_from_json <
  2416. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2417. };
  2418. template <typename BasicJsonType, typename ConstructibleArrayType>
  2419. struct is_constructible_array_type
  2420. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2421. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  2422. typename = void>
  2423. struct is_compatible_integer_type_impl : std::false_type {};
  2424. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2425. struct is_compatible_integer_type_impl <
  2426. RealIntegerType, CompatibleNumberIntegerType,
  2427. enable_if_t<std::is_integral<RealIntegerType>::value and
  2428. std::is_integral<CompatibleNumberIntegerType>::value and
  2429. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2430. {
  2431. // is there an assert somewhere on overflows?
  2432. using RealLimits = std::numeric_limits<RealIntegerType>;
  2433. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2434. static constexpr auto value =
  2435. std::is_constructible<RealIntegerType,
  2436. CompatibleNumberIntegerType>::value and
  2437. CompatibleLimits::is_integer and
  2438. RealLimits::is_signed == CompatibleLimits::is_signed;
  2439. };
  2440. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  2441. struct is_compatible_integer_type
  2442. : is_compatible_integer_type_impl<RealIntegerType,
  2443. CompatibleNumberIntegerType> {};
  2444. template <typename BasicJsonType, typename CompatibleType, typename = void>
  2445. struct is_compatible_type_impl: std::false_type {};
  2446. template <typename BasicJsonType, typename CompatibleType>
  2447. struct is_compatible_type_impl <
  2448. BasicJsonType, CompatibleType,
  2449. enable_if_t<is_complete_type<CompatibleType>::value >>
  2450. {
  2451. static constexpr bool value =
  2452. has_to_json<BasicJsonType, CompatibleType>::value;
  2453. };
  2454. template <typename BasicJsonType, typename CompatibleType>
  2455. struct is_compatible_type
  2456. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2457. // https://en.cppreference.com/w/cpp/types/conjunction
  2458. template<class...> struct conjunction : std::true_type { };
  2459. template<class B1> struct conjunction<B1> : B1 { };
  2460. template<class B1, class... Bn>
  2461. struct conjunction<B1, Bn...>
  2462. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  2463. template <typename T1, typename T2>
  2464. struct is_constructible_tuple : std::false_type {};
  2465. template <typename T1, typename... Args>
  2466. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
  2467. } // namespace detail
  2468. } // namespace nlohmann
  2469. // #include <nlohmann/detail/value_t.hpp>
  2470. #include <array> // array
  2471. #include <ciso646> // and
  2472. #include <cstddef> // size_t
  2473. #include <cstdint> // uint8_t
  2474. #include <string> // string
  2475. namespace nlohmann
  2476. {
  2477. namespace detail
  2478. {
  2479. ///////////////////////////
  2480. // JSON type enumeration //
  2481. ///////////////////////////
  2482. /*!
  2483. @brief the JSON type enumeration
  2484. This enumeration collects the different JSON types. It is internally used to
  2485. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2486. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2487. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2488. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2489. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2490. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2491. @ref basic_json::is_structured() rely on it.
  2492. @note There are three enumeration entries (number_integer, number_unsigned, and
  2493. number_float), because the library distinguishes these three types for numbers:
  2494. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2495. @ref basic_json::number_integer_t is used for signed integers, and
  2496. @ref basic_json::number_float_t is used for floating-point numbers or to
  2497. approximate integers which do not fit in the limits of their respective type.
  2498. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2499. value with the default value for a given type
  2500. @since version 1.0.0
  2501. */
  2502. enum class value_t : std::uint8_t
  2503. {
  2504. null, ///< null value
  2505. object, ///< object (unordered set of name/value pairs)
  2506. array, ///< array (ordered collection of values)
  2507. string, ///< string value
  2508. boolean, ///< boolean value
  2509. number_integer, ///< number value (signed integer)
  2510. number_unsigned, ///< number value (unsigned integer)
  2511. number_float, ///< number value (floating-point)
  2512. discarded ///< discarded by the the parser callback function
  2513. };
  2514. /*!
  2515. @brief comparison operator for JSON types
  2516. Returns an ordering that is similar to Python:
  2517. - order: null < boolean < number < object < array < string
  2518. - furthermore, each type is not smaller than itself
  2519. - discarded values are not comparable
  2520. @since version 1.0.0
  2521. */
  2522. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2523. {
  2524. static constexpr std::array<std::uint8_t, 8> order = {{
  2525. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2526. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  2527. }
  2528. };
  2529. const auto l_index = static_cast<std::size_t>(lhs);
  2530. const auto r_index = static_cast<std::size_t>(rhs);
  2531. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  2532. }
  2533. } // namespace detail
  2534. } // namespace nlohmann
  2535. namespace nlohmann
  2536. {
  2537. namespace detail
  2538. {
  2539. template<typename BasicJsonType>
  2540. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2541. {
  2542. if (JSON_HEDLEY_UNLIKELY(not j.is_null()))
  2543. {
  2544. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2545. }
  2546. n = nullptr;
  2547. }
  2548. // overloads for basic_json template parameters
  2549. template<typename BasicJsonType, typename ArithmeticType,
  2550. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  2551. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2552. int> = 0>
  2553. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2554. {
  2555. switch (static_cast<value_t>(j))
  2556. {
  2557. case value_t::number_unsigned:
  2558. {
  2559. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2560. break;
  2561. }
  2562. case value_t::number_integer:
  2563. {
  2564. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2565. break;
  2566. }
  2567. case value_t::number_float:
  2568. {
  2569. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2570. break;
  2571. }
  2572. default:
  2573. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2574. }
  2575. }
  2576. template<typename BasicJsonType>
  2577. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2578. {
  2579. if (JSON_HEDLEY_UNLIKELY(not j.is_boolean()))
  2580. {
  2581. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2582. }
  2583. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2584. }
  2585. template<typename BasicJsonType>
  2586. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2587. {
  2588. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2589. {
  2590. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2591. }
  2592. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2593. }
  2594. template <
  2595. typename BasicJsonType, typename ConstructibleStringType,
  2596. enable_if_t <
  2597. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  2598. not std::is_same<typename BasicJsonType::string_t,
  2599. ConstructibleStringType>::value,
  2600. int > = 0 >
  2601. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2602. {
  2603. if (JSON_HEDLEY_UNLIKELY(not j.is_string()))
  2604. {
  2605. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2606. }
  2607. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2608. }
  2609. template<typename BasicJsonType>
  2610. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2611. {
  2612. get_arithmetic_value(j, val);
  2613. }
  2614. template<typename BasicJsonType>
  2615. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2616. {
  2617. get_arithmetic_value(j, val);
  2618. }
  2619. template<typename BasicJsonType>
  2620. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2621. {
  2622. get_arithmetic_value(j, val);
  2623. }
  2624. template<typename BasicJsonType, typename EnumType,
  2625. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2626. void from_json(const BasicJsonType& j, EnumType& e)
  2627. {
  2628. typename std::underlying_type<EnumType>::type val;
  2629. get_arithmetic_value(j, val);
  2630. e = static_cast<EnumType>(val);
  2631. }
  2632. // forward_list doesn't have an insert method
  2633. template<typename BasicJsonType, typename T, typename Allocator,
  2634. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2635. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  2636. {
  2637. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2638. {
  2639. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2640. }
  2641. l.clear();
  2642. std::transform(j.rbegin(), j.rend(),
  2643. std::front_inserter(l), [](const BasicJsonType & i)
  2644. {
  2645. return i.template get<T>();
  2646. });
  2647. }
  2648. // valarray doesn't have an insert method
  2649. template<typename BasicJsonType, typename T,
  2650. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  2651. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  2652. {
  2653. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2654. {
  2655. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2656. }
  2657. l.resize(j.size());
  2658. std::copy(j.begin(), j.end(), std::begin(l));
  2659. }
  2660. template <typename BasicJsonType, typename T, std::size_t N>
  2661. auto from_json(const BasicJsonType& j, T (&arr)[N])
  2662. -> decltype(j.template get<T>(), void())
  2663. {
  2664. for (std::size_t i = 0; i < N; ++i)
  2665. {
  2666. arr[i] = j.at(i).template get<T>();
  2667. }
  2668. }
  2669. template<typename BasicJsonType>
  2670. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  2671. {
  2672. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  2673. }
  2674. template <typename BasicJsonType, typename T, std::size_t N>
  2675. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  2676. priority_tag<2> /*unused*/)
  2677. -> decltype(j.template get<T>(), void())
  2678. {
  2679. for (std::size_t i = 0; i < N; ++i)
  2680. {
  2681. arr[i] = j.at(i).template get<T>();
  2682. }
  2683. }
  2684. template<typename BasicJsonType, typename ConstructibleArrayType>
  2685. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  2686. -> decltype(
  2687. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  2688. j.template get<typename ConstructibleArrayType::value_type>(),
  2689. void())
  2690. {
  2691. using std::end;
  2692. ConstructibleArrayType ret;
  2693. ret.reserve(j.size());
  2694. std::transform(j.begin(), j.end(),
  2695. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  2696. {
  2697. // get<BasicJsonType>() returns *this, this won't call a from_json
  2698. // method when value_type is BasicJsonType
  2699. return i.template get<typename ConstructibleArrayType::value_type>();
  2700. });
  2701. arr = std::move(ret);
  2702. }
  2703. template <typename BasicJsonType, typename ConstructibleArrayType>
  2704. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  2705. priority_tag<0> /*unused*/)
  2706. {
  2707. using std::end;
  2708. ConstructibleArrayType ret;
  2709. std::transform(
  2710. j.begin(), j.end(), std::inserter(ret, end(ret)),
  2711. [](const BasicJsonType & i)
  2712. {
  2713. // get<BasicJsonType>() returns *this, this won't call a from_json
  2714. // method when value_type is BasicJsonType
  2715. return i.template get<typename ConstructibleArrayType::value_type>();
  2716. });
  2717. arr = std::move(ret);
  2718. }
  2719. template <typename BasicJsonType, typename ConstructibleArrayType,
  2720. enable_if_t <
  2721. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  2722. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  2723. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  2724. not is_basic_json<ConstructibleArrayType>::value,
  2725. int > = 0 >
  2726. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  2727. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  2728. j.template get<typename ConstructibleArrayType::value_type>(),
  2729. void())
  2730. {
  2731. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2732. {
  2733. JSON_THROW(type_error::create(302, "type must be array, but is " +
  2734. std::string(j.type_name())));
  2735. }
  2736. from_json_array_impl(j, arr, priority_tag<3> {});
  2737. }
  2738. template<typename BasicJsonType, typename ConstructibleObjectType,
  2739. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  2740. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  2741. {
  2742. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  2743. {
  2744. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  2745. }
  2746. ConstructibleObjectType ret;
  2747. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  2748. using value_type = typename ConstructibleObjectType::value_type;
  2749. std::transform(
  2750. inner_object->begin(), inner_object->end(),
  2751. std::inserter(ret, ret.begin()),
  2752. [](typename BasicJsonType::object_t::value_type const & p)
  2753. {
  2754. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  2755. });
  2756. obj = std::move(ret);
  2757. }
  2758. // overload for arithmetic types, not chosen for basic_json template arguments
  2759. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  2760. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  2761. // an arithmetic type?
  2762. template<typename BasicJsonType, typename ArithmeticType,
  2763. enable_if_t <
  2764. std::is_arithmetic<ArithmeticType>::value and
  2765. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  2766. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  2767. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  2768. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2769. int> = 0>
  2770. void from_json(const BasicJsonType& j, ArithmeticType& val)
  2771. {
  2772. switch (static_cast<value_t>(j))
  2773. {
  2774. case value_t::number_unsigned:
  2775. {
  2776. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2777. break;
  2778. }
  2779. case value_t::number_integer:
  2780. {
  2781. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2782. break;
  2783. }
  2784. case value_t::number_float:
  2785. {
  2786. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2787. break;
  2788. }
  2789. case value_t::boolean:
  2790. {
  2791. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  2792. break;
  2793. }
  2794. default:
  2795. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2796. }
  2797. }
  2798. template<typename BasicJsonType, typename A1, typename A2>
  2799. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  2800. {
  2801. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  2802. }
  2803. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  2804. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  2805. {
  2806. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  2807. }
  2808. template<typename BasicJsonType, typename... Args>
  2809. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  2810. {
  2811. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  2812. }
  2813. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  2814. typename = enable_if_t<not std::is_constructible<
  2815. typename BasicJsonType::string_t, Key>::value>>
  2816. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  2817. {
  2818. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2819. {
  2820. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2821. }
  2822. m.clear();
  2823. for (const auto& p : j)
  2824. {
  2825. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2826. {
  2827. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2828. }
  2829. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2830. }
  2831. }
  2832. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  2833. typename = enable_if_t<not std::is_constructible<
  2834. typename BasicJsonType::string_t, Key>::value>>
  2835. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  2836. {
  2837. if (JSON_HEDLEY_UNLIKELY(not j.is_array()))
  2838. {
  2839. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  2840. }
  2841. m.clear();
  2842. for (const auto& p : j)
  2843. {
  2844. if (JSON_HEDLEY_UNLIKELY(not p.is_array()))
  2845. {
  2846. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  2847. }
  2848. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  2849. }
  2850. }
  2851. struct from_json_fn
  2852. {
  2853. template<typename BasicJsonType, typename T>
  2854. auto operator()(const BasicJsonType& j, T& val) const
  2855. noexcept(noexcept(from_json(j, val)))
  2856. -> decltype(from_json(j, val), void())
  2857. {
  2858. return from_json(j, val);
  2859. }
  2860. };
  2861. } // namespace detail
  2862. /// namespace to hold default `from_json` function
  2863. /// to see why this is required:
  2864. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  2865. namespace
  2866. {
  2867. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  2868. } // namespace
  2869. } // namespace nlohmann
  2870. // #include <nlohmann/detail/conversions/to_json.hpp>
  2871. #include <algorithm> // copy
  2872. #include <ciso646> // or, and, not
  2873. #include <iterator> // begin, end
  2874. #include <string> // string
  2875. #include <tuple> // tuple, get
  2876. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  2877. #include <utility> // move, forward, declval, pair
  2878. #include <valarray> // valarray
  2879. #include <vector> // vector
  2880. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  2881. #include <cstddef> // size_t
  2882. #include <iterator> // input_iterator_tag
  2883. #include <string> // string, to_string
  2884. #include <tuple> // tuple_size, get, tuple_element
  2885. // #include <nlohmann/detail/meta/type_traits.hpp>
  2886. // #include <nlohmann/detail/value_t.hpp>
  2887. namespace nlohmann
  2888. {
  2889. namespace detail
  2890. {
  2891. template<typename string_type>
  2892. void int_to_string( string_type& target, std::size_t value )
  2893. {
  2894. target = std::to_string(value);
  2895. }
  2896. template <typename IteratorType> class iteration_proxy_value
  2897. {
  2898. public:
  2899. using difference_type = std::ptrdiff_t;
  2900. using value_type = iteration_proxy_value;
  2901. using pointer = value_type * ;
  2902. using reference = value_type & ;
  2903. using iterator_category = std::input_iterator_tag;
  2904. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  2905. private:
  2906. /// the iterator
  2907. IteratorType anchor;
  2908. /// an index for arrays (used to create key names)
  2909. std::size_t array_index = 0;
  2910. /// last stringified array index
  2911. mutable std::size_t array_index_last = 0;
  2912. /// a string representation of the array index
  2913. mutable string_type array_index_str = "0";
  2914. /// an empty string (to return a reference for primitive values)
  2915. const string_type empty_str = "";
  2916. public:
  2917. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  2918. /// dereference operator (needed for range-based for)
  2919. iteration_proxy_value& operator*()
  2920. {
  2921. return *this;
  2922. }
  2923. /// increment operator (needed for range-based for)
  2924. iteration_proxy_value& operator++()
  2925. {
  2926. ++anchor;
  2927. ++array_index;
  2928. return *this;
  2929. }
  2930. /// equality operator (needed for InputIterator)
  2931. bool operator==(const iteration_proxy_value& o) const
  2932. {
  2933. return anchor == o.anchor;
  2934. }
  2935. /// inequality operator (needed for range-based for)
  2936. bool operator!=(const iteration_proxy_value& o) const
  2937. {
  2938. return anchor != o.anchor;
  2939. }
  2940. /// return key of the iterator
  2941. const string_type& key() const
  2942. {
  2943. assert(anchor.m_object != nullptr);
  2944. switch (anchor.m_object->type())
  2945. {
  2946. // use integer array index as key
  2947. case value_t::array:
  2948. {
  2949. if (array_index != array_index_last)
  2950. {
  2951. int_to_string( array_index_str, array_index );
  2952. array_index_last = array_index;
  2953. }
  2954. return array_index_str;
  2955. }
  2956. // use key from the object
  2957. case value_t::object:
  2958. return anchor.key();
  2959. // use an empty key for all primitive types
  2960. default:
  2961. return empty_str;
  2962. }
  2963. }
  2964. /// return value of the iterator
  2965. typename IteratorType::reference value() const
  2966. {
  2967. return anchor.value();
  2968. }
  2969. };
  2970. /// proxy class for the items() function
  2971. template<typename IteratorType> class iteration_proxy
  2972. {
  2973. private:
  2974. /// the container to iterate
  2975. typename IteratorType::reference container;
  2976. public:
  2977. /// construct iteration proxy from a container
  2978. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  2979. : container(cont) {}
  2980. /// return iterator begin (needed for range-based for)
  2981. iteration_proxy_value<IteratorType> begin() noexcept
  2982. {
  2983. return iteration_proxy_value<IteratorType>(container.begin());
  2984. }
  2985. /// return iterator end (needed for range-based for)
  2986. iteration_proxy_value<IteratorType> end() noexcept
  2987. {
  2988. return iteration_proxy_value<IteratorType>(container.end());
  2989. }
  2990. };
  2991. // Structured Bindings Support
  2992. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  2993. // And see https://github.com/nlohmann/json/pull/1391
  2994. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  2995. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  2996. {
  2997. return i.key();
  2998. }
  2999. // Structured Bindings Support
  3000. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3001. // And see https://github.com/nlohmann/json/pull/1391
  3002. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3003. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3004. {
  3005. return i.value();
  3006. }
  3007. } // namespace detail
  3008. } // namespace nlohmann
  3009. // The Addition to the STD Namespace is required to add
  3010. // Structured Bindings Support to the iteration_proxy_value class
  3011. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3012. // And see https://github.com/nlohmann/json/pull/1391
  3013. namespace std
  3014. {
  3015. #if defined(__clang__)
  3016. // Fix: https://github.com/nlohmann/json/issues/1401
  3017. #pragma clang diagnostic push
  3018. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3019. #endif
  3020. template <typename IteratorType>
  3021. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3022. : public std::integral_constant<std::size_t, 2> {};
  3023. template <std::size_t N, typename IteratorType>
  3024. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3025. {
  3026. public:
  3027. using type = decltype(
  3028. get<N>(std::declval <
  3029. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3030. };
  3031. #if defined(__clang__)
  3032. #pragma clang diagnostic pop
  3033. #endif
  3034. } // namespace std
  3035. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3036. // #include <nlohmann/detail/meta/type_traits.hpp>
  3037. // #include <nlohmann/detail/value_t.hpp>
  3038. namespace nlohmann
  3039. {
  3040. namespace detail
  3041. {
  3042. //////////////////
  3043. // constructors //
  3044. //////////////////
  3045. template<value_t> struct external_constructor;
  3046. template<>
  3047. struct external_constructor<value_t::boolean>
  3048. {
  3049. template<typename BasicJsonType>
  3050. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3051. {
  3052. j.m_type = value_t::boolean;
  3053. j.m_value = b;
  3054. j.assert_invariant();
  3055. }
  3056. };
  3057. template<>
  3058. struct external_constructor<value_t::string>
  3059. {
  3060. template<typename BasicJsonType>
  3061. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3062. {
  3063. j.m_type = value_t::string;
  3064. j.m_value = s;
  3065. j.assert_invariant();
  3066. }
  3067. template<typename BasicJsonType>
  3068. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3069. {
  3070. j.m_type = value_t::string;
  3071. j.m_value = std::move(s);
  3072. j.assert_invariant();
  3073. }
  3074. template<typename BasicJsonType, typename CompatibleStringType,
  3075. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3076. int> = 0>
  3077. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3078. {
  3079. j.m_type = value_t::string;
  3080. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3081. j.assert_invariant();
  3082. }
  3083. };
  3084. template<>
  3085. struct external_constructor<value_t::number_float>
  3086. {
  3087. template<typename BasicJsonType>
  3088. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3089. {
  3090. j.m_type = value_t::number_float;
  3091. j.m_value = val;
  3092. j.assert_invariant();
  3093. }
  3094. };
  3095. template<>
  3096. struct external_constructor<value_t::number_unsigned>
  3097. {
  3098. template<typename BasicJsonType>
  3099. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3100. {
  3101. j.m_type = value_t::number_unsigned;
  3102. j.m_value = val;
  3103. j.assert_invariant();
  3104. }
  3105. };
  3106. template<>
  3107. struct external_constructor<value_t::number_integer>
  3108. {
  3109. template<typename BasicJsonType>
  3110. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3111. {
  3112. j.m_type = value_t::number_integer;
  3113. j.m_value = val;
  3114. j.assert_invariant();
  3115. }
  3116. };
  3117. template<>
  3118. struct external_constructor<value_t::array>
  3119. {
  3120. template<typename BasicJsonType>
  3121. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3122. {
  3123. j.m_type = value_t::array;
  3124. j.m_value = arr;
  3125. j.assert_invariant();
  3126. }
  3127. template<typename BasicJsonType>
  3128. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3129. {
  3130. j.m_type = value_t::array;
  3131. j.m_value = std::move(arr);
  3132. j.assert_invariant();
  3133. }
  3134. template<typename BasicJsonType, typename CompatibleArrayType,
  3135. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3136. int> = 0>
  3137. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3138. {
  3139. using std::begin;
  3140. using std::end;
  3141. j.m_type = value_t::array;
  3142. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3143. j.assert_invariant();
  3144. }
  3145. template<typename BasicJsonType>
  3146. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3147. {
  3148. j.m_type = value_t::array;
  3149. j.m_value = value_t::array;
  3150. j.m_value.array->reserve(arr.size());
  3151. for (const bool x : arr)
  3152. {
  3153. j.m_value.array->push_back(x);
  3154. }
  3155. j.assert_invariant();
  3156. }
  3157. template<typename BasicJsonType, typename T,
  3158. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3159. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3160. {
  3161. j.m_type = value_t::array;
  3162. j.m_value = value_t::array;
  3163. j.m_value.array->resize(arr.size());
  3164. if (arr.size() > 0)
  3165. {
  3166. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3167. }
  3168. j.assert_invariant();
  3169. }
  3170. };
  3171. template<>
  3172. struct external_constructor<value_t::object>
  3173. {
  3174. template<typename BasicJsonType>
  3175. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3176. {
  3177. j.m_type = value_t::object;
  3178. j.m_value = obj;
  3179. j.assert_invariant();
  3180. }
  3181. template<typename BasicJsonType>
  3182. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3183. {
  3184. j.m_type = value_t::object;
  3185. j.m_value = std::move(obj);
  3186. j.assert_invariant();
  3187. }
  3188. template<typename BasicJsonType, typename CompatibleObjectType,
  3189. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  3190. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3191. {
  3192. using std::begin;
  3193. using std::end;
  3194. j.m_type = value_t::object;
  3195. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3196. j.assert_invariant();
  3197. }
  3198. };
  3199. /////////////
  3200. // to_json //
  3201. /////////////
  3202. template<typename BasicJsonType, typename T,
  3203. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3204. void to_json(BasicJsonType& j, T b) noexcept
  3205. {
  3206. external_constructor<value_t::boolean>::construct(j, b);
  3207. }
  3208. template<typename BasicJsonType, typename CompatibleString,
  3209. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3210. void to_json(BasicJsonType& j, const CompatibleString& s)
  3211. {
  3212. external_constructor<value_t::string>::construct(j, s);
  3213. }
  3214. template<typename BasicJsonType>
  3215. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3216. {
  3217. external_constructor<value_t::string>::construct(j, std::move(s));
  3218. }
  3219. template<typename BasicJsonType, typename FloatType,
  3220. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3221. void to_json(BasicJsonType& j, FloatType val) noexcept
  3222. {
  3223. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3224. }
  3225. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3226. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3227. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3228. {
  3229. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3230. }
  3231. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3232. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3233. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3234. {
  3235. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3236. }
  3237. template<typename BasicJsonType, typename EnumType,
  3238. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3239. void to_json(BasicJsonType& j, EnumType e) noexcept
  3240. {
  3241. using underlying_type = typename std::underlying_type<EnumType>::type;
  3242. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3243. }
  3244. template<typename BasicJsonType>
  3245. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3246. {
  3247. external_constructor<value_t::array>::construct(j, e);
  3248. }
  3249. template <typename BasicJsonType, typename CompatibleArrayType,
  3250. enable_if_t<is_compatible_array_type<BasicJsonType,
  3251. CompatibleArrayType>::value and
  3252. not is_compatible_object_type<
  3253. BasicJsonType, CompatibleArrayType>::value and
  3254. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  3255. not is_basic_json<CompatibleArrayType>::value,
  3256. int> = 0>
  3257. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3258. {
  3259. external_constructor<value_t::array>::construct(j, arr);
  3260. }
  3261. template<typename BasicJsonType, typename T,
  3262. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3263. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3264. {
  3265. external_constructor<value_t::array>::construct(j, std::move(arr));
  3266. }
  3267. template<typename BasicJsonType>
  3268. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3269. {
  3270. external_constructor<value_t::array>::construct(j, std::move(arr));
  3271. }
  3272. template<typename BasicJsonType, typename CompatibleObjectType,
  3273. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  3274. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3275. {
  3276. external_constructor<value_t::object>::construct(j, obj);
  3277. }
  3278. template<typename BasicJsonType>
  3279. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3280. {
  3281. external_constructor<value_t::object>::construct(j, std::move(obj));
  3282. }
  3283. template <
  3284. typename BasicJsonType, typename T, std::size_t N,
  3285. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  3286. const T(&)[N]>::value,
  3287. int> = 0 >
  3288. void to_json(BasicJsonType& j, const T(&arr)[N])
  3289. {
  3290. external_constructor<value_t::array>::construct(j, arr);
  3291. }
  3292. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  3293. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  3294. {
  3295. j = { p.first, p.second };
  3296. }
  3297. // for https://github.com/nlohmann/json/pull/1134
  3298. template < typename BasicJsonType, typename T,
  3299. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3300. void to_json(BasicJsonType& j, const T& b)
  3301. {
  3302. j = { {b.key(), b.value()} };
  3303. }
  3304. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3305. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3306. {
  3307. j = { std::get<Idx>(t)... };
  3308. }
  3309. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  3310. void to_json(BasicJsonType& j, const T& t)
  3311. {
  3312. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  3313. }
  3314. struct to_json_fn
  3315. {
  3316. template<typename BasicJsonType, typename T>
  3317. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3318. -> decltype(to_json(j, std::forward<T>(val)), void())
  3319. {
  3320. return to_json(j, std::forward<T>(val));
  3321. }
  3322. };
  3323. } // namespace detail
  3324. /// namespace to hold default `to_json` function
  3325. namespace
  3326. {
  3327. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3328. } // namespace
  3329. } // namespace nlohmann
  3330. namespace nlohmann
  3331. {
  3332. template<typename, typename>
  3333. struct adl_serializer
  3334. {
  3335. /*!
  3336. @brief convert a JSON value to any value type
  3337. This function is usually called by the `get()` function of the
  3338. @ref basic_json class (either explicit or via conversion operators).
  3339. @param[in] j JSON value to read from
  3340. @param[in,out] val value to write to
  3341. */
  3342. template<typename BasicJsonType, typename ValueType>
  3343. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3344. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3345. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3346. {
  3347. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3348. }
  3349. /*!
  3350. @brief convert any value type to a JSON value
  3351. This function is usually called by the constructors of the @ref basic_json
  3352. class.
  3353. @param[in,out] j JSON value to write to
  3354. @param[in] val value to read from
  3355. */
  3356. template <typename BasicJsonType, typename ValueType>
  3357. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3358. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3359. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3360. {
  3361. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3362. }
  3363. };
  3364. } // namespace nlohmann
  3365. // #include <nlohmann/detail/conversions/from_json.hpp>
  3366. // #include <nlohmann/detail/conversions/to_json.hpp>
  3367. // #include <nlohmann/detail/exceptions.hpp>
  3368. // #include <nlohmann/detail/input/binary_reader.hpp>
  3369. #include <algorithm> // generate_n
  3370. #include <array> // array
  3371. #include <cassert> // assert
  3372. #include <cmath> // ldexp
  3373. #include <cstddef> // size_t
  3374. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3375. #include <cstdio> // snprintf
  3376. #include <cstring> // memcpy
  3377. #include <iterator> // back_inserter
  3378. #include <limits> // numeric_limits
  3379. #include <string> // char_traits, string
  3380. #include <utility> // make_pair, move
  3381. // #include <nlohmann/detail/exceptions.hpp>
  3382. // #include <nlohmann/detail/input/input_adapters.hpp>
  3383. #include <array> // array
  3384. #include <cassert> // assert
  3385. #include <cstddef> // size_t
  3386. #include <cstdio> //FILE *
  3387. #include <cstring> // strlen
  3388. #include <istream> // istream
  3389. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3390. #include <memory> // shared_ptr, make_shared, addressof
  3391. #include <numeric> // accumulate
  3392. #include <string> // string, char_traits
  3393. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3394. #include <utility> // pair, declval
  3395. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3396. // #include <nlohmann/detail/macro_scope.hpp>
  3397. namespace nlohmann
  3398. {
  3399. namespace detail
  3400. {
  3401. /// the supported input formats
  3402. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3403. ////////////////////
  3404. // input adapters //
  3405. ////////////////////
  3406. /*!
  3407. @brief abstract input adapter interface
  3408. Produces a stream of std::char_traits<char>::int_type characters from a
  3409. std::istream, a buffer, or some other input type. Accepts the return of
  3410. exactly one non-EOF character for future input. The int_type characters
  3411. returned consist of all valid char values as positive values (typically
  3412. unsigned char), plus an EOF value outside that range, specified by the value
  3413. of the function std::char_traits<char>::eof(). This value is typically -1, but
  3414. could be any arbitrary value which is not a valid char value.
  3415. */
  3416. struct input_adapter_protocol
  3417. {
  3418. /// get a character [0,255] or std::char_traits<char>::eof().
  3419. virtual std::char_traits<char>::int_type get_character() = 0;
  3420. virtual ~input_adapter_protocol() = default;
  3421. };
  3422. /// a type to simplify interfaces
  3423. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  3424. /*!
  3425. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3426. buffer. This adapter is a very low level adapter.
  3427. */
  3428. class file_input_adapter : public input_adapter_protocol
  3429. {
  3430. public:
  3431. JSON_HEDLEY_NON_NULL(2)
  3432. explicit file_input_adapter(std::FILE* f) noexcept
  3433. : m_file(f)
  3434. {}
  3435. // make class move-only
  3436. file_input_adapter(const file_input_adapter&) = delete;
  3437. file_input_adapter(file_input_adapter&&) = default;
  3438. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3439. file_input_adapter& operator=(file_input_adapter&&) = default;
  3440. ~file_input_adapter() override = default;
  3441. std::char_traits<char>::int_type get_character() noexcept override
  3442. {
  3443. return std::fgetc(m_file);
  3444. }
  3445. private:
  3446. /// the file pointer to read from
  3447. std::FILE* m_file;
  3448. };
  3449. /*!
  3450. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3451. beginning of input. Does not support changing the underlying std::streambuf
  3452. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3453. subsequent use of standard std::istream operations to process any input
  3454. characters following those used in parsing the JSON input. Clears the
  3455. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3456. subsequent call for input from the std::istream.
  3457. */
  3458. class input_stream_adapter : public input_adapter_protocol
  3459. {
  3460. public:
  3461. ~input_stream_adapter() override
  3462. {
  3463. // clear stream flags; we use underlying streambuf I/O, do not
  3464. // maintain ifstream flags, except eof
  3465. is.clear(is.rdstate() & std::ios::eofbit);
  3466. }
  3467. explicit input_stream_adapter(std::istream& i)
  3468. : is(i), sb(*i.rdbuf())
  3469. {}
  3470. // delete because of pointer members
  3471. input_stream_adapter(const input_stream_adapter&) = delete;
  3472. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3473. input_stream_adapter(input_stream_adapter&&) = delete;
  3474. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  3475. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3476. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3477. // end up as the same value, eg. 0xFFFFFFFF.
  3478. std::char_traits<char>::int_type get_character() override
  3479. {
  3480. auto res = sb.sbumpc();
  3481. // set eof manually, as we don't use the istream interface.
  3482. if (res == EOF)
  3483. {
  3484. is.clear(is.rdstate() | std::ios::eofbit);
  3485. }
  3486. return res;
  3487. }
  3488. private:
  3489. /// the associated input stream
  3490. std::istream& is;
  3491. std::streambuf& sb;
  3492. };
  3493. /// input adapter for buffer input
  3494. class input_buffer_adapter : public input_adapter_protocol
  3495. {
  3496. public:
  3497. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  3498. : cursor(b), limit(b == nullptr ? nullptr : (b + l))
  3499. {}
  3500. // delete because of pointer members
  3501. input_buffer_adapter(const input_buffer_adapter&) = delete;
  3502. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  3503. input_buffer_adapter(input_buffer_adapter&&) = delete;
  3504. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  3505. ~input_buffer_adapter() override = default;
  3506. std::char_traits<char>::int_type get_character() noexcept override
  3507. {
  3508. if (JSON_HEDLEY_LIKELY(cursor < limit))
  3509. {
  3510. assert(cursor != nullptr and limit != nullptr);
  3511. return std::char_traits<char>::to_int_type(*(cursor++));
  3512. }
  3513. return std::char_traits<char>::eof();
  3514. }
  3515. private:
  3516. /// pointer to the current character
  3517. const char* cursor;
  3518. /// pointer past the last character
  3519. const char* const limit;
  3520. };
  3521. template<typename WideStringType, size_t T>
  3522. struct wide_string_input_helper
  3523. {
  3524. // UTF-32
  3525. static void fill_buffer(const WideStringType& str,
  3526. size_t& current_wchar,
  3527. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3528. size_t& utf8_bytes_index,
  3529. size_t& utf8_bytes_filled)
  3530. {
  3531. utf8_bytes_index = 0;
  3532. if (current_wchar == str.size())
  3533. {
  3534. utf8_bytes[0] = std::char_traits<char>::eof();
  3535. utf8_bytes_filled = 1;
  3536. }
  3537. else
  3538. {
  3539. // get the current character
  3540. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3541. // UTF-32 to UTF-8 encoding
  3542. if (wc < 0x80)
  3543. {
  3544. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3545. utf8_bytes_filled = 1;
  3546. }
  3547. else if (wc <= 0x7FF)
  3548. {
  3549. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  3550. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3551. utf8_bytes_filled = 2;
  3552. }
  3553. else if (wc <= 0xFFFF)
  3554. {
  3555. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  3556. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3557. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3558. utf8_bytes_filled = 3;
  3559. }
  3560. else if (wc <= 0x10FFFF)
  3561. {
  3562. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  3563. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  3564. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3565. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3566. utf8_bytes_filled = 4;
  3567. }
  3568. else
  3569. {
  3570. // unknown character
  3571. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3572. utf8_bytes_filled = 1;
  3573. }
  3574. }
  3575. }
  3576. };
  3577. template<typename WideStringType>
  3578. struct wide_string_input_helper<WideStringType, 2>
  3579. {
  3580. // UTF-16
  3581. static void fill_buffer(const WideStringType& str,
  3582. size_t& current_wchar,
  3583. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  3584. size_t& utf8_bytes_index,
  3585. size_t& utf8_bytes_filled)
  3586. {
  3587. utf8_bytes_index = 0;
  3588. if (current_wchar == str.size())
  3589. {
  3590. utf8_bytes[0] = std::char_traits<char>::eof();
  3591. utf8_bytes_filled = 1;
  3592. }
  3593. else
  3594. {
  3595. // get the current character
  3596. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  3597. // UTF-16 to UTF-8 encoding
  3598. if (wc < 0x80)
  3599. {
  3600. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3601. utf8_bytes_filled = 1;
  3602. }
  3603. else if (wc <= 0x7FF)
  3604. {
  3605. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  3606. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3607. utf8_bytes_filled = 2;
  3608. }
  3609. else if (0xD800 > wc or wc >= 0xE000)
  3610. {
  3611. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  3612. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  3613. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  3614. utf8_bytes_filled = 3;
  3615. }
  3616. else
  3617. {
  3618. if (current_wchar < str.size())
  3619. {
  3620. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  3621. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  3622. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  3623. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  3624. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  3625. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  3626. utf8_bytes_filled = 4;
  3627. }
  3628. else
  3629. {
  3630. // unknown character
  3631. ++current_wchar;
  3632. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  3633. utf8_bytes_filled = 1;
  3634. }
  3635. }
  3636. }
  3637. }
  3638. };
  3639. template<typename WideStringType>
  3640. class wide_string_input_adapter : public input_adapter_protocol
  3641. {
  3642. public:
  3643. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  3644. : str(w)
  3645. {}
  3646. std::char_traits<char>::int_type get_character() noexcept override
  3647. {
  3648. // check if buffer needs to be filled
  3649. if (utf8_bytes_index == utf8_bytes_filled)
  3650. {
  3651. fill_buffer<sizeof(typename WideStringType::value_type)>();
  3652. assert(utf8_bytes_filled > 0);
  3653. assert(utf8_bytes_index == 0);
  3654. }
  3655. // use buffer
  3656. assert(utf8_bytes_filled > 0);
  3657. assert(utf8_bytes_index < utf8_bytes_filled);
  3658. return utf8_bytes[utf8_bytes_index++];
  3659. }
  3660. private:
  3661. template<size_t T>
  3662. void fill_buffer()
  3663. {
  3664. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  3665. }
  3666. /// the wstring to process
  3667. const WideStringType& str;
  3668. /// index of the current wchar in str
  3669. std::size_t current_wchar = 0;
  3670. /// a buffer for UTF-8 bytes
  3671. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  3672. /// index to the utf8_codes array for the next valid byte
  3673. std::size_t utf8_bytes_index = 0;
  3674. /// number of valid bytes in the utf8_codes array
  3675. std::size_t utf8_bytes_filled = 0;
  3676. };
  3677. class input_adapter
  3678. {
  3679. public:
  3680. // native support
  3681. JSON_HEDLEY_NON_NULL(2)
  3682. input_adapter(std::FILE* file)
  3683. : ia(std::make_shared<file_input_adapter>(file)) {}
  3684. /// input adapter for input stream
  3685. input_adapter(std::istream& i)
  3686. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3687. /// input adapter for input stream
  3688. input_adapter(std::istream&& i)
  3689. : ia(std::make_shared<input_stream_adapter>(i)) {}
  3690. input_adapter(const std::wstring& ws)
  3691. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  3692. input_adapter(const std::u16string& ws)
  3693. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  3694. input_adapter(const std::u32string& ws)
  3695. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  3696. /// input adapter for buffer
  3697. template<typename CharT,
  3698. typename std::enable_if<
  3699. std::is_pointer<CharT>::value and
  3700. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3701. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3702. int>::type = 0>
  3703. input_adapter(CharT b, std::size_t l)
  3704. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  3705. // derived support
  3706. /// input adapter for string literal
  3707. template<typename CharT,
  3708. typename std::enable_if<
  3709. std::is_pointer<CharT>::value and
  3710. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  3711. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  3712. int>::type = 0>
  3713. input_adapter(CharT b)
  3714. : input_adapter(reinterpret_cast<const char*>(b),
  3715. std::strlen(reinterpret_cast<const char*>(b))) {}
  3716. /// input adapter for iterator range with contiguous storage
  3717. template<class IteratorType,
  3718. typename std::enable_if<
  3719. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  3720. int>::type = 0>
  3721. input_adapter(IteratorType first, IteratorType last)
  3722. {
  3723. #ifndef NDEBUG
  3724. // assertion to check that the iterator range is indeed contiguous,
  3725. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  3726. const auto is_contiguous = std::accumulate(
  3727. first, last, std::pair<bool, int>(true, 0),
  3728. [&first](std::pair<bool, int> res, decltype(*first) val)
  3729. {
  3730. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  3731. return res;
  3732. }).first;
  3733. assert(is_contiguous);
  3734. #endif
  3735. // assertion to check that each element is 1 byte long
  3736. static_assert(
  3737. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  3738. "each element in the iterator range must have the size of 1 byte");
  3739. const auto len = static_cast<size_t>(std::distance(first, last));
  3740. if (JSON_HEDLEY_LIKELY(len > 0))
  3741. {
  3742. // there is at least one element: use the address of first
  3743. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  3744. }
  3745. else
  3746. {
  3747. // the address of first cannot be used: use nullptr
  3748. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  3749. }
  3750. }
  3751. /// input adapter for array
  3752. template<class T, std::size_t N>
  3753. input_adapter(T (&array)[N])
  3754. : input_adapter(std::begin(array), std::end(array)) {}
  3755. /// input adapter for contiguous container
  3756. template<class ContiguousContainer, typename
  3757. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  3758. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  3759. int>::type = 0>
  3760. input_adapter(const ContiguousContainer& c)
  3761. : input_adapter(std::begin(c), std::end(c)) {}
  3762. operator input_adapter_t()
  3763. {
  3764. return ia;
  3765. }
  3766. private:
  3767. /// the actual adapter
  3768. input_adapter_t ia = nullptr;
  3769. };
  3770. } // namespace detail
  3771. } // namespace nlohmann
  3772. // #include <nlohmann/detail/input/json_sax.hpp>
  3773. #include <cassert> // assert
  3774. #include <cstddef>
  3775. #include <string> // string
  3776. #include <utility> // move
  3777. #include <vector> // vector
  3778. // #include <nlohmann/detail/exceptions.hpp>
  3779. // #include <nlohmann/detail/macro_scope.hpp>
  3780. namespace nlohmann
  3781. {
  3782. /*!
  3783. @brief SAX interface
  3784. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3785. Each function is called in different situations while the input is parsed. The
  3786. boolean return value informs the parser whether to continue processing the
  3787. input.
  3788. */
  3789. template<typename BasicJsonType>
  3790. struct json_sax
  3791. {
  3792. /// type for (signed) integers
  3793. using number_integer_t = typename BasicJsonType::number_integer_t;
  3794. /// type for unsigned integers
  3795. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3796. /// type for floating-point numbers
  3797. using number_float_t = typename BasicJsonType::number_float_t;
  3798. /// type for strings
  3799. using string_t = typename BasicJsonType::string_t;
  3800. /*!
  3801. @brief a null value was read
  3802. @return whether parsing should proceed
  3803. */
  3804. virtual bool null() = 0;
  3805. /*!
  3806. @brief a boolean value was read
  3807. @param[in] val boolean value
  3808. @return whether parsing should proceed
  3809. */
  3810. virtual bool boolean(bool val) = 0;
  3811. /*!
  3812. @brief an integer number was read
  3813. @param[in] val integer value
  3814. @return whether parsing should proceed
  3815. */
  3816. virtual bool number_integer(number_integer_t val) = 0;
  3817. /*!
  3818. @brief an unsigned integer number was read
  3819. @param[in] val unsigned integer value
  3820. @return whether parsing should proceed
  3821. */
  3822. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3823. /*!
  3824. @brief an floating-point number was read
  3825. @param[in] val floating-point value
  3826. @param[in] s raw token value
  3827. @return whether parsing should proceed
  3828. */
  3829. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3830. /*!
  3831. @brief a string was read
  3832. @param[in] val string value
  3833. @return whether parsing should proceed
  3834. @note It is safe to move the passed string.
  3835. */
  3836. virtual bool string(string_t& val) = 0;
  3837. /*!
  3838. @brief the beginning of an object was read
  3839. @param[in] elements number of object elements or -1 if unknown
  3840. @return whether parsing should proceed
  3841. @note binary formats may report the number of elements
  3842. */
  3843. virtual bool start_object(std::size_t elements) = 0;
  3844. /*!
  3845. @brief an object key was read
  3846. @param[in] val object key
  3847. @return whether parsing should proceed
  3848. @note It is safe to move the passed string.
  3849. */
  3850. virtual bool key(string_t& val) = 0;
  3851. /*!
  3852. @brief the end of an object was read
  3853. @return whether parsing should proceed
  3854. */
  3855. virtual bool end_object() = 0;
  3856. /*!
  3857. @brief the beginning of an array was read
  3858. @param[in] elements number of array elements or -1 if unknown
  3859. @return whether parsing should proceed
  3860. @note binary formats may report the number of elements
  3861. */
  3862. virtual bool start_array(std::size_t elements) = 0;
  3863. /*!
  3864. @brief the end of an array was read
  3865. @return whether parsing should proceed
  3866. */
  3867. virtual bool end_array() = 0;
  3868. /*!
  3869. @brief a parse error occurred
  3870. @param[in] position the position in the input where the error occurs
  3871. @param[in] last_token the last read token
  3872. @param[in] ex an exception object describing the error
  3873. @return whether parsing should proceed (must return false)
  3874. */
  3875. virtual bool parse_error(std::size_t position,
  3876. const std::string& last_token,
  3877. const detail::exception& ex) = 0;
  3878. virtual ~json_sax() = default;
  3879. };
  3880. namespace detail
  3881. {
  3882. /*!
  3883. @brief SAX implementation to create a JSON value from SAX events
  3884. This class implements the @ref json_sax interface and processes the SAX events
  3885. to create a JSON value which makes it basically a DOM parser. The structure or
  3886. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3887. a pointer to the respective array or object for each recursion depth.
  3888. After successful parsing, the value that is passed by reference to the
  3889. constructor contains the parsed value.
  3890. @tparam BasicJsonType the JSON type
  3891. */
  3892. template<typename BasicJsonType>
  3893. class json_sax_dom_parser
  3894. {
  3895. public:
  3896. using number_integer_t = typename BasicJsonType::number_integer_t;
  3897. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3898. using number_float_t = typename BasicJsonType::number_float_t;
  3899. using string_t = typename BasicJsonType::string_t;
  3900. /*!
  3901. @param[in, out] r reference to a JSON value that is manipulated while
  3902. parsing
  3903. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3904. */
  3905. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3906. : root(r), allow_exceptions(allow_exceptions_)
  3907. {}
  3908. // make class move-only
  3909. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  3910. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  3911. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  3912. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  3913. ~json_sax_dom_parser() = default;
  3914. bool null()
  3915. {
  3916. handle_value(nullptr);
  3917. return true;
  3918. }
  3919. bool boolean(bool val)
  3920. {
  3921. handle_value(val);
  3922. return true;
  3923. }
  3924. bool number_integer(number_integer_t val)
  3925. {
  3926. handle_value(val);
  3927. return true;
  3928. }
  3929. bool number_unsigned(number_unsigned_t val)
  3930. {
  3931. handle_value(val);
  3932. return true;
  3933. }
  3934. bool number_float(number_float_t val, const string_t& /*unused*/)
  3935. {
  3936. handle_value(val);
  3937. return true;
  3938. }
  3939. bool string(string_t& val)
  3940. {
  3941. handle_value(val);
  3942. return true;
  3943. }
  3944. bool start_object(std::size_t len)
  3945. {
  3946. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3947. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3948. {
  3949. JSON_THROW(out_of_range::create(408,
  3950. "excessive object size: " + std::to_string(len)));
  3951. }
  3952. return true;
  3953. }
  3954. bool key(string_t& val)
  3955. {
  3956. // add null at given key and store the reference for later
  3957. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3958. return true;
  3959. }
  3960. bool end_object()
  3961. {
  3962. ref_stack.pop_back();
  3963. return true;
  3964. }
  3965. bool start_array(std::size_t len)
  3966. {
  3967. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3968. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3969. {
  3970. JSON_THROW(out_of_range::create(408,
  3971. "excessive array size: " + std::to_string(len)));
  3972. }
  3973. return true;
  3974. }
  3975. bool end_array()
  3976. {
  3977. ref_stack.pop_back();
  3978. return true;
  3979. }
  3980. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  3981. const detail::exception& ex)
  3982. {
  3983. errored = true;
  3984. if (allow_exceptions)
  3985. {
  3986. // determine the proper exception type from the id
  3987. switch ((ex.id / 100) % 100)
  3988. {
  3989. case 1:
  3990. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  3991. case 4:
  3992. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  3993. // LCOV_EXCL_START
  3994. case 2:
  3995. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  3996. case 3:
  3997. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  3998. case 5:
  3999. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4000. default:
  4001. assert(false);
  4002. // LCOV_EXCL_STOP
  4003. }
  4004. }
  4005. return false;
  4006. }
  4007. constexpr bool is_errored() const
  4008. {
  4009. return errored;
  4010. }
  4011. private:
  4012. /*!
  4013. @invariant If the ref stack is empty, then the passed value will be the new
  4014. root.
  4015. @invariant If the ref stack contains a value, then it is an array or an
  4016. object to which we can add elements
  4017. */
  4018. template<typename Value>
  4019. JSON_HEDLEY_RETURNS_NON_NULL
  4020. BasicJsonType* handle_value(Value&& v)
  4021. {
  4022. if (ref_stack.empty())
  4023. {
  4024. root = BasicJsonType(std::forward<Value>(v));
  4025. return &root;
  4026. }
  4027. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4028. if (ref_stack.back()->is_array())
  4029. {
  4030. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4031. return &(ref_stack.back()->m_value.array->back());
  4032. }
  4033. assert(ref_stack.back()->is_object());
  4034. assert(object_element);
  4035. *object_element = BasicJsonType(std::forward<Value>(v));
  4036. return object_element;
  4037. }
  4038. /// the parsed JSON value
  4039. BasicJsonType& root;
  4040. /// stack to model hierarchy of values
  4041. std::vector<BasicJsonType*> ref_stack {};
  4042. /// helper to hold the reference for the next object element
  4043. BasicJsonType* object_element = nullptr;
  4044. /// whether a syntax error occurred
  4045. bool errored = false;
  4046. /// whether to throw exceptions in case of errors
  4047. const bool allow_exceptions = true;
  4048. };
  4049. template<typename BasicJsonType>
  4050. class json_sax_dom_callback_parser
  4051. {
  4052. public:
  4053. using number_integer_t = typename BasicJsonType::number_integer_t;
  4054. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4055. using number_float_t = typename BasicJsonType::number_float_t;
  4056. using string_t = typename BasicJsonType::string_t;
  4057. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4058. using parse_event_t = typename BasicJsonType::parse_event_t;
  4059. json_sax_dom_callback_parser(BasicJsonType& r,
  4060. const parser_callback_t cb,
  4061. const bool allow_exceptions_ = true)
  4062. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4063. {
  4064. keep_stack.push_back(true);
  4065. }
  4066. // make class move-only
  4067. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4068. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4069. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4070. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4071. ~json_sax_dom_callback_parser() = default;
  4072. bool null()
  4073. {
  4074. handle_value(nullptr);
  4075. return true;
  4076. }
  4077. bool boolean(bool val)
  4078. {
  4079. handle_value(val);
  4080. return true;
  4081. }
  4082. bool number_integer(number_integer_t val)
  4083. {
  4084. handle_value(val);
  4085. return true;
  4086. }
  4087. bool number_unsigned(number_unsigned_t val)
  4088. {
  4089. handle_value(val);
  4090. return true;
  4091. }
  4092. bool number_float(number_float_t val, const string_t& /*unused*/)
  4093. {
  4094. handle_value(val);
  4095. return true;
  4096. }
  4097. bool string(string_t& val)
  4098. {
  4099. handle_value(val);
  4100. return true;
  4101. }
  4102. bool start_object(std::size_t len)
  4103. {
  4104. // check callback for object start
  4105. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4106. keep_stack.push_back(keep);
  4107. auto val = handle_value(BasicJsonType::value_t::object, true);
  4108. ref_stack.push_back(val.second);
  4109. // check object limit
  4110. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4111. {
  4112. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4113. }
  4114. return true;
  4115. }
  4116. bool key(string_t& val)
  4117. {
  4118. BasicJsonType k = BasicJsonType(val);
  4119. // check callback for key
  4120. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4121. key_keep_stack.push_back(keep);
  4122. // add discarded value at given key and store the reference for later
  4123. if (keep and ref_stack.back())
  4124. {
  4125. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4126. }
  4127. return true;
  4128. }
  4129. bool end_object()
  4130. {
  4131. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4132. {
  4133. // discard object
  4134. *ref_stack.back() = discarded;
  4135. }
  4136. assert(not ref_stack.empty());
  4137. assert(not keep_stack.empty());
  4138. ref_stack.pop_back();
  4139. keep_stack.pop_back();
  4140. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  4141. {
  4142. // remove discarded value
  4143. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4144. {
  4145. if (it->is_discarded())
  4146. {
  4147. ref_stack.back()->erase(it);
  4148. break;
  4149. }
  4150. }
  4151. }
  4152. return true;
  4153. }
  4154. bool start_array(std::size_t len)
  4155. {
  4156. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4157. keep_stack.push_back(keep);
  4158. auto val = handle_value(BasicJsonType::value_t::array, true);
  4159. ref_stack.push_back(val.second);
  4160. // check array limit
  4161. if (ref_stack.back() and JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  4162. {
  4163. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4164. }
  4165. return true;
  4166. }
  4167. bool end_array()
  4168. {
  4169. bool keep = true;
  4170. if (ref_stack.back())
  4171. {
  4172. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4173. if (not keep)
  4174. {
  4175. // discard array
  4176. *ref_stack.back() = discarded;
  4177. }
  4178. }
  4179. assert(not ref_stack.empty());
  4180. assert(not keep_stack.empty());
  4181. ref_stack.pop_back();
  4182. keep_stack.pop_back();
  4183. // remove discarded value
  4184. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  4185. {
  4186. ref_stack.back()->m_value.array->pop_back();
  4187. }
  4188. return true;
  4189. }
  4190. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4191. const detail::exception& ex)
  4192. {
  4193. errored = true;
  4194. if (allow_exceptions)
  4195. {
  4196. // determine the proper exception type from the id
  4197. switch ((ex.id / 100) % 100)
  4198. {
  4199. case 1:
  4200. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  4201. case 4:
  4202. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  4203. // LCOV_EXCL_START
  4204. case 2:
  4205. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  4206. case 3:
  4207. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  4208. case 5:
  4209. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  4210. default:
  4211. assert(false);
  4212. // LCOV_EXCL_STOP
  4213. }
  4214. }
  4215. return false;
  4216. }
  4217. constexpr bool is_errored() const
  4218. {
  4219. return errored;
  4220. }
  4221. private:
  4222. /*!
  4223. @param[in] v value to add to the JSON value we build during parsing
  4224. @param[in] skip_callback whether we should skip calling the callback
  4225. function; this is required after start_array() and
  4226. start_object() SAX events, because otherwise we would call the
  4227. callback function with an empty array or object, respectively.
  4228. @invariant If the ref stack is empty, then the passed value will be the new
  4229. root.
  4230. @invariant If the ref stack contains a value, then it is an array or an
  4231. object to which we can add elements
  4232. @return pair of boolean (whether value should be kept) and pointer (to the
  4233. passed value in the ref_stack hierarchy; nullptr if not kept)
  4234. */
  4235. template<typename Value>
  4236. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4237. {
  4238. assert(not keep_stack.empty());
  4239. // do not handle this value if we know it would be added to a discarded
  4240. // container
  4241. if (not keep_stack.back())
  4242. {
  4243. return {false, nullptr};
  4244. }
  4245. // create value
  4246. auto value = BasicJsonType(std::forward<Value>(v));
  4247. // check callback
  4248. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4249. // do not handle this value if we just learnt it shall be discarded
  4250. if (not keep)
  4251. {
  4252. return {false, nullptr};
  4253. }
  4254. if (ref_stack.empty())
  4255. {
  4256. root = std::move(value);
  4257. return {true, &root};
  4258. }
  4259. // skip this value if we already decided to skip the parent
  4260. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4261. if (not ref_stack.back())
  4262. {
  4263. return {false, nullptr};
  4264. }
  4265. // we now only expect arrays and objects
  4266. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  4267. // array
  4268. if (ref_stack.back()->is_array())
  4269. {
  4270. ref_stack.back()->m_value.array->push_back(std::move(value));
  4271. return {true, &(ref_stack.back()->m_value.array->back())};
  4272. }
  4273. // object
  4274. assert(ref_stack.back()->is_object());
  4275. // check if we should store an element for the current key
  4276. assert(not key_keep_stack.empty());
  4277. const bool store_element = key_keep_stack.back();
  4278. key_keep_stack.pop_back();
  4279. if (not store_element)
  4280. {
  4281. return {false, nullptr};
  4282. }
  4283. assert(object_element);
  4284. *object_element = std::move(value);
  4285. return {true, object_element};
  4286. }
  4287. /// the parsed JSON value
  4288. BasicJsonType& root;
  4289. /// stack to model hierarchy of values
  4290. std::vector<BasicJsonType*> ref_stack {};
  4291. /// stack to manage which values to keep
  4292. std::vector<bool> keep_stack {};
  4293. /// stack to manage which object keys to keep
  4294. std::vector<bool> key_keep_stack {};
  4295. /// helper to hold the reference for the next object element
  4296. BasicJsonType* object_element = nullptr;
  4297. /// whether a syntax error occurred
  4298. bool errored = false;
  4299. /// callback function
  4300. const parser_callback_t callback = nullptr;
  4301. /// whether to throw exceptions in case of errors
  4302. const bool allow_exceptions = true;
  4303. /// a discarded value for the callback
  4304. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4305. };
  4306. template<typename BasicJsonType>
  4307. class json_sax_acceptor
  4308. {
  4309. public:
  4310. using number_integer_t = typename BasicJsonType::number_integer_t;
  4311. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4312. using number_float_t = typename BasicJsonType::number_float_t;
  4313. using string_t = typename BasicJsonType::string_t;
  4314. bool null()
  4315. {
  4316. return true;
  4317. }
  4318. bool boolean(bool /*unused*/)
  4319. {
  4320. return true;
  4321. }
  4322. bool number_integer(number_integer_t /*unused*/)
  4323. {
  4324. return true;
  4325. }
  4326. bool number_unsigned(number_unsigned_t /*unused*/)
  4327. {
  4328. return true;
  4329. }
  4330. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4331. {
  4332. return true;
  4333. }
  4334. bool string(string_t& /*unused*/)
  4335. {
  4336. return true;
  4337. }
  4338. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4339. {
  4340. return true;
  4341. }
  4342. bool key(string_t& /*unused*/)
  4343. {
  4344. return true;
  4345. }
  4346. bool end_object()
  4347. {
  4348. return true;
  4349. }
  4350. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4351. {
  4352. return true;
  4353. }
  4354. bool end_array()
  4355. {
  4356. return true;
  4357. }
  4358. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4359. {
  4360. return false;
  4361. }
  4362. };
  4363. } // namespace detail
  4364. } // namespace nlohmann
  4365. // #include <nlohmann/detail/macro_scope.hpp>
  4366. // #include <nlohmann/detail/meta/is_sax.hpp>
  4367. #include <cstdint> // size_t
  4368. #include <utility> // declval
  4369. #include <string> // string
  4370. // #include <nlohmann/detail/meta/detected.hpp>
  4371. // #include <nlohmann/detail/meta/type_traits.hpp>
  4372. namespace nlohmann
  4373. {
  4374. namespace detail
  4375. {
  4376. template <typename T>
  4377. using null_function_t = decltype(std::declval<T&>().null());
  4378. template <typename T>
  4379. using boolean_function_t =
  4380. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4381. template <typename T, typename Integer>
  4382. using number_integer_function_t =
  4383. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4384. template <typename T, typename Unsigned>
  4385. using number_unsigned_function_t =
  4386. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4387. template <typename T, typename Float, typename String>
  4388. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4389. std::declval<Float>(), std::declval<const String&>()));
  4390. template <typename T, typename String>
  4391. using string_function_t =
  4392. decltype(std::declval<T&>().string(std::declval<String&>()));
  4393. template <typename T>
  4394. using start_object_function_t =
  4395. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4396. template <typename T, typename String>
  4397. using key_function_t =
  4398. decltype(std::declval<T&>().key(std::declval<String&>()));
  4399. template <typename T>
  4400. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4401. template <typename T>
  4402. using start_array_function_t =
  4403. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4404. template <typename T>
  4405. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4406. template <typename T, typename Exception>
  4407. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4408. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4409. std::declval<const Exception&>()));
  4410. template <typename SAX, typename BasicJsonType>
  4411. struct is_sax
  4412. {
  4413. private:
  4414. static_assert(is_basic_json<BasicJsonType>::value,
  4415. "BasicJsonType must be of type basic_json<...>");
  4416. using number_integer_t = typename BasicJsonType::number_integer_t;
  4417. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4418. using number_float_t = typename BasicJsonType::number_float_t;
  4419. using string_t = typename BasicJsonType::string_t;
  4420. using exception_t = typename BasicJsonType::exception;
  4421. public:
  4422. static constexpr bool value =
  4423. is_detected_exact<bool, null_function_t, SAX>::value &&
  4424. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4425. is_detected_exact<bool, number_integer_function_t, SAX,
  4426. number_integer_t>::value &&
  4427. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4428. number_unsigned_t>::value &&
  4429. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4430. string_t>::value &&
  4431. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4432. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4433. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4434. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4435. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4436. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4437. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4438. };
  4439. template <typename SAX, typename BasicJsonType>
  4440. struct is_sax_static_asserts
  4441. {
  4442. private:
  4443. static_assert(is_basic_json<BasicJsonType>::value,
  4444. "BasicJsonType must be of type basic_json<...>");
  4445. using number_integer_t = typename BasicJsonType::number_integer_t;
  4446. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4447. using number_float_t = typename BasicJsonType::number_float_t;
  4448. using string_t = typename BasicJsonType::string_t;
  4449. using exception_t = typename BasicJsonType::exception;
  4450. public:
  4451. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  4452. "Missing/invalid function: bool null()");
  4453. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4454. "Missing/invalid function: bool boolean(bool)");
  4455. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  4456. "Missing/invalid function: bool boolean(bool)");
  4457. static_assert(
  4458. is_detected_exact<bool, number_integer_function_t, SAX,
  4459. number_integer_t>::value,
  4460. "Missing/invalid function: bool number_integer(number_integer_t)");
  4461. static_assert(
  4462. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4463. number_unsigned_t>::value,
  4464. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  4465. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  4466. number_float_t, string_t>::value,
  4467. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  4468. static_assert(
  4469. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  4470. "Missing/invalid function: bool string(string_t&)");
  4471. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  4472. "Missing/invalid function: bool start_object(std::size_t)");
  4473. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  4474. "Missing/invalid function: bool key(string_t&)");
  4475. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  4476. "Missing/invalid function: bool end_object()");
  4477. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  4478. "Missing/invalid function: bool start_array(std::size_t)");
  4479. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  4480. "Missing/invalid function: bool end_array()");
  4481. static_assert(
  4482. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  4483. "Missing/invalid function: bool parse_error(std::size_t, const "
  4484. "std::string&, const exception&)");
  4485. };
  4486. } // namespace detail
  4487. } // namespace nlohmann
  4488. // #include <nlohmann/detail/value_t.hpp>
  4489. namespace nlohmann
  4490. {
  4491. namespace detail
  4492. {
  4493. ///////////////////
  4494. // binary reader //
  4495. ///////////////////
  4496. /*!
  4497. @brief deserialization of CBOR, MessagePack, and UBJSON values
  4498. */
  4499. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  4500. class binary_reader
  4501. {
  4502. using number_integer_t = typename BasicJsonType::number_integer_t;
  4503. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4504. using number_float_t = typename BasicJsonType::number_float_t;
  4505. using string_t = typename BasicJsonType::string_t;
  4506. using json_sax_t = SAX;
  4507. public:
  4508. /*!
  4509. @brief create a binary reader
  4510. @param[in] adapter input adapter to read from
  4511. */
  4512. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  4513. {
  4514. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  4515. assert(ia);
  4516. }
  4517. // make class move-only
  4518. binary_reader(const binary_reader&) = delete;
  4519. binary_reader(binary_reader&&) = default;
  4520. binary_reader& operator=(const binary_reader&) = delete;
  4521. binary_reader& operator=(binary_reader&&) = default;
  4522. ~binary_reader() = default;
  4523. /*!
  4524. @param[in] format the binary format to parse
  4525. @param[in] sax_ a SAX event processor
  4526. @param[in] strict whether to expect the input to be consumed completed
  4527. @return
  4528. */
  4529. JSON_HEDLEY_NON_NULL(3)
  4530. bool sax_parse(const input_format_t format,
  4531. json_sax_t* sax_,
  4532. const bool strict = true)
  4533. {
  4534. sax = sax_;
  4535. bool result = false;
  4536. switch (format)
  4537. {
  4538. case input_format_t::bson:
  4539. result = parse_bson_internal();
  4540. break;
  4541. case input_format_t::cbor:
  4542. result = parse_cbor_internal();
  4543. break;
  4544. case input_format_t::msgpack:
  4545. result = parse_msgpack_internal();
  4546. break;
  4547. case input_format_t::ubjson:
  4548. result = parse_ubjson_internal();
  4549. break;
  4550. default: // LCOV_EXCL_LINE
  4551. assert(false); // LCOV_EXCL_LINE
  4552. }
  4553. // strict mode: next byte must be EOF
  4554. if (result and strict)
  4555. {
  4556. if (format == input_format_t::ubjson)
  4557. {
  4558. get_ignore_noop();
  4559. }
  4560. else
  4561. {
  4562. get();
  4563. }
  4564. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char>::eof()))
  4565. {
  4566. return sax->parse_error(chars_read, get_token_string(),
  4567. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  4568. }
  4569. }
  4570. return result;
  4571. }
  4572. /*!
  4573. @brief determine system byte order
  4574. @return true if and only if system's byte order is little endian
  4575. @note from http://stackoverflow.com/a/1001328/266378
  4576. */
  4577. static constexpr bool little_endianess(int num = 1) noexcept
  4578. {
  4579. return *reinterpret_cast<char*>(&num) == 1;
  4580. }
  4581. private:
  4582. //////////
  4583. // BSON //
  4584. //////////
  4585. /*!
  4586. @brief Reads in a BSON-object and passes it to the SAX-parser.
  4587. @return whether a valid BSON-value was passed to the SAX parser
  4588. */
  4589. bool parse_bson_internal()
  4590. {
  4591. std::int32_t document_size;
  4592. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4593. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4594. {
  4595. return false;
  4596. }
  4597. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  4598. {
  4599. return false;
  4600. }
  4601. return sax->end_object();
  4602. }
  4603. /*!
  4604. @brief Parses a C-style string from the BSON input.
  4605. @param[in, out] result A reference to the string variable where the read
  4606. string is to be stored.
  4607. @return `true` if the \x00-byte indicating the end of the string was
  4608. encountered before the EOF; false` indicates an unexpected EOF.
  4609. */
  4610. bool get_bson_cstr(string_t& result)
  4611. {
  4612. auto out = std::back_inserter(result);
  4613. while (true)
  4614. {
  4615. get();
  4616. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  4617. {
  4618. return false;
  4619. }
  4620. if (current == 0x00)
  4621. {
  4622. return true;
  4623. }
  4624. *out++ = static_cast<char>(current);
  4625. }
  4626. return true;
  4627. }
  4628. /*!
  4629. @brief Parses a zero-terminated string of length @a len from the BSON
  4630. input.
  4631. @param[in] len The length (including the zero-byte at the end) of the
  4632. string to be read.
  4633. @param[in, out] result A reference to the string variable where the read
  4634. string is to be stored.
  4635. @tparam NumberType The type of the length @a len
  4636. @pre len >= 1
  4637. @return `true` if the string was successfully parsed
  4638. */
  4639. template<typename NumberType>
  4640. bool get_bson_string(const NumberType len, string_t& result)
  4641. {
  4642. if (JSON_HEDLEY_UNLIKELY(len < 1))
  4643. {
  4644. auto last_token = get_token_string();
  4645. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string")));
  4646. }
  4647. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  4648. }
  4649. /*!
  4650. @brief Read a BSON document element of the given @a element_type.
  4651. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  4652. @param[in] element_type_parse_position The position in the input stream,
  4653. where the `element_type` was read.
  4654. @warning Not all BSON element types are supported yet. An unsupported
  4655. @a element_type will give rise to a parse_error.114:
  4656. Unsupported BSON record type 0x...
  4657. @return whether a valid BSON-object/array was passed to the SAX parser
  4658. */
  4659. bool parse_bson_element_internal(const int element_type,
  4660. const std::size_t element_type_parse_position)
  4661. {
  4662. switch (element_type)
  4663. {
  4664. case 0x01: // double
  4665. {
  4666. double number;
  4667. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4668. }
  4669. case 0x02: // string
  4670. {
  4671. std::int32_t len;
  4672. string_t value;
  4673. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  4674. }
  4675. case 0x03: // object
  4676. {
  4677. return parse_bson_internal();
  4678. }
  4679. case 0x04: // array
  4680. {
  4681. return parse_bson_array();
  4682. }
  4683. case 0x08: // boolean
  4684. {
  4685. return sax->boolean(get() != 0);
  4686. }
  4687. case 0x0A: // null
  4688. {
  4689. return sax->null();
  4690. }
  4691. case 0x10: // int32
  4692. {
  4693. std::int32_t value;
  4694. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4695. }
  4696. case 0x12: // int64
  4697. {
  4698. std::int64_t value;
  4699. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  4700. }
  4701. default: // anything else not supported (yet)
  4702. {
  4703. std::array<char, 3> cr{{}};
  4704. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  4705. return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data())));
  4706. }
  4707. }
  4708. }
  4709. /*!
  4710. @brief Read a BSON element list (as specified in the BSON-spec)
  4711. The same binary layout is used for objects and arrays, hence it must be
  4712. indicated with the argument @a is_array which one is expected
  4713. (true --> array, false --> object).
  4714. @param[in] is_array Determines if the element list being read is to be
  4715. treated as an object (@a is_array == false), or as an
  4716. array (@a is_array == true).
  4717. @return whether a valid BSON-object/array was passed to the SAX parser
  4718. */
  4719. bool parse_bson_element_list(const bool is_array)
  4720. {
  4721. string_t key;
  4722. while (int element_type = get())
  4723. {
  4724. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  4725. {
  4726. return false;
  4727. }
  4728. const std::size_t element_type_parse_position = chars_read;
  4729. if (JSON_HEDLEY_UNLIKELY(not get_bson_cstr(key)))
  4730. {
  4731. return false;
  4732. }
  4733. if (not is_array and not sax->key(key))
  4734. {
  4735. return false;
  4736. }
  4737. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  4738. {
  4739. return false;
  4740. }
  4741. // get_bson_cstr only appends
  4742. key.clear();
  4743. }
  4744. return true;
  4745. }
  4746. /*!
  4747. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  4748. @return whether a valid BSON-array was passed to the SAX parser
  4749. */
  4750. bool parse_bson_array()
  4751. {
  4752. std::int32_t document_size;
  4753. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  4754. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4755. {
  4756. return false;
  4757. }
  4758. if (JSON_HEDLEY_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  4759. {
  4760. return false;
  4761. }
  4762. return sax->end_array();
  4763. }
  4764. //////////
  4765. // CBOR //
  4766. //////////
  4767. /*!
  4768. @param[in] get_char whether a new character should be retrieved from the
  4769. input (true, default) or whether the last read
  4770. character should be considered instead
  4771. @return whether a valid CBOR value was passed to the SAX parser
  4772. */
  4773. bool parse_cbor_internal(const bool get_char = true)
  4774. {
  4775. switch (get_char ? get() : current)
  4776. {
  4777. // EOF
  4778. case std::char_traits<char>::eof():
  4779. return unexpect_eof(input_format_t::cbor, "value");
  4780. // Integer 0x00..0x17 (0..23)
  4781. case 0x00:
  4782. case 0x01:
  4783. case 0x02:
  4784. case 0x03:
  4785. case 0x04:
  4786. case 0x05:
  4787. case 0x06:
  4788. case 0x07:
  4789. case 0x08:
  4790. case 0x09:
  4791. case 0x0A:
  4792. case 0x0B:
  4793. case 0x0C:
  4794. case 0x0D:
  4795. case 0x0E:
  4796. case 0x0F:
  4797. case 0x10:
  4798. case 0x11:
  4799. case 0x12:
  4800. case 0x13:
  4801. case 0x14:
  4802. case 0x15:
  4803. case 0x16:
  4804. case 0x17:
  4805. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  4806. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  4807. {
  4808. std::uint8_t number;
  4809. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4810. }
  4811. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  4812. {
  4813. std::uint16_t number;
  4814. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4815. }
  4816. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  4817. {
  4818. std::uint32_t number;
  4819. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4820. }
  4821. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  4822. {
  4823. std::uint64_t number;
  4824. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  4825. }
  4826. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  4827. case 0x20:
  4828. case 0x21:
  4829. case 0x22:
  4830. case 0x23:
  4831. case 0x24:
  4832. case 0x25:
  4833. case 0x26:
  4834. case 0x27:
  4835. case 0x28:
  4836. case 0x29:
  4837. case 0x2A:
  4838. case 0x2B:
  4839. case 0x2C:
  4840. case 0x2D:
  4841. case 0x2E:
  4842. case 0x2F:
  4843. case 0x30:
  4844. case 0x31:
  4845. case 0x32:
  4846. case 0x33:
  4847. case 0x34:
  4848. case 0x35:
  4849. case 0x36:
  4850. case 0x37:
  4851. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  4852. case 0x38: // Negative integer (one-byte uint8_t follows)
  4853. {
  4854. std::uint8_t number;
  4855. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4856. }
  4857. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4858. {
  4859. std::uint16_t number;
  4860. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4861. }
  4862. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  4863. {
  4864. std::uint32_t number;
  4865. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  4866. }
  4867. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  4868. {
  4869. std::uint64_t number;
  4870. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  4871. - static_cast<number_integer_t>(number));
  4872. }
  4873. // UTF-8 string (0x00..0x17 bytes follow)
  4874. case 0x60:
  4875. case 0x61:
  4876. case 0x62:
  4877. case 0x63:
  4878. case 0x64:
  4879. case 0x65:
  4880. case 0x66:
  4881. case 0x67:
  4882. case 0x68:
  4883. case 0x69:
  4884. case 0x6A:
  4885. case 0x6B:
  4886. case 0x6C:
  4887. case 0x6D:
  4888. case 0x6E:
  4889. case 0x6F:
  4890. case 0x70:
  4891. case 0x71:
  4892. case 0x72:
  4893. case 0x73:
  4894. case 0x74:
  4895. case 0x75:
  4896. case 0x76:
  4897. case 0x77:
  4898. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4899. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4900. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  4901. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  4902. case 0x7F: // UTF-8 string (indefinite length)
  4903. {
  4904. string_t s;
  4905. return get_cbor_string(s) and sax->string(s);
  4906. }
  4907. // array (0x00..0x17 data items follow)
  4908. case 0x80:
  4909. case 0x81:
  4910. case 0x82:
  4911. case 0x83:
  4912. case 0x84:
  4913. case 0x85:
  4914. case 0x86:
  4915. case 0x87:
  4916. case 0x88:
  4917. case 0x89:
  4918. case 0x8A:
  4919. case 0x8B:
  4920. case 0x8C:
  4921. case 0x8D:
  4922. case 0x8E:
  4923. case 0x8F:
  4924. case 0x90:
  4925. case 0x91:
  4926. case 0x92:
  4927. case 0x93:
  4928. case 0x94:
  4929. case 0x95:
  4930. case 0x96:
  4931. case 0x97:
  4932. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4933. case 0x98: // array (one-byte uint8_t for n follows)
  4934. {
  4935. std::uint8_t len;
  4936. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4937. }
  4938. case 0x99: // array (two-byte uint16_t for n follow)
  4939. {
  4940. std::uint16_t len;
  4941. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4942. }
  4943. case 0x9A: // array (four-byte uint32_t for n follow)
  4944. {
  4945. std::uint32_t len;
  4946. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4947. }
  4948. case 0x9B: // array (eight-byte uint64_t for n follow)
  4949. {
  4950. std::uint64_t len;
  4951. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  4952. }
  4953. case 0x9F: // array (indefinite length)
  4954. return get_cbor_array(std::size_t(-1));
  4955. // map (0x00..0x17 pairs of data items follow)
  4956. case 0xA0:
  4957. case 0xA1:
  4958. case 0xA2:
  4959. case 0xA3:
  4960. case 0xA4:
  4961. case 0xA5:
  4962. case 0xA6:
  4963. case 0xA7:
  4964. case 0xA8:
  4965. case 0xA9:
  4966. case 0xAA:
  4967. case 0xAB:
  4968. case 0xAC:
  4969. case 0xAD:
  4970. case 0xAE:
  4971. case 0xAF:
  4972. case 0xB0:
  4973. case 0xB1:
  4974. case 0xB2:
  4975. case 0xB3:
  4976. case 0xB4:
  4977. case 0xB5:
  4978. case 0xB6:
  4979. case 0xB7:
  4980. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  4981. case 0xB8: // map (one-byte uint8_t for n follows)
  4982. {
  4983. std::uint8_t len;
  4984. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4985. }
  4986. case 0xB9: // map (two-byte uint16_t for n follow)
  4987. {
  4988. std::uint16_t len;
  4989. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4990. }
  4991. case 0xBA: // map (four-byte uint32_t for n follow)
  4992. {
  4993. std::uint32_t len;
  4994. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  4995. }
  4996. case 0xBB: // map (eight-byte uint64_t for n follow)
  4997. {
  4998. std::uint64_t len;
  4999. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  5000. }
  5001. case 0xBF: // map (indefinite length)
  5002. return get_cbor_object(std::size_t(-1));
  5003. case 0xF4: // false
  5004. return sax->boolean(false);
  5005. case 0xF5: // true
  5006. return sax->boolean(true);
  5007. case 0xF6: // null
  5008. return sax->null();
  5009. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5010. {
  5011. const int byte1_raw = get();
  5012. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5013. {
  5014. return false;
  5015. }
  5016. const int byte2_raw = get();
  5017. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  5018. {
  5019. return false;
  5020. }
  5021. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5022. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5023. // code from RFC 7049, Appendix D, Figure 3:
  5024. // As half-precision floating-point numbers were only added
  5025. // to IEEE 754 in 2008, today's programming platforms often
  5026. // still only have limited support for them. It is very
  5027. // easy to include at least decoding support for them even
  5028. // without such support. An example of a small decoder for
  5029. // half-precision floating-point numbers in the C language
  5030. // is shown in Fig. 3.
  5031. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5032. const double val = [&half]
  5033. {
  5034. const int exp = (half >> 10u) & 0x1Fu;
  5035. const unsigned int mant = half & 0x3FFu;
  5036. assert(0 <= exp and exp <= 32);
  5037. assert(mant <= 1024);
  5038. switch (exp)
  5039. {
  5040. case 0:
  5041. return std::ldexp(mant, -24);
  5042. case 31:
  5043. return (mant == 0)
  5044. ? std::numeric_limits<double>::infinity()
  5045. : std::numeric_limits<double>::quiet_NaN();
  5046. default:
  5047. return std::ldexp(mant + 1024, exp - 25);
  5048. }
  5049. }();
  5050. return sax->number_float((half & 0x8000u) != 0
  5051. ? static_cast<number_float_t>(-val)
  5052. : static_cast<number_float_t>(val), "");
  5053. }
  5054. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5055. {
  5056. float number;
  5057. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5058. }
  5059. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5060. {
  5061. double number;
  5062. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5063. }
  5064. default: // anything else (0xFF is handled inside the other types)
  5065. {
  5066. auto last_token = get_token_string();
  5067. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value")));
  5068. }
  5069. }
  5070. }
  5071. /*!
  5072. @brief reads a CBOR string
  5073. This function first reads starting bytes to determine the expected
  5074. string length and then copies this number of bytes into a string.
  5075. Additionally, CBOR's strings with indefinite lengths are supported.
  5076. @param[out] result created string
  5077. @return whether string creation completed
  5078. */
  5079. bool get_cbor_string(string_t& result)
  5080. {
  5081. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  5082. {
  5083. return false;
  5084. }
  5085. switch (current)
  5086. {
  5087. // UTF-8 string (0x00..0x17 bytes follow)
  5088. case 0x60:
  5089. case 0x61:
  5090. case 0x62:
  5091. case 0x63:
  5092. case 0x64:
  5093. case 0x65:
  5094. case 0x66:
  5095. case 0x67:
  5096. case 0x68:
  5097. case 0x69:
  5098. case 0x6A:
  5099. case 0x6B:
  5100. case 0x6C:
  5101. case 0x6D:
  5102. case 0x6E:
  5103. case 0x6F:
  5104. case 0x70:
  5105. case 0x71:
  5106. case 0x72:
  5107. case 0x73:
  5108. case 0x74:
  5109. case 0x75:
  5110. case 0x76:
  5111. case 0x77:
  5112. {
  5113. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5114. }
  5115. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5116. {
  5117. std::uint8_t len;
  5118. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5119. }
  5120. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5121. {
  5122. std::uint16_t len;
  5123. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5124. }
  5125. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5126. {
  5127. std::uint32_t len;
  5128. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5129. }
  5130. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5131. {
  5132. std::uint64_t len;
  5133. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  5134. }
  5135. case 0x7F: // UTF-8 string (indefinite length)
  5136. {
  5137. while (get() != 0xFF)
  5138. {
  5139. string_t chunk;
  5140. if (not get_cbor_string(chunk))
  5141. {
  5142. return false;
  5143. }
  5144. result.append(chunk);
  5145. }
  5146. return true;
  5147. }
  5148. default:
  5149. {
  5150. auto last_token = get_token_string();
  5151. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string")));
  5152. }
  5153. }
  5154. }
  5155. /*!
  5156. @param[in] len the length of the array or std::size_t(-1) for an
  5157. array of indefinite size
  5158. @return whether array creation completed
  5159. */
  5160. bool get_cbor_array(const std::size_t len)
  5161. {
  5162. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5163. {
  5164. return false;
  5165. }
  5166. if (len != std::size_t(-1))
  5167. {
  5168. for (std::size_t i = 0; i < len; ++i)
  5169. {
  5170. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5171. {
  5172. return false;
  5173. }
  5174. }
  5175. }
  5176. else
  5177. {
  5178. while (get() != 0xFF)
  5179. {
  5180. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal(false)))
  5181. {
  5182. return false;
  5183. }
  5184. }
  5185. }
  5186. return sax->end_array();
  5187. }
  5188. /*!
  5189. @param[in] len the length of the object or std::size_t(-1) for an
  5190. object of indefinite size
  5191. @return whether object creation completed
  5192. */
  5193. bool get_cbor_object(const std::size_t len)
  5194. {
  5195. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5196. {
  5197. return false;
  5198. }
  5199. string_t key;
  5200. if (len != std::size_t(-1))
  5201. {
  5202. for (std::size_t i = 0; i < len; ++i)
  5203. {
  5204. get();
  5205. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5206. {
  5207. return false;
  5208. }
  5209. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5210. {
  5211. return false;
  5212. }
  5213. key.clear();
  5214. }
  5215. }
  5216. else
  5217. {
  5218. while (get() != 0xFF)
  5219. {
  5220. if (JSON_HEDLEY_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  5221. {
  5222. return false;
  5223. }
  5224. if (JSON_HEDLEY_UNLIKELY(not parse_cbor_internal()))
  5225. {
  5226. return false;
  5227. }
  5228. key.clear();
  5229. }
  5230. }
  5231. return sax->end_object();
  5232. }
  5233. /////////////
  5234. // MsgPack //
  5235. /////////////
  5236. /*!
  5237. @return whether a valid MessagePack value was passed to the SAX parser
  5238. */
  5239. bool parse_msgpack_internal()
  5240. {
  5241. switch (get())
  5242. {
  5243. // EOF
  5244. case std::char_traits<char>::eof():
  5245. return unexpect_eof(input_format_t::msgpack, "value");
  5246. // positive fixint
  5247. case 0x00:
  5248. case 0x01:
  5249. case 0x02:
  5250. case 0x03:
  5251. case 0x04:
  5252. case 0x05:
  5253. case 0x06:
  5254. case 0x07:
  5255. case 0x08:
  5256. case 0x09:
  5257. case 0x0A:
  5258. case 0x0B:
  5259. case 0x0C:
  5260. case 0x0D:
  5261. case 0x0E:
  5262. case 0x0F:
  5263. case 0x10:
  5264. case 0x11:
  5265. case 0x12:
  5266. case 0x13:
  5267. case 0x14:
  5268. case 0x15:
  5269. case 0x16:
  5270. case 0x17:
  5271. case 0x18:
  5272. case 0x19:
  5273. case 0x1A:
  5274. case 0x1B:
  5275. case 0x1C:
  5276. case 0x1D:
  5277. case 0x1E:
  5278. case 0x1F:
  5279. case 0x20:
  5280. case 0x21:
  5281. case 0x22:
  5282. case 0x23:
  5283. case 0x24:
  5284. case 0x25:
  5285. case 0x26:
  5286. case 0x27:
  5287. case 0x28:
  5288. case 0x29:
  5289. case 0x2A:
  5290. case 0x2B:
  5291. case 0x2C:
  5292. case 0x2D:
  5293. case 0x2E:
  5294. case 0x2F:
  5295. case 0x30:
  5296. case 0x31:
  5297. case 0x32:
  5298. case 0x33:
  5299. case 0x34:
  5300. case 0x35:
  5301. case 0x36:
  5302. case 0x37:
  5303. case 0x38:
  5304. case 0x39:
  5305. case 0x3A:
  5306. case 0x3B:
  5307. case 0x3C:
  5308. case 0x3D:
  5309. case 0x3E:
  5310. case 0x3F:
  5311. case 0x40:
  5312. case 0x41:
  5313. case 0x42:
  5314. case 0x43:
  5315. case 0x44:
  5316. case 0x45:
  5317. case 0x46:
  5318. case 0x47:
  5319. case 0x48:
  5320. case 0x49:
  5321. case 0x4A:
  5322. case 0x4B:
  5323. case 0x4C:
  5324. case 0x4D:
  5325. case 0x4E:
  5326. case 0x4F:
  5327. case 0x50:
  5328. case 0x51:
  5329. case 0x52:
  5330. case 0x53:
  5331. case 0x54:
  5332. case 0x55:
  5333. case 0x56:
  5334. case 0x57:
  5335. case 0x58:
  5336. case 0x59:
  5337. case 0x5A:
  5338. case 0x5B:
  5339. case 0x5C:
  5340. case 0x5D:
  5341. case 0x5E:
  5342. case 0x5F:
  5343. case 0x60:
  5344. case 0x61:
  5345. case 0x62:
  5346. case 0x63:
  5347. case 0x64:
  5348. case 0x65:
  5349. case 0x66:
  5350. case 0x67:
  5351. case 0x68:
  5352. case 0x69:
  5353. case 0x6A:
  5354. case 0x6B:
  5355. case 0x6C:
  5356. case 0x6D:
  5357. case 0x6E:
  5358. case 0x6F:
  5359. case 0x70:
  5360. case 0x71:
  5361. case 0x72:
  5362. case 0x73:
  5363. case 0x74:
  5364. case 0x75:
  5365. case 0x76:
  5366. case 0x77:
  5367. case 0x78:
  5368. case 0x79:
  5369. case 0x7A:
  5370. case 0x7B:
  5371. case 0x7C:
  5372. case 0x7D:
  5373. case 0x7E:
  5374. case 0x7F:
  5375. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5376. // fixmap
  5377. case 0x80:
  5378. case 0x81:
  5379. case 0x82:
  5380. case 0x83:
  5381. case 0x84:
  5382. case 0x85:
  5383. case 0x86:
  5384. case 0x87:
  5385. case 0x88:
  5386. case 0x89:
  5387. case 0x8A:
  5388. case 0x8B:
  5389. case 0x8C:
  5390. case 0x8D:
  5391. case 0x8E:
  5392. case 0x8F:
  5393. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5394. // fixarray
  5395. case 0x90:
  5396. case 0x91:
  5397. case 0x92:
  5398. case 0x93:
  5399. case 0x94:
  5400. case 0x95:
  5401. case 0x96:
  5402. case 0x97:
  5403. case 0x98:
  5404. case 0x99:
  5405. case 0x9A:
  5406. case 0x9B:
  5407. case 0x9C:
  5408. case 0x9D:
  5409. case 0x9E:
  5410. case 0x9F:
  5411. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  5412. // fixstr
  5413. case 0xA0:
  5414. case 0xA1:
  5415. case 0xA2:
  5416. case 0xA3:
  5417. case 0xA4:
  5418. case 0xA5:
  5419. case 0xA6:
  5420. case 0xA7:
  5421. case 0xA8:
  5422. case 0xA9:
  5423. case 0xAA:
  5424. case 0xAB:
  5425. case 0xAC:
  5426. case 0xAD:
  5427. case 0xAE:
  5428. case 0xAF:
  5429. case 0xB0:
  5430. case 0xB1:
  5431. case 0xB2:
  5432. case 0xB3:
  5433. case 0xB4:
  5434. case 0xB5:
  5435. case 0xB6:
  5436. case 0xB7:
  5437. case 0xB8:
  5438. case 0xB9:
  5439. case 0xBA:
  5440. case 0xBB:
  5441. case 0xBC:
  5442. case 0xBD:
  5443. case 0xBE:
  5444. case 0xBF:
  5445. case 0xD9: // str 8
  5446. case 0xDA: // str 16
  5447. case 0xDB: // str 32
  5448. {
  5449. string_t s;
  5450. return get_msgpack_string(s) and sax->string(s);
  5451. }
  5452. case 0xC0: // nil
  5453. return sax->null();
  5454. case 0xC2: // false
  5455. return sax->boolean(false);
  5456. case 0xC3: // true
  5457. return sax->boolean(true);
  5458. case 0xCA: // float 32
  5459. {
  5460. float number;
  5461. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5462. }
  5463. case 0xCB: // float 64
  5464. {
  5465. double number;
  5466. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5467. }
  5468. case 0xCC: // uint 8
  5469. {
  5470. std::uint8_t number;
  5471. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5472. }
  5473. case 0xCD: // uint 16
  5474. {
  5475. std::uint16_t number;
  5476. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5477. }
  5478. case 0xCE: // uint 32
  5479. {
  5480. std::uint32_t number;
  5481. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5482. }
  5483. case 0xCF: // uint 64
  5484. {
  5485. std::uint64_t number;
  5486. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  5487. }
  5488. case 0xD0: // int 8
  5489. {
  5490. std::int8_t number;
  5491. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5492. }
  5493. case 0xD1: // int 16
  5494. {
  5495. std::int16_t number;
  5496. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5497. }
  5498. case 0xD2: // int 32
  5499. {
  5500. std::int32_t number;
  5501. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5502. }
  5503. case 0xD3: // int 64
  5504. {
  5505. std::int64_t number;
  5506. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  5507. }
  5508. case 0xDC: // array 16
  5509. {
  5510. std::uint16_t len;
  5511. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5512. }
  5513. case 0xDD: // array 32
  5514. {
  5515. std::uint32_t len;
  5516. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  5517. }
  5518. case 0xDE: // map 16
  5519. {
  5520. std::uint16_t len;
  5521. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5522. }
  5523. case 0xDF: // map 32
  5524. {
  5525. std::uint32_t len;
  5526. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  5527. }
  5528. // negative fixint
  5529. case 0xE0:
  5530. case 0xE1:
  5531. case 0xE2:
  5532. case 0xE3:
  5533. case 0xE4:
  5534. case 0xE5:
  5535. case 0xE6:
  5536. case 0xE7:
  5537. case 0xE8:
  5538. case 0xE9:
  5539. case 0xEA:
  5540. case 0xEB:
  5541. case 0xEC:
  5542. case 0xED:
  5543. case 0xEE:
  5544. case 0xEF:
  5545. case 0xF0:
  5546. case 0xF1:
  5547. case 0xF2:
  5548. case 0xF3:
  5549. case 0xF4:
  5550. case 0xF5:
  5551. case 0xF6:
  5552. case 0xF7:
  5553. case 0xF8:
  5554. case 0xF9:
  5555. case 0xFA:
  5556. case 0xFB:
  5557. case 0xFC:
  5558. case 0xFD:
  5559. case 0xFE:
  5560. case 0xFF:
  5561. return sax->number_integer(static_cast<std::int8_t>(current));
  5562. default: // anything else
  5563. {
  5564. auto last_token = get_token_string();
  5565. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value")));
  5566. }
  5567. }
  5568. }
  5569. /*!
  5570. @brief reads a MessagePack string
  5571. This function first reads starting bytes to determine the expected
  5572. string length and then copies this number of bytes into a string.
  5573. @param[out] result created string
  5574. @return whether string creation completed
  5575. */
  5576. bool get_msgpack_string(string_t& result)
  5577. {
  5578. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  5579. {
  5580. return false;
  5581. }
  5582. switch (current)
  5583. {
  5584. // fixstr
  5585. case 0xA0:
  5586. case 0xA1:
  5587. case 0xA2:
  5588. case 0xA3:
  5589. case 0xA4:
  5590. case 0xA5:
  5591. case 0xA6:
  5592. case 0xA7:
  5593. case 0xA8:
  5594. case 0xA9:
  5595. case 0xAA:
  5596. case 0xAB:
  5597. case 0xAC:
  5598. case 0xAD:
  5599. case 0xAE:
  5600. case 0xAF:
  5601. case 0xB0:
  5602. case 0xB1:
  5603. case 0xB2:
  5604. case 0xB3:
  5605. case 0xB4:
  5606. case 0xB5:
  5607. case 0xB6:
  5608. case 0xB7:
  5609. case 0xB8:
  5610. case 0xB9:
  5611. case 0xBA:
  5612. case 0xBB:
  5613. case 0xBC:
  5614. case 0xBD:
  5615. case 0xBE:
  5616. case 0xBF:
  5617. {
  5618. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  5619. }
  5620. case 0xD9: // str 8
  5621. {
  5622. std::uint8_t len;
  5623. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5624. }
  5625. case 0xDA: // str 16
  5626. {
  5627. std::uint16_t len;
  5628. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5629. }
  5630. case 0xDB: // str 32
  5631. {
  5632. std::uint32_t len;
  5633. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  5634. }
  5635. default:
  5636. {
  5637. auto last_token = get_token_string();
  5638. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string")));
  5639. }
  5640. }
  5641. }
  5642. /*!
  5643. @param[in] len the length of the array
  5644. @return whether array creation completed
  5645. */
  5646. bool get_msgpack_array(const std::size_t len)
  5647. {
  5648. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(len)))
  5649. {
  5650. return false;
  5651. }
  5652. for (std::size_t i = 0; i < len; ++i)
  5653. {
  5654. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5655. {
  5656. return false;
  5657. }
  5658. }
  5659. return sax->end_array();
  5660. }
  5661. /*!
  5662. @param[in] len the length of the object
  5663. @return whether object creation completed
  5664. */
  5665. bool get_msgpack_object(const std::size_t len)
  5666. {
  5667. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(len)))
  5668. {
  5669. return false;
  5670. }
  5671. string_t key;
  5672. for (std::size_t i = 0; i < len; ++i)
  5673. {
  5674. get();
  5675. if (JSON_HEDLEY_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  5676. {
  5677. return false;
  5678. }
  5679. if (JSON_HEDLEY_UNLIKELY(not parse_msgpack_internal()))
  5680. {
  5681. return false;
  5682. }
  5683. key.clear();
  5684. }
  5685. return sax->end_object();
  5686. }
  5687. ////////////
  5688. // UBJSON //
  5689. ////////////
  5690. /*!
  5691. @param[in] get_char whether a new character should be retrieved from the
  5692. input (true, default) or whether the last read
  5693. character should be considered instead
  5694. @return whether a valid UBJSON value was passed to the SAX parser
  5695. */
  5696. bool parse_ubjson_internal(const bool get_char = true)
  5697. {
  5698. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  5699. }
  5700. /*!
  5701. @brief reads a UBJSON string
  5702. This function is either called after reading the 'S' byte explicitly
  5703. indicating a string, or in case of an object key where the 'S' byte can be
  5704. left out.
  5705. @param[out] result created string
  5706. @param[in] get_char whether a new character should be retrieved from the
  5707. input (true, default) or whether the last read
  5708. character should be considered instead
  5709. @return whether string creation completed
  5710. */
  5711. bool get_ubjson_string(string_t& result, const bool get_char = true)
  5712. {
  5713. if (get_char)
  5714. {
  5715. get(); // TODO(niels): may we ignore N here?
  5716. }
  5717. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5718. {
  5719. return false;
  5720. }
  5721. switch (current)
  5722. {
  5723. case 'U':
  5724. {
  5725. std::uint8_t len;
  5726. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5727. }
  5728. case 'i':
  5729. {
  5730. std::int8_t len;
  5731. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5732. }
  5733. case 'I':
  5734. {
  5735. std::int16_t len;
  5736. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5737. }
  5738. case 'l':
  5739. {
  5740. std::int32_t len;
  5741. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5742. }
  5743. case 'L':
  5744. {
  5745. std::int64_t len;
  5746. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  5747. }
  5748. default:
  5749. auto last_token = get_token_string();
  5750. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string")));
  5751. }
  5752. }
  5753. /*!
  5754. @param[out] result determined size
  5755. @return whether size determination completed
  5756. */
  5757. bool get_ubjson_size_value(std::size_t& result)
  5758. {
  5759. switch (get_ignore_noop())
  5760. {
  5761. case 'U':
  5762. {
  5763. std::uint8_t number;
  5764. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5765. {
  5766. return false;
  5767. }
  5768. result = static_cast<std::size_t>(number);
  5769. return true;
  5770. }
  5771. case 'i':
  5772. {
  5773. std::int8_t number;
  5774. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5775. {
  5776. return false;
  5777. }
  5778. result = static_cast<std::size_t>(number);
  5779. return true;
  5780. }
  5781. case 'I':
  5782. {
  5783. std::int16_t number;
  5784. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5785. {
  5786. return false;
  5787. }
  5788. result = static_cast<std::size_t>(number);
  5789. return true;
  5790. }
  5791. case 'l':
  5792. {
  5793. std::int32_t number;
  5794. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5795. {
  5796. return false;
  5797. }
  5798. result = static_cast<std::size_t>(number);
  5799. return true;
  5800. }
  5801. case 'L':
  5802. {
  5803. std::int64_t number;
  5804. if (JSON_HEDLEY_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  5805. {
  5806. return false;
  5807. }
  5808. result = static_cast<std::size_t>(number);
  5809. return true;
  5810. }
  5811. default:
  5812. {
  5813. auto last_token = get_token_string();
  5814. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size")));
  5815. }
  5816. }
  5817. }
  5818. /*!
  5819. @brief determine the type and size for a container
  5820. In the optimized UBJSON format, a type and a size can be provided to allow
  5821. for a more compact representation.
  5822. @param[out] result pair of the size and the type
  5823. @return whether pair creation completed
  5824. */
  5825. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  5826. {
  5827. result.first = string_t::npos; // size
  5828. result.second = 0; // type
  5829. get_ignore_noop();
  5830. if (current == '$')
  5831. {
  5832. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  5833. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  5834. {
  5835. return false;
  5836. }
  5837. get_ignore_noop();
  5838. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  5839. {
  5840. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  5841. {
  5842. return false;
  5843. }
  5844. auto last_token = get_token_string();
  5845. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size")));
  5846. }
  5847. return get_ubjson_size_value(result.first);
  5848. }
  5849. if (current == '#')
  5850. {
  5851. return get_ubjson_size_value(result.first);
  5852. }
  5853. return true;
  5854. }
  5855. /*!
  5856. @param prefix the previously read or set type prefix
  5857. @return whether value creation completed
  5858. */
  5859. bool get_ubjson_value(const int prefix)
  5860. {
  5861. switch (prefix)
  5862. {
  5863. case std::char_traits<char>::eof(): // EOF
  5864. return unexpect_eof(input_format_t::ubjson, "value");
  5865. case 'T': // true
  5866. return sax->boolean(true);
  5867. case 'F': // false
  5868. return sax->boolean(false);
  5869. case 'Z': // null
  5870. return sax->null();
  5871. case 'U':
  5872. {
  5873. std::uint8_t number;
  5874. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  5875. }
  5876. case 'i':
  5877. {
  5878. std::int8_t number;
  5879. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5880. }
  5881. case 'I':
  5882. {
  5883. std::int16_t number;
  5884. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5885. }
  5886. case 'l':
  5887. {
  5888. std::int32_t number;
  5889. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5890. }
  5891. case 'L':
  5892. {
  5893. std::int64_t number;
  5894. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  5895. }
  5896. case 'd':
  5897. {
  5898. float number;
  5899. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5900. }
  5901. case 'D':
  5902. {
  5903. double number;
  5904. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  5905. }
  5906. case 'C': // char
  5907. {
  5908. get();
  5909. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  5910. {
  5911. return false;
  5912. }
  5913. if (JSON_HEDLEY_UNLIKELY(current > 127))
  5914. {
  5915. auto last_token = get_token_string();
  5916. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char")));
  5917. }
  5918. string_t s(1, static_cast<char>(current));
  5919. return sax->string(s);
  5920. }
  5921. case 'S': // string
  5922. {
  5923. string_t s;
  5924. return get_ubjson_string(s) and sax->string(s);
  5925. }
  5926. case '[': // array
  5927. return get_ubjson_array();
  5928. case '{': // object
  5929. return get_ubjson_object();
  5930. default: // anything else
  5931. {
  5932. auto last_token = get_token_string();
  5933. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value")));
  5934. }
  5935. }
  5936. }
  5937. /*!
  5938. @return whether array creation completed
  5939. */
  5940. bool get_ubjson_array()
  5941. {
  5942. std::pair<std::size_t, int> size_and_type;
  5943. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  5944. {
  5945. return false;
  5946. }
  5947. if (size_and_type.first != string_t::npos)
  5948. {
  5949. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(size_and_type.first)))
  5950. {
  5951. return false;
  5952. }
  5953. if (size_and_type.second != 0)
  5954. {
  5955. if (size_and_type.second != 'N')
  5956. {
  5957. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5958. {
  5959. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  5960. {
  5961. return false;
  5962. }
  5963. }
  5964. }
  5965. }
  5966. else
  5967. {
  5968. for (std::size_t i = 0; i < size_and_type.first; ++i)
  5969. {
  5970. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  5971. {
  5972. return false;
  5973. }
  5974. }
  5975. }
  5976. }
  5977. else
  5978. {
  5979. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  5980. {
  5981. return false;
  5982. }
  5983. while (current != ']')
  5984. {
  5985. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal(false)))
  5986. {
  5987. return false;
  5988. }
  5989. get_ignore_noop();
  5990. }
  5991. }
  5992. return sax->end_array();
  5993. }
  5994. /*!
  5995. @return whether object creation completed
  5996. */
  5997. bool get_ubjson_object()
  5998. {
  5999. std::pair<std::size_t, int> size_and_type;
  6000. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6001. {
  6002. return false;
  6003. }
  6004. string_t key;
  6005. if (size_and_type.first != string_t::npos)
  6006. {
  6007. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(size_and_type.first)))
  6008. {
  6009. return false;
  6010. }
  6011. if (size_and_type.second != 0)
  6012. {
  6013. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6014. {
  6015. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6016. {
  6017. return false;
  6018. }
  6019. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6020. {
  6021. return false;
  6022. }
  6023. key.clear();
  6024. }
  6025. }
  6026. else
  6027. {
  6028. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6029. {
  6030. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6031. {
  6032. return false;
  6033. }
  6034. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6035. {
  6036. return false;
  6037. }
  6038. key.clear();
  6039. }
  6040. }
  6041. }
  6042. else
  6043. {
  6044. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6045. {
  6046. return false;
  6047. }
  6048. while (current != '}')
  6049. {
  6050. if (JSON_HEDLEY_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6051. {
  6052. return false;
  6053. }
  6054. if (JSON_HEDLEY_UNLIKELY(not parse_ubjson_internal()))
  6055. {
  6056. return false;
  6057. }
  6058. get_ignore_noop();
  6059. key.clear();
  6060. }
  6061. }
  6062. return sax->end_object();
  6063. }
  6064. ///////////////////////
  6065. // Utility functions //
  6066. ///////////////////////
  6067. /*!
  6068. @brief get next character from the input
  6069. This function provides the interface to the used input adapter. It does
  6070. not throw in case the input reached EOF, but returns a -'ve valued
  6071. `std::char_traits<char>::eof()` in that case.
  6072. @return character read from the input
  6073. */
  6074. int get()
  6075. {
  6076. ++chars_read;
  6077. return current = ia->get_character();
  6078. }
  6079. /*!
  6080. @return character read from the input after ignoring all 'N' entries
  6081. */
  6082. int get_ignore_noop()
  6083. {
  6084. do
  6085. {
  6086. get();
  6087. }
  6088. while (current == 'N');
  6089. return current;
  6090. }
  6091. /*
  6092. @brief read a number from the input
  6093. @tparam NumberType the type of the number
  6094. @param[in] format the current format (for diagnostics)
  6095. @param[out] result number of type @a NumberType
  6096. @return whether conversion completed
  6097. @note This function needs to respect the system's endianess, because
  6098. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6099. (big endian) and therefore need reordering on little endian systems.
  6100. */
  6101. template<typename NumberType, bool InputIsLittleEndian = false>
  6102. bool get_number(const input_format_t format, NumberType& result)
  6103. {
  6104. // step 1: read input into array with system's byte order
  6105. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6106. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6107. {
  6108. get();
  6109. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "number")))
  6110. {
  6111. return false;
  6112. }
  6113. // reverse byte order prior to conversion if necessary
  6114. if (is_little_endian != InputIsLittleEndian)
  6115. {
  6116. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6117. }
  6118. else
  6119. {
  6120. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6121. }
  6122. }
  6123. // step 2: convert array into number of type T and return
  6124. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6125. return true;
  6126. }
  6127. /*!
  6128. @brief create a string by reading characters from the input
  6129. @tparam NumberType the type of the number
  6130. @param[in] format the current format (for diagnostics)
  6131. @param[in] len number of characters to read
  6132. @param[out] result string created by reading @a len bytes
  6133. @return whether string creation completed
  6134. @note We can not reserve @a len bytes for the result, because @a len
  6135. may be too large. Usually, @ref unexpect_eof() detects the end of
  6136. the input before we run out of string memory.
  6137. */
  6138. template<typename NumberType>
  6139. bool get_string(const input_format_t format,
  6140. const NumberType len,
  6141. string_t& result)
  6142. {
  6143. bool success = true;
  6144. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6145. {
  6146. get();
  6147. if (JSON_HEDLEY_UNLIKELY(not unexpect_eof(format, "string")))
  6148. {
  6149. success = false;
  6150. }
  6151. return static_cast<char>(current);
  6152. });
  6153. return success;
  6154. }
  6155. /*!
  6156. @param[in] format the current format (for diagnostics)
  6157. @param[in] context further context information (for diagnostics)
  6158. @return whether the last read character is not EOF
  6159. */
  6160. JSON_HEDLEY_NON_NULL(3)
  6161. bool unexpect_eof(const input_format_t format, const char* context) const
  6162. {
  6163. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char>::eof()))
  6164. {
  6165. return sax->parse_error(chars_read, "<end of file>",
  6166. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  6167. }
  6168. return true;
  6169. }
  6170. /*!
  6171. @return a string representation of the last read byte
  6172. */
  6173. std::string get_token_string() const
  6174. {
  6175. std::array<char, 3> cr{{}};
  6176. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  6177. return std::string{cr.data()};
  6178. }
  6179. /*!
  6180. @param[in] format the current format
  6181. @param[in] detail a detailed error message
  6182. @param[in] context further context information
  6183. @return a message string to use in the parse_error exceptions
  6184. */
  6185. std::string exception_message(const input_format_t format,
  6186. const std::string& detail,
  6187. const std::string& context) const
  6188. {
  6189. std::string error_msg = "syntax error while parsing ";
  6190. switch (format)
  6191. {
  6192. case input_format_t::cbor:
  6193. error_msg += "CBOR";
  6194. break;
  6195. case input_format_t::msgpack:
  6196. error_msg += "MessagePack";
  6197. break;
  6198. case input_format_t::ubjson:
  6199. error_msg += "UBJSON";
  6200. break;
  6201. case input_format_t::bson:
  6202. error_msg += "BSON";
  6203. break;
  6204. default: // LCOV_EXCL_LINE
  6205. assert(false); // LCOV_EXCL_LINE
  6206. }
  6207. return error_msg + " " + context + ": " + detail;
  6208. }
  6209. private:
  6210. /// input adapter
  6211. input_adapter_t ia = nullptr;
  6212. /// the current character
  6213. int current = std::char_traits<char>::eof();
  6214. /// the number of characters read
  6215. std::size_t chars_read = 0;
  6216. /// whether we can assume little endianess
  6217. const bool is_little_endian = little_endianess();
  6218. /// the SAX parser
  6219. json_sax_t* sax = nullptr;
  6220. };
  6221. } // namespace detail
  6222. } // namespace nlohmann
  6223. // #include <nlohmann/detail/input/input_adapters.hpp>
  6224. // #include <nlohmann/detail/input/lexer.hpp>
  6225. #include <array> // array
  6226. #include <clocale> // localeconv
  6227. #include <cstddef> // size_t
  6228. #include <cstdio> // snprintf
  6229. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  6230. #include <initializer_list> // initializer_list
  6231. #include <string> // char_traits, string
  6232. #include <utility> // move
  6233. #include <vector> // vector
  6234. // #include <nlohmann/detail/input/input_adapters.hpp>
  6235. // #include <nlohmann/detail/input/position_t.hpp>
  6236. // #include <nlohmann/detail/macro_scope.hpp>
  6237. namespace nlohmann
  6238. {
  6239. namespace detail
  6240. {
  6241. ///////////
  6242. // lexer //
  6243. ///////////
  6244. /*!
  6245. @brief lexical analysis
  6246. This class organizes the lexical analysis during JSON deserialization.
  6247. */
  6248. template<typename BasicJsonType>
  6249. class lexer
  6250. {
  6251. using number_integer_t = typename BasicJsonType::number_integer_t;
  6252. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6253. using number_float_t = typename BasicJsonType::number_float_t;
  6254. using string_t = typename BasicJsonType::string_t;
  6255. public:
  6256. /// token types for the parser
  6257. enum class token_type
  6258. {
  6259. uninitialized, ///< indicating the scanner is uninitialized
  6260. literal_true, ///< the `true` literal
  6261. literal_false, ///< the `false` literal
  6262. literal_null, ///< the `null` literal
  6263. value_string, ///< a string -- use get_string() for actual value
  6264. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  6265. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  6266. value_float, ///< an floating point number -- use get_number_float() for actual value
  6267. begin_array, ///< the character for array begin `[`
  6268. begin_object, ///< the character for object begin `{`
  6269. end_array, ///< the character for array end `]`
  6270. end_object, ///< the character for object end `}`
  6271. name_separator, ///< the name separator `:`
  6272. value_separator, ///< the value separator `,`
  6273. parse_error, ///< indicating a parse error
  6274. end_of_input, ///< indicating the end of the input buffer
  6275. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  6276. };
  6277. /// return name of values of type token_type (only used for errors)
  6278. JSON_HEDLEY_RETURNS_NON_NULL
  6279. JSON_HEDLEY_CONST
  6280. static const char* token_type_name(const token_type t) noexcept
  6281. {
  6282. switch (t)
  6283. {
  6284. case token_type::uninitialized:
  6285. return "<uninitialized>";
  6286. case token_type::literal_true:
  6287. return "true literal";
  6288. case token_type::literal_false:
  6289. return "false literal";
  6290. case token_type::literal_null:
  6291. return "null literal";
  6292. case token_type::value_string:
  6293. return "string literal";
  6294. case lexer::token_type::value_unsigned:
  6295. case lexer::token_type::value_integer:
  6296. case lexer::token_type::value_float:
  6297. return "number literal";
  6298. case token_type::begin_array:
  6299. return "'['";
  6300. case token_type::begin_object:
  6301. return "'{'";
  6302. case token_type::end_array:
  6303. return "']'";
  6304. case token_type::end_object:
  6305. return "'}'";
  6306. case token_type::name_separator:
  6307. return "':'";
  6308. case token_type::value_separator:
  6309. return "','";
  6310. case token_type::parse_error:
  6311. return "<parse error>";
  6312. case token_type::end_of_input:
  6313. return "end of input";
  6314. case token_type::literal_or_value:
  6315. return "'[', '{', or a literal";
  6316. // LCOV_EXCL_START
  6317. default: // catch non-enum values
  6318. return "unknown token";
  6319. // LCOV_EXCL_STOP
  6320. }
  6321. }
  6322. explicit lexer(detail::input_adapter_t&& adapter)
  6323. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  6324. // delete because of pointer members
  6325. lexer(const lexer&) = delete;
  6326. lexer(lexer&&) = delete;
  6327. lexer& operator=(lexer&) = delete;
  6328. lexer& operator=(lexer&&) = delete;
  6329. ~lexer() = default;
  6330. private:
  6331. /////////////////////
  6332. // locales
  6333. /////////////////////
  6334. /// return the locale-dependent decimal point
  6335. JSON_HEDLEY_PURE
  6336. static char get_decimal_point() noexcept
  6337. {
  6338. const auto loc = localeconv();
  6339. assert(loc != nullptr);
  6340. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  6341. }
  6342. /////////////////////
  6343. // scan functions
  6344. /////////////////////
  6345. /*!
  6346. @brief get codepoint from 4 hex characters following `\u`
  6347. For input "\u c1 c2 c3 c4" the codepoint is:
  6348. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  6349. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  6350. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  6351. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  6352. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  6353. between the ASCII value of the character and the desired integer value.
  6354. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  6355. non-hex character)
  6356. */
  6357. int get_codepoint()
  6358. {
  6359. // this function only makes sense after reading `\u`
  6360. assert(current == 'u');
  6361. int codepoint = 0;
  6362. const auto factors = { 12u, 8u, 4u, 0u };
  6363. for (const auto factor : factors)
  6364. {
  6365. get();
  6366. if (current >= '0' and current <= '9')
  6367. {
  6368. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  6369. }
  6370. else if (current >= 'A' and current <= 'F')
  6371. {
  6372. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  6373. }
  6374. else if (current >= 'a' and current <= 'f')
  6375. {
  6376. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  6377. }
  6378. else
  6379. {
  6380. return -1;
  6381. }
  6382. }
  6383. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  6384. return codepoint;
  6385. }
  6386. /*!
  6387. @brief check if the next byte(s) are inside a given range
  6388. Adds the current byte and, for each passed range, reads a new byte and
  6389. checks if it is inside the range. If a violation was detected, set up an
  6390. error message and return false. Otherwise, return true.
  6391. @param[in] ranges list of integers; interpreted as list of pairs of
  6392. inclusive lower and upper bound, respectively
  6393. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  6394. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  6395. @return true if and only if no range violation was detected
  6396. */
  6397. bool next_byte_in_range(std::initializer_list<int> ranges)
  6398. {
  6399. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  6400. add(current);
  6401. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  6402. {
  6403. get();
  6404. if (JSON_HEDLEY_LIKELY(*range <= current and current <= *(++range)))
  6405. {
  6406. add(current);
  6407. }
  6408. else
  6409. {
  6410. error_message = "invalid string: ill-formed UTF-8 byte";
  6411. return false;
  6412. }
  6413. }
  6414. return true;
  6415. }
  6416. /*!
  6417. @brief scan a string literal
  6418. This function scans a string according to Sect. 7 of RFC 7159. While
  6419. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  6420. function returns successfully, token_buffer is *not* null-terminated (as it
  6421. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  6422. string.
  6423. @return token_type::value_string if string could be successfully scanned,
  6424. token_type::parse_error otherwise
  6425. @note In case of errors, variable error_message contains a textual
  6426. description.
  6427. */
  6428. token_type scan_string()
  6429. {
  6430. // reset token_buffer (ignore opening quote)
  6431. reset();
  6432. // we entered the function by reading an open quote
  6433. assert(current == '\"');
  6434. while (true)
  6435. {
  6436. // get next character
  6437. switch (get())
  6438. {
  6439. // end of file while parsing string
  6440. case std::char_traits<char>::eof():
  6441. {
  6442. error_message = "invalid string: missing closing quote";
  6443. return token_type::parse_error;
  6444. }
  6445. // closing quote
  6446. case '\"':
  6447. {
  6448. return token_type::value_string;
  6449. }
  6450. // escapes
  6451. case '\\':
  6452. {
  6453. switch (get())
  6454. {
  6455. // quotation mark
  6456. case '\"':
  6457. add('\"');
  6458. break;
  6459. // reverse solidus
  6460. case '\\':
  6461. add('\\');
  6462. break;
  6463. // solidus
  6464. case '/':
  6465. add('/');
  6466. break;
  6467. // backspace
  6468. case 'b':
  6469. add('\b');
  6470. break;
  6471. // form feed
  6472. case 'f':
  6473. add('\f');
  6474. break;
  6475. // line feed
  6476. case 'n':
  6477. add('\n');
  6478. break;
  6479. // carriage return
  6480. case 'r':
  6481. add('\r');
  6482. break;
  6483. // tab
  6484. case 't':
  6485. add('\t');
  6486. break;
  6487. // unicode escapes
  6488. case 'u':
  6489. {
  6490. const int codepoint1 = get_codepoint();
  6491. int codepoint = codepoint1; // start with codepoint1
  6492. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  6493. {
  6494. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6495. return token_type::parse_error;
  6496. }
  6497. // check if code point is a high surrogate
  6498. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  6499. {
  6500. // expect next \uxxxx entry
  6501. if (JSON_HEDLEY_LIKELY(get() == '\\' and get() == 'u'))
  6502. {
  6503. const int codepoint2 = get_codepoint();
  6504. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  6505. {
  6506. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  6507. return token_type::parse_error;
  6508. }
  6509. // check if codepoint2 is a low surrogate
  6510. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  6511. {
  6512. // overwrite codepoint
  6513. codepoint = static_cast<int>(
  6514. // high surrogate occupies the most significant 22 bits
  6515. (static_cast<unsigned int>(codepoint1) << 10u)
  6516. // low surrogate occupies the least significant 15 bits
  6517. + static_cast<unsigned int>(codepoint2)
  6518. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6519. // in the result so we have to subtract with:
  6520. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6521. - 0x35FDC00u);
  6522. }
  6523. else
  6524. {
  6525. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6526. return token_type::parse_error;
  6527. }
  6528. }
  6529. else
  6530. {
  6531. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  6532. return token_type::parse_error;
  6533. }
  6534. }
  6535. else
  6536. {
  6537. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  6538. {
  6539. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  6540. return token_type::parse_error;
  6541. }
  6542. }
  6543. // result of the above calculation yields a proper codepoint
  6544. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  6545. // translate codepoint into bytes
  6546. if (codepoint < 0x80)
  6547. {
  6548. // 1-byte characters: 0xxxxxxx (ASCII)
  6549. add(codepoint);
  6550. }
  6551. else if (codepoint <= 0x7FF)
  6552. {
  6553. // 2-byte characters: 110xxxxx 10xxxxxx
  6554. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  6555. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6556. }
  6557. else if (codepoint <= 0xFFFF)
  6558. {
  6559. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6560. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  6561. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6562. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6563. }
  6564. else
  6565. {
  6566. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6567. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  6568. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  6569. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  6570. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  6571. }
  6572. break;
  6573. }
  6574. // other characters after escape
  6575. default:
  6576. error_message = "invalid string: forbidden character after backslash";
  6577. return token_type::parse_error;
  6578. }
  6579. break;
  6580. }
  6581. // invalid control characters
  6582. case 0x00:
  6583. {
  6584. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  6585. return token_type::parse_error;
  6586. }
  6587. case 0x01:
  6588. {
  6589. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  6590. return token_type::parse_error;
  6591. }
  6592. case 0x02:
  6593. {
  6594. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  6595. return token_type::parse_error;
  6596. }
  6597. case 0x03:
  6598. {
  6599. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  6600. return token_type::parse_error;
  6601. }
  6602. case 0x04:
  6603. {
  6604. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  6605. return token_type::parse_error;
  6606. }
  6607. case 0x05:
  6608. {
  6609. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  6610. return token_type::parse_error;
  6611. }
  6612. case 0x06:
  6613. {
  6614. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  6615. return token_type::parse_error;
  6616. }
  6617. case 0x07:
  6618. {
  6619. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  6620. return token_type::parse_error;
  6621. }
  6622. case 0x08:
  6623. {
  6624. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  6625. return token_type::parse_error;
  6626. }
  6627. case 0x09:
  6628. {
  6629. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  6630. return token_type::parse_error;
  6631. }
  6632. case 0x0A:
  6633. {
  6634. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  6635. return token_type::parse_error;
  6636. }
  6637. case 0x0B:
  6638. {
  6639. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  6640. return token_type::parse_error;
  6641. }
  6642. case 0x0C:
  6643. {
  6644. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  6645. return token_type::parse_error;
  6646. }
  6647. case 0x0D:
  6648. {
  6649. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  6650. return token_type::parse_error;
  6651. }
  6652. case 0x0E:
  6653. {
  6654. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  6655. return token_type::parse_error;
  6656. }
  6657. case 0x0F:
  6658. {
  6659. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  6660. return token_type::parse_error;
  6661. }
  6662. case 0x10:
  6663. {
  6664. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  6665. return token_type::parse_error;
  6666. }
  6667. case 0x11:
  6668. {
  6669. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  6670. return token_type::parse_error;
  6671. }
  6672. case 0x12:
  6673. {
  6674. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  6675. return token_type::parse_error;
  6676. }
  6677. case 0x13:
  6678. {
  6679. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  6680. return token_type::parse_error;
  6681. }
  6682. case 0x14:
  6683. {
  6684. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  6685. return token_type::parse_error;
  6686. }
  6687. case 0x15:
  6688. {
  6689. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  6690. return token_type::parse_error;
  6691. }
  6692. case 0x16:
  6693. {
  6694. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  6695. return token_type::parse_error;
  6696. }
  6697. case 0x17:
  6698. {
  6699. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  6700. return token_type::parse_error;
  6701. }
  6702. case 0x18:
  6703. {
  6704. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  6705. return token_type::parse_error;
  6706. }
  6707. case 0x19:
  6708. {
  6709. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  6710. return token_type::parse_error;
  6711. }
  6712. case 0x1A:
  6713. {
  6714. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  6715. return token_type::parse_error;
  6716. }
  6717. case 0x1B:
  6718. {
  6719. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  6720. return token_type::parse_error;
  6721. }
  6722. case 0x1C:
  6723. {
  6724. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  6725. return token_type::parse_error;
  6726. }
  6727. case 0x1D:
  6728. {
  6729. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  6730. return token_type::parse_error;
  6731. }
  6732. case 0x1E:
  6733. {
  6734. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  6735. return token_type::parse_error;
  6736. }
  6737. case 0x1F:
  6738. {
  6739. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  6740. return token_type::parse_error;
  6741. }
  6742. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  6743. case 0x20:
  6744. case 0x21:
  6745. case 0x23:
  6746. case 0x24:
  6747. case 0x25:
  6748. case 0x26:
  6749. case 0x27:
  6750. case 0x28:
  6751. case 0x29:
  6752. case 0x2A:
  6753. case 0x2B:
  6754. case 0x2C:
  6755. case 0x2D:
  6756. case 0x2E:
  6757. case 0x2F:
  6758. case 0x30:
  6759. case 0x31:
  6760. case 0x32:
  6761. case 0x33:
  6762. case 0x34:
  6763. case 0x35:
  6764. case 0x36:
  6765. case 0x37:
  6766. case 0x38:
  6767. case 0x39:
  6768. case 0x3A:
  6769. case 0x3B:
  6770. case 0x3C:
  6771. case 0x3D:
  6772. case 0x3E:
  6773. case 0x3F:
  6774. case 0x40:
  6775. case 0x41:
  6776. case 0x42:
  6777. case 0x43:
  6778. case 0x44:
  6779. case 0x45:
  6780. case 0x46:
  6781. case 0x47:
  6782. case 0x48:
  6783. case 0x49:
  6784. case 0x4A:
  6785. case 0x4B:
  6786. case 0x4C:
  6787. case 0x4D:
  6788. case 0x4E:
  6789. case 0x4F:
  6790. case 0x50:
  6791. case 0x51:
  6792. case 0x52:
  6793. case 0x53:
  6794. case 0x54:
  6795. case 0x55:
  6796. case 0x56:
  6797. case 0x57:
  6798. case 0x58:
  6799. case 0x59:
  6800. case 0x5A:
  6801. case 0x5B:
  6802. case 0x5D:
  6803. case 0x5E:
  6804. case 0x5F:
  6805. case 0x60:
  6806. case 0x61:
  6807. case 0x62:
  6808. case 0x63:
  6809. case 0x64:
  6810. case 0x65:
  6811. case 0x66:
  6812. case 0x67:
  6813. case 0x68:
  6814. case 0x69:
  6815. case 0x6A:
  6816. case 0x6B:
  6817. case 0x6C:
  6818. case 0x6D:
  6819. case 0x6E:
  6820. case 0x6F:
  6821. case 0x70:
  6822. case 0x71:
  6823. case 0x72:
  6824. case 0x73:
  6825. case 0x74:
  6826. case 0x75:
  6827. case 0x76:
  6828. case 0x77:
  6829. case 0x78:
  6830. case 0x79:
  6831. case 0x7A:
  6832. case 0x7B:
  6833. case 0x7C:
  6834. case 0x7D:
  6835. case 0x7E:
  6836. case 0x7F:
  6837. {
  6838. add(current);
  6839. break;
  6840. }
  6841. // U+0080..U+07FF: bytes C2..DF 80..BF
  6842. case 0xC2:
  6843. case 0xC3:
  6844. case 0xC4:
  6845. case 0xC5:
  6846. case 0xC6:
  6847. case 0xC7:
  6848. case 0xC8:
  6849. case 0xC9:
  6850. case 0xCA:
  6851. case 0xCB:
  6852. case 0xCC:
  6853. case 0xCD:
  6854. case 0xCE:
  6855. case 0xCF:
  6856. case 0xD0:
  6857. case 0xD1:
  6858. case 0xD2:
  6859. case 0xD3:
  6860. case 0xD4:
  6861. case 0xD5:
  6862. case 0xD6:
  6863. case 0xD7:
  6864. case 0xD8:
  6865. case 0xD9:
  6866. case 0xDA:
  6867. case 0xDB:
  6868. case 0xDC:
  6869. case 0xDD:
  6870. case 0xDE:
  6871. case 0xDF:
  6872. {
  6873. if (JSON_HEDLEY_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  6874. {
  6875. return token_type::parse_error;
  6876. }
  6877. break;
  6878. }
  6879. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  6880. case 0xE0:
  6881. {
  6882. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  6883. {
  6884. return token_type::parse_error;
  6885. }
  6886. break;
  6887. }
  6888. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  6889. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  6890. case 0xE1:
  6891. case 0xE2:
  6892. case 0xE3:
  6893. case 0xE4:
  6894. case 0xE5:
  6895. case 0xE6:
  6896. case 0xE7:
  6897. case 0xE8:
  6898. case 0xE9:
  6899. case 0xEA:
  6900. case 0xEB:
  6901. case 0xEC:
  6902. case 0xEE:
  6903. case 0xEF:
  6904. {
  6905. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  6906. {
  6907. return token_type::parse_error;
  6908. }
  6909. break;
  6910. }
  6911. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  6912. case 0xED:
  6913. {
  6914. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  6915. {
  6916. return token_type::parse_error;
  6917. }
  6918. break;
  6919. }
  6920. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  6921. case 0xF0:
  6922. {
  6923. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6924. {
  6925. return token_type::parse_error;
  6926. }
  6927. break;
  6928. }
  6929. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  6930. case 0xF1:
  6931. case 0xF2:
  6932. case 0xF3:
  6933. {
  6934. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  6935. {
  6936. return token_type::parse_error;
  6937. }
  6938. break;
  6939. }
  6940. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  6941. case 0xF4:
  6942. {
  6943. if (JSON_HEDLEY_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  6944. {
  6945. return token_type::parse_error;
  6946. }
  6947. break;
  6948. }
  6949. // remaining bytes (80..C1 and F5..FF) are ill-formed
  6950. default:
  6951. {
  6952. error_message = "invalid string: ill-formed UTF-8 byte";
  6953. return token_type::parse_error;
  6954. }
  6955. }
  6956. }
  6957. }
  6958. JSON_HEDLEY_NON_NULL(2)
  6959. static void strtof(float& f, const char* str, char** endptr) noexcept
  6960. {
  6961. f = std::strtof(str, endptr);
  6962. }
  6963. JSON_HEDLEY_NON_NULL(2)
  6964. static void strtof(double& f, const char* str, char** endptr) noexcept
  6965. {
  6966. f = std::strtod(str, endptr);
  6967. }
  6968. JSON_HEDLEY_NON_NULL(2)
  6969. static void strtof(long double& f, const char* str, char** endptr) noexcept
  6970. {
  6971. f = std::strtold(str, endptr);
  6972. }
  6973. /*!
  6974. @brief scan a number literal
  6975. This function scans a string according to Sect. 6 of RFC 7159.
  6976. The function is realized with a deterministic finite state machine derived
  6977. from the grammar described in RFC 7159. Starting in state "init", the
  6978. input is read and used to determined the next state. Only state "done"
  6979. accepts the number. State "error" is a trap state to model errors. In the
  6980. table below, "anything" means any character but the ones listed before.
  6981. state | 0 | 1-9 | e E | + | - | . | anything
  6982. ---------|----------|----------|----------|---------|---------|----------|-----------
  6983. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  6984. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  6985. zero | done | done | exponent | done | done | decimal1 | done
  6986. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  6987. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  6988. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  6989. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  6990. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  6991. any2 | any2 | any2 | done | done | done | done | done
  6992. The state machine is realized with one label per state (prefixed with
  6993. "scan_number_") and `goto` statements between them. The state machine
  6994. contains cycles, but any cycle can be left when EOF is read. Therefore,
  6995. the function is guaranteed to terminate.
  6996. During scanning, the read bytes are stored in token_buffer. This string is
  6997. then converted to a signed integer, an unsigned integer, or a
  6998. floating-point number.
  6999. @return token_type::value_unsigned, token_type::value_integer, or
  7000. token_type::value_float if number could be successfully scanned,
  7001. token_type::parse_error otherwise
  7002. @note The scanner is independent of the current locale. Internally, the
  7003. locale's decimal point is used instead of `.` to work with the
  7004. locale-dependent converters.
  7005. */
  7006. token_type scan_number() // lgtm [cpp/use-of-goto]
  7007. {
  7008. // reset token_buffer to store the number's bytes
  7009. reset();
  7010. // the type of the parsed number; initially set to unsigned; will be
  7011. // changed if minus sign, decimal point or exponent is read
  7012. token_type number_type = token_type::value_unsigned;
  7013. // state (init): we just found out we need to scan a number
  7014. switch (current)
  7015. {
  7016. case '-':
  7017. {
  7018. add(current);
  7019. goto scan_number_minus;
  7020. }
  7021. case '0':
  7022. {
  7023. add(current);
  7024. goto scan_number_zero;
  7025. }
  7026. case '1':
  7027. case '2':
  7028. case '3':
  7029. case '4':
  7030. case '5':
  7031. case '6':
  7032. case '7':
  7033. case '8':
  7034. case '9':
  7035. {
  7036. add(current);
  7037. goto scan_number_any1;
  7038. }
  7039. // all other characters are rejected outside scan_number()
  7040. default: // LCOV_EXCL_LINE
  7041. assert(false); // LCOV_EXCL_LINE
  7042. }
  7043. scan_number_minus:
  7044. // state: we just parsed a leading minus sign
  7045. number_type = token_type::value_integer;
  7046. switch (get())
  7047. {
  7048. case '0':
  7049. {
  7050. add(current);
  7051. goto scan_number_zero;
  7052. }
  7053. case '1':
  7054. case '2':
  7055. case '3':
  7056. case '4':
  7057. case '5':
  7058. case '6':
  7059. case '7':
  7060. case '8':
  7061. case '9':
  7062. {
  7063. add(current);
  7064. goto scan_number_any1;
  7065. }
  7066. default:
  7067. {
  7068. error_message = "invalid number; expected digit after '-'";
  7069. return token_type::parse_error;
  7070. }
  7071. }
  7072. scan_number_zero:
  7073. // state: we just parse a zero (maybe with a leading minus sign)
  7074. switch (get())
  7075. {
  7076. case '.':
  7077. {
  7078. add(decimal_point_char);
  7079. goto scan_number_decimal1;
  7080. }
  7081. case 'e':
  7082. case 'E':
  7083. {
  7084. add(current);
  7085. goto scan_number_exponent;
  7086. }
  7087. default:
  7088. goto scan_number_done;
  7089. }
  7090. scan_number_any1:
  7091. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  7092. switch (get())
  7093. {
  7094. case '0':
  7095. case '1':
  7096. case '2':
  7097. case '3':
  7098. case '4':
  7099. case '5':
  7100. case '6':
  7101. case '7':
  7102. case '8':
  7103. case '9':
  7104. {
  7105. add(current);
  7106. goto scan_number_any1;
  7107. }
  7108. case '.':
  7109. {
  7110. add(decimal_point_char);
  7111. goto scan_number_decimal1;
  7112. }
  7113. case 'e':
  7114. case 'E':
  7115. {
  7116. add(current);
  7117. goto scan_number_exponent;
  7118. }
  7119. default:
  7120. goto scan_number_done;
  7121. }
  7122. scan_number_decimal1:
  7123. // state: we just parsed a decimal point
  7124. number_type = token_type::value_float;
  7125. switch (get())
  7126. {
  7127. case '0':
  7128. case '1':
  7129. case '2':
  7130. case '3':
  7131. case '4':
  7132. case '5':
  7133. case '6':
  7134. case '7':
  7135. case '8':
  7136. case '9':
  7137. {
  7138. add(current);
  7139. goto scan_number_decimal2;
  7140. }
  7141. default:
  7142. {
  7143. error_message = "invalid number; expected digit after '.'";
  7144. return token_type::parse_error;
  7145. }
  7146. }
  7147. scan_number_decimal2:
  7148. // we just parsed at least one number after a decimal point
  7149. switch (get())
  7150. {
  7151. case '0':
  7152. case '1':
  7153. case '2':
  7154. case '3':
  7155. case '4':
  7156. case '5':
  7157. case '6':
  7158. case '7':
  7159. case '8':
  7160. case '9':
  7161. {
  7162. add(current);
  7163. goto scan_number_decimal2;
  7164. }
  7165. case 'e':
  7166. case 'E':
  7167. {
  7168. add(current);
  7169. goto scan_number_exponent;
  7170. }
  7171. default:
  7172. goto scan_number_done;
  7173. }
  7174. scan_number_exponent:
  7175. // we just parsed an exponent
  7176. number_type = token_type::value_float;
  7177. switch (get())
  7178. {
  7179. case '+':
  7180. case '-':
  7181. {
  7182. add(current);
  7183. goto scan_number_sign;
  7184. }
  7185. case '0':
  7186. case '1':
  7187. case '2':
  7188. case '3':
  7189. case '4':
  7190. case '5':
  7191. case '6':
  7192. case '7':
  7193. case '8':
  7194. case '9':
  7195. {
  7196. add(current);
  7197. goto scan_number_any2;
  7198. }
  7199. default:
  7200. {
  7201. error_message =
  7202. "invalid number; expected '+', '-', or digit after exponent";
  7203. return token_type::parse_error;
  7204. }
  7205. }
  7206. scan_number_sign:
  7207. // we just parsed an exponent sign
  7208. switch (get())
  7209. {
  7210. case '0':
  7211. case '1':
  7212. case '2':
  7213. case '3':
  7214. case '4':
  7215. case '5':
  7216. case '6':
  7217. case '7':
  7218. case '8':
  7219. case '9':
  7220. {
  7221. add(current);
  7222. goto scan_number_any2;
  7223. }
  7224. default:
  7225. {
  7226. error_message = "invalid number; expected digit after exponent sign";
  7227. return token_type::parse_error;
  7228. }
  7229. }
  7230. scan_number_any2:
  7231. // we just parsed a number after the exponent or exponent sign
  7232. switch (get())
  7233. {
  7234. case '0':
  7235. case '1':
  7236. case '2':
  7237. case '3':
  7238. case '4':
  7239. case '5':
  7240. case '6':
  7241. case '7':
  7242. case '8':
  7243. case '9':
  7244. {
  7245. add(current);
  7246. goto scan_number_any2;
  7247. }
  7248. default:
  7249. goto scan_number_done;
  7250. }
  7251. scan_number_done:
  7252. // unget the character after the number (we only read it to know that
  7253. // we are done scanning a number)
  7254. unget();
  7255. char* endptr = nullptr;
  7256. errno = 0;
  7257. // try to parse integers first and fall back to floats
  7258. if (number_type == token_type::value_unsigned)
  7259. {
  7260. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  7261. // we checked the number format before
  7262. assert(endptr == token_buffer.data() + token_buffer.size());
  7263. if (errno == 0)
  7264. {
  7265. value_unsigned = static_cast<number_unsigned_t>(x);
  7266. if (value_unsigned == x)
  7267. {
  7268. return token_type::value_unsigned;
  7269. }
  7270. }
  7271. }
  7272. else if (number_type == token_type::value_integer)
  7273. {
  7274. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  7275. // we checked the number format before
  7276. assert(endptr == token_buffer.data() + token_buffer.size());
  7277. if (errno == 0)
  7278. {
  7279. value_integer = static_cast<number_integer_t>(x);
  7280. if (value_integer == x)
  7281. {
  7282. return token_type::value_integer;
  7283. }
  7284. }
  7285. }
  7286. // this code is reached if we parse a floating-point number or if an
  7287. // integer conversion above failed
  7288. strtof(value_float, token_buffer.data(), &endptr);
  7289. // we checked the number format before
  7290. assert(endptr == token_buffer.data() + token_buffer.size());
  7291. return token_type::value_float;
  7292. }
  7293. /*!
  7294. @param[in] literal_text the literal text to expect
  7295. @param[in] length the length of the passed literal text
  7296. @param[in] return_type the token type to return on success
  7297. */
  7298. JSON_HEDLEY_NON_NULL(2)
  7299. token_type scan_literal(const char* literal_text, const std::size_t length,
  7300. token_type return_type)
  7301. {
  7302. assert(current == literal_text[0]);
  7303. for (std::size_t i = 1; i < length; ++i)
  7304. {
  7305. if (JSON_HEDLEY_UNLIKELY(get() != literal_text[i]))
  7306. {
  7307. error_message = "invalid literal";
  7308. return token_type::parse_error;
  7309. }
  7310. }
  7311. return return_type;
  7312. }
  7313. /////////////////////
  7314. // input management
  7315. /////////////////////
  7316. /// reset token_buffer; current character is beginning of token
  7317. void reset() noexcept
  7318. {
  7319. token_buffer.clear();
  7320. token_string.clear();
  7321. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7322. }
  7323. /*
  7324. @brief get next character from the input
  7325. This function provides the interface to the used input adapter. It does
  7326. not throw in case the input reached EOF, but returns a
  7327. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  7328. for use in error messages.
  7329. @return character read from the input
  7330. */
  7331. std::char_traits<char>::int_type get()
  7332. {
  7333. ++position.chars_read_total;
  7334. ++position.chars_read_current_line;
  7335. if (next_unget)
  7336. {
  7337. // just reset the next_unget variable and work with current
  7338. next_unget = false;
  7339. }
  7340. else
  7341. {
  7342. current = ia->get_character();
  7343. }
  7344. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7345. {
  7346. token_string.push_back(std::char_traits<char>::to_char_type(current));
  7347. }
  7348. if (current == '\n')
  7349. {
  7350. ++position.lines_read;
  7351. position.chars_read_current_line = 0;
  7352. }
  7353. return current;
  7354. }
  7355. /*!
  7356. @brief unget current character (read it again on next get)
  7357. We implement unget by setting variable next_unget to true. The input is not
  7358. changed - we just simulate ungetting by modifying chars_read_total,
  7359. chars_read_current_line, and token_string. The next call to get() will
  7360. behave as if the unget character is read again.
  7361. */
  7362. void unget()
  7363. {
  7364. next_unget = true;
  7365. --position.chars_read_total;
  7366. // in case we "unget" a newline, we have to also decrement the lines_read
  7367. if (position.chars_read_current_line == 0)
  7368. {
  7369. if (position.lines_read > 0)
  7370. {
  7371. --position.lines_read;
  7372. }
  7373. }
  7374. else
  7375. {
  7376. --position.chars_read_current_line;
  7377. }
  7378. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char>::eof()))
  7379. {
  7380. assert(not token_string.empty());
  7381. token_string.pop_back();
  7382. }
  7383. }
  7384. /// add a character to token_buffer
  7385. void add(int c)
  7386. {
  7387. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  7388. }
  7389. public:
  7390. /////////////////////
  7391. // value getters
  7392. /////////////////////
  7393. /// return integer value
  7394. constexpr number_integer_t get_number_integer() const noexcept
  7395. {
  7396. return value_integer;
  7397. }
  7398. /// return unsigned integer value
  7399. constexpr number_unsigned_t get_number_unsigned() const noexcept
  7400. {
  7401. return value_unsigned;
  7402. }
  7403. /// return floating-point value
  7404. constexpr number_float_t get_number_float() const noexcept
  7405. {
  7406. return value_float;
  7407. }
  7408. /// return current string value (implicitly resets the token; useful only once)
  7409. string_t& get_string()
  7410. {
  7411. return token_buffer;
  7412. }
  7413. /////////////////////
  7414. // diagnostics
  7415. /////////////////////
  7416. /// return position of last read token
  7417. constexpr position_t get_position() const noexcept
  7418. {
  7419. return position;
  7420. }
  7421. /// return the last read token (for errors only). Will never contain EOF
  7422. /// (an arbitrary value that is not a valid char value, often -1), because
  7423. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  7424. std::string get_token_string() const
  7425. {
  7426. // escape control characters
  7427. std::string result;
  7428. for (const auto c : token_string)
  7429. {
  7430. if ('\x00' <= c and c <= '\x1F')
  7431. {
  7432. // escape control characters
  7433. std::array<char, 9> cs{{}};
  7434. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  7435. result += cs.data();
  7436. }
  7437. else
  7438. {
  7439. // add character as is
  7440. result.push_back(c);
  7441. }
  7442. }
  7443. return result;
  7444. }
  7445. /// return syntax error message
  7446. JSON_HEDLEY_RETURNS_NON_NULL
  7447. constexpr const char* get_error_message() const noexcept
  7448. {
  7449. return error_message;
  7450. }
  7451. /////////////////////
  7452. // actual scanner
  7453. /////////////////////
  7454. /*!
  7455. @brief skip the UTF-8 byte order mark
  7456. @return true iff there is no BOM or the correct BOM has been skipped
  7457. */
  7458. bool skip_bom()
  7459. {
  7460. if (get() == 0xEF)
  7461. {
  7462. // check if we completely parse the BOM
  7463. return get() == 0xBB and get() == 0xBF;
  7464. }
  7465. // the first character is not the beginning of the BOM; unget it to
  7466. // process is later
  7467. unget();
  7468. return true;
  7469. }
  7470. token_type scan()
  7471. {
  7472. // initially, skip the BOM
  7473. if (position.chars_read_total == 0 and not skip_bom())
  7474. {
  7475. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  7476. return token_type::parse_error;
  7477. }
  7478. // read next character and ignore whitespace
  7479. do
  7480. {
  7481. get();
  7482. }
  7483. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  7484. switch (current)
  7485. {
  7486. // structural characters
  7487. case '[':
  7488. return token_type::begin_array;
  7489. case ']':
  7490. return token_type::end_array;
  7491. case '{':
  7492. return token_type::begin_object;
  7493. case '}':
  7494. return token_type::end_object;
  7495. case ':':
  7496. return token_type::name_separator;
  7497. case ',':
  7498. return token_type::value_separator;
  7499. // literals
  7500. case 't':
  7501. return scan_literal("true", 4, token_type::literal_true);
  7502. case 'f':
  7503. return scan_literal("false", 5, token_type::literal_false);
  7504. case 'n':
  7505. return scan_literal("null", 4, token_type::literal_null);
  7506. // string
  7507. case '\"':
  7508. return scan_string();
  7509. // number
  7510. case '-':
  7511. case '0':
  7512. case '1':
  7513. case '2':
  7514. case '3':
  7515. case '4':
  7516. case '5':
  7517. case '6':
  7518. case '7':
  7519. case '8':
  7520. case '9':
  7521. return scan_number();
  7522. // end of input (the null byte is needed when parsing from
  7523. // string literals)
  7524. case '\0':
  7525. case std::char_traits<char>::eof():
  7526. return token_type::end_of_input;
  7527. // error
  7528. default:
  7529. error_message = "invalid literal";
  7530. return token_type::parse_error;
  7531. }
  7532. }
  7533. private:
  7534. /// input adapter
  7535. detail::input_adapter_t ia = nullptr;
  7536. /// the current character
  7537. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  7538. /// whether the next get() call should just return current
  7539. bool next_unget = false;
  7540. /// the start position of the current token
  7541. position_t position {};
  7542. /// raw input token string (for error messages)
  7543. std::vector<char> token_string {};
  7544. /// buffer for variable-length tokens (numbers, strings)
  7545. string_t token_buffer {};
  7546. /// a description of occurred lexer errors
  7547. const char* error_message = "";
  7548. // number values
  7549. number_integer_t value_integer = 0;
  7550. number_unsigned_t value_unsigned = 0;
  7551. number_float_t value_float = 0;
  7552. /// the decimal point
  7553. const char decimal_point_char = '.';
  7554. };
  7555. } // namespace detail
  7556. } // namespace nlohmann
  7557. // #include <nlohmann/detail/input/parser.hpp>
  7558. #include <cassert> // assert
  7559. #include <cmath> // isfinite
  7560. #include <cstdint> // uint8_t
  7561. #include <functional> // function
  7562. #include <string> // string
  7563. #include <utility> // move
  7564. #include <vector> // vector
  7565. // #include <nlohmann/detail/exceptions.hpp>
  7566. // #include <nlohmann/detail/input/input_adapters.hpp>
  7567. // #include <nlohmann/detail/input/json_sax.hpp>
  7568. // #include <nlohmann/detail/input/lexer.hpp>
  7569. // #include <nlohmann/detail/macro_scope.hpp>
  7570. // #include <nlohmann/detail/meta/is_sax.hpp>
  7571. // #include <nlohmann/detail/value_t.hpp>
  7572. namespace nlohmann
  7573. {
  7574. namespace detail
  7575. {
  7576. ////////////
  7577. // parser //
  7578. ////////////
  7579. /*!
  7580. @brief syntax analysis
  7581. This class implements a recursive decent parser.
  7582. */
  7583. template<typename BasicJsonType>
  7584. class parser
  7585. {
  7586. using number_integer_t = typename BasicJsonType::number_integer_t;
  7587. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7588. using number_float_t = typename BasicJsonType::number_float_t;
  7589. using string_t = typename BasicJsonType::string_t;
  7590. using lexer_t = lexer<BasicJsonType>;
  7591. using token_type = typename lexer_t::token_type;
  7592. public:
  7593. enum class parse_event_t : uint8_t
  7594. {
  7595. /// the parser read `{` and started to process a JSON object
  7596. object_start,
  7597. /// the parser read `}` and finished processing a JSON object
  7598. object_end,
  7599. /// the parser read `[` and started to process a JSON array
  7600. array_start,
  7601. /// the parser read `]` and finished processing a JSON array
  7602. array_end,
  7603. /// the parser read a key of a value in an object
  7604. key,
  7605. /// the parser finished reading a JSON value
  7606. value
  7607. };
  7608. using parser_callback_t =
  7609. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  7610. /// a parser reading from an input adapter
  7611. explicit parser(detail::input_adapter_t&& adapter,
  7612. const parser_callback_t cb = nullptr,
  7613. const bool allow_exceptions_ = true)
  7614. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  7615. {
  7616. // read first token
  7617. get_token();
  7618. }
  7619. /*!
  7620. @brief public parser interface
  7621. @param[in] strict whether to expect the last token to be EOF
  7622. @param[in,out] result parsed JSON value
  7623. @throw parse_error.101 in case of an unexpected token
  7624. @throw parse_error.102 if to_unicode fails or surrogate error
  7625. @throw parse_error.103 if to_unicode fails
  7626. */
  7627. void parse(const bool strict, BasicJsonType& result)
  7628. {
  7629. if (callback)
  7630. {
  7631. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  7632. sax_parse_internal(&sdp);
  7633. result.assert_invariant();
  7634. // in strict mode, input must be completely read
  7635. if (strict and (get_token() != token_type::end_of_input))
  7636. {
  7637. sdp.parse_error(m_lexer.get_position(),
  7638. m_lexer.get_token_string(),
  7639. parse_error::create(101, m_lexer.get_position(),
  7640. exception_message(token_type::end_of_input, "value")));
  7641. }
  7642. // in case of an error, return discarded value
  7643. if (sdp.is_errored())
  7644. {
  7645. result = value_t::discarded;
  7646. return;
  7647. }
  7648. // set top-level value to null if it was discarded by the callback
  7649. // function
  7650. if (result.is_discarded())
  7651. {
  7652. result = nullptr;
  7653. }
  7654. }
  7655. else
  7656. {
  7657. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  7658. sax_parse_internal(&sdp);
  7659. result.assert_invariant();
  7660. // in strict mode, input must be completely read
  7661. if (strict and (get_token() != token_type::end_of_input))
  7662. {
  7663. sdp.parse_error(m_lexer.get_position(),
  7664. m_lexer.get_token_string(),
  7665. parse_error::create(101, m_lexer.get_position(),
  7666. exception_message(token_type::end_of_input, "value")));
  7667. }
  7668. // in case of an error, return discarded value
  7669. if (sdp.is_errored())
  7670. {
  7671. result = value_t::discarded;
  7672. return;
  7673. }
  7674. }
  7675. }
  7676. /*!
  7677. @brief public accept interface
  7678. @param[in] strict whether to expect the last token to be EOF
  7679. @return whether the input is a proper JSON text
  7680. */
  7681. bool accept(const bool strict = true)
  7682. {
  7683. json_sax_acceptor<BasicJsonType> sax_acceptor;
  7684. return sax_parse(&sax_acceptor, strict);
  7685. }
  7686. template <typename SAX>
  7687. JSON_HEDLEY_NON_NULL(2)
  7688. bool sax_parse(SAX* sax, const bool strict = true)
  7689. {
  7690. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  7691. const bool result = sax_parse_internal(sax);
  7692. // strict mode: next byte must be EOF
  7693. if (result and strict and (get_token() != token_type::end_of_input))
  7694. {
  7695. return sax->parse_error(m_lexer.get_position(),
  7696. m_lexer.get_token_string(),
  7697. parse_error::create(101, m_lexer.get_position(),
  7698. exception_message(token_type::end_of_input, "value")));
  7699. }
  7700. return result;
  7701. }
  7702. private:
  7703. template <typename SAX>
  7704. JSON_HEDLEY_NON_NULL(2)
  7705. bool sax_parse_internal(SAX* sax)
  7706. {
  7707. // stack to remember the hierarchy of structured values we are parsing
  7708. // true = array; false = object
  7709. std::vector<bool> states;
  7710. // value to avoid a goto (see comment where set to true)
  7711. bool skip_to_state_evaluation = false;
  7712. while (true)
  7713. {
  7714. if (not skip_to_state_evaluation)
  7715. {
  7716. // invariant: get_token() was called before each iteration
  7717. switch (last_token)
  7718. {
  7719. case token_type::begin_object:
  7720. {
  7721. if (JSON_HEDLEY_UNLIKELY(not sax->start_object(std::size_t(-1))))
  7722. {
  7723. return false;
  7724. }
  7725. // closing } -> we are done
  7726. if (get_token() == token_type::end_object)
  7727. {
  7728. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7729. {
  7730. return false;
  7731. }
  7732. break;
  7733. }
  7734. // parse key
  7735. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  7736. {
  7737. return sax->parse_error(m_lexer.get_position(),
  7738. m_lexer.get_token_string(),
  7739. parse_error::create(101, m_lexer.get_position(),
  7740. exception_message(token_type::value_string, "object key")));
  7741. }
  7742. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7743. {
  7744. return false;
  7745. }
  7746. // parse separator (:)
  7747. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7748. {
  7749. return sax->parse_error(m_lexer.get_position(),
  7750. m_lexer.get_token_string(),
  7751. parse_error::create(101, m_lexer.get_position(),
  7752. exception_message(token_type::name_separator, "object separator")));
  7753. }
  7754. // remember we are now inside an object
  7755. states.push_back(false);
  7756. // parse values
  7757. get_token();
  7758. continue;
  7759. }
  7760. case token_type::begin_array:
  7761. {
  7762. if (JSON_HEDLEY_UNLIKELY(not sax->start_array(std::size_t(-1))))
  7763. {
  7764. return false;
  7765. }
  7766. // closing ] -> we are done
  7767. if (get_token() == token_type::end_array)
  7768. {
  7769. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7770. {
  7771. return false;
  7772. }
  7773. break;
  7774. }
  7775. // remember we are now inside an array
  7776. states.push_back(true);
  7777. // parse values (no need to call get_token)
  7778. continue;
  7779. }
  7780. case token_type::value_float:
  7781. {
  7782. const auto res = m_lexer.get_number_float();
  7783. if (JSON_HEDLEY_UNLIKELY(not std::isfinite(res)))
  7784. {
  7785. return sax->parse_error(m_lexer.get_position(),
  7786. m_lexer.get_token_string(),
  7787. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  7788. }
  7789. if (JSON_HEDLEY_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  7790. {
  7791. return false;
  7792. }
  7793. break;
  7794. }
  7795. case token_type::literal_false:
  7796. {
  7797. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(false)))
  7798. {
  7799. return false;
  7800. }
  7801. break;
  7802. }
  7803. case token_type::literal_null:
  7804. {
  7805. if (JSON_HEDLEY_UNLIKELY(not sax->null()))
  7806. {
  7807. return false;
  7808. }
  7809. break;
  7810. }
  7811. case token_type::literal_true:
  7812. {
  7813. if (JSON_HEDLEY_UNLIKELY(not sax->boolean(true)))
  7814. {
  7815. return false;
  7816. }
  7817. break;
  7818. }
  7819. case token_type::value_integer:
  7820. {
  7821. if (JSON_HEDLEY_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  7822. {
  7823. return false;
  7824. }
  7825. break;
  7826. }
  7827. case token_type::value_string:
  7828. {
  7829. if (JSON_HEDLEY_UNLIKELY(not sax->string(m_lexer.get_string())))
  7830. {
  7831. return false;
  7832. }
  7833. break;
  7834. }
  7835. case token_type::value_unsigned:
  7836. {
  7837. if (JSON_HEDLEY_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  7838. {
  7839. return false;
  7840. }
  7841. break;
  7842. }
  7843. case token_type::parse_error:
  7844. {
  7845. // using "uninitialized" to avoid "expected" message
  7846. return sax->parse_error(m_lexer.get_position(),
  7847. m_lexer.get_token_string(),
  7848. parse_error::create(101, m_lexer.get_position(),
  7849. exception_message(token_type::uninitialized, "value")));
  7850. }
  7851. default: // the last token was unexpected
  7852. {
  7853. return sax->parse_error(m_lexer.get_position(),
  7854. m_lexer.get_token_string(),
  7855. parse_error::create(101, m_lexer.get_position(),
  7856. exception_message(token_type::literal_or_value, "value")));
  7857. }
  7858. }
  7859. }
  7860. else
  7861. {
  7862. skip_to_state_evaluation = false;
  7863. }
  7864. // we reached this line after we successfully parsed a value
  7865. if (states.empty())
  7866. {
  7867. // empty stack: we reached the end of the hierarchy: done
  7868. return true;
  7869. }
  7870. if (states.back()) // array
  7871. {
  7872. // comma -> next value
  7873. if (get_token() == token_type::value_separator)
  7874. {
  7875. // parse a new value
  7876. get_token();
  7877. continue;
  7878. }
  7879. // closing ]
  7880. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  7881. {
  7882. if (JSON_HEDLEY_UNLIKELY(not sax->end_array()))
  7883. {
  7884. return false;
  7885. }
  7886. // We are done with this array. Before we can parse a
  7887. // new value, we need to evaluate the new state first.
  7888. // By setting skip_to_state_evaluation to false, we
  7889. // are effectively jumping to the beginning of this if.
  7890. assert(not states.empty());
  7891. states.pop_back();
  7892. skip_to_state_evaluation = true;
  7893. continue;
  7894. }
  7895. return sax->parse_error(m_lexer.get_position(),
  7896. m_lexer.get_token_string(),
  7897. parse_error::create(101, m_lexer.get_position(),
  7898. exception_message(token_type::end_array, "array")));
  7899. }
  7900. else // object
  7901. {
  7902. // comma -> next value
  7903. if (get_token() == token_type::value_separator)
  7904. {
  7905. // parse key
  7906. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  7907. {
  7908. return sax->parse_error(m_lexer.get_position(),
  7909. m_lexer.get_token_string(),
  7910. parse_error::create(101, m_lexer.get_position(),
  7911. exception_message(token_type::value_string, "object key")));
  7912. }
  7913. if (JSON_HEDLEY_UNLIKELY(not sax->key(m_lexer.get_string())))
  7914. {
  7915. return false;
  7916. }
  7917. // parse separator (:)
  7918. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  7919. {
  7920. return sax->parse_error(m_lexer.get_position(),
  7921. m_lexer.get_token_string(),
  7922. parse_error::create(101, m_lexer.get_position(),
  7923. exception_message(token_type::name_separator, "object separator")));
  7924. }
  7925. // parse values
  7926. get_token();
  7927. continue;
  7928. }
  7929. // closing }
  7930. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  7931. {
  7932. if (JSON_HEDLEY_UNLIKELY(not sax->end_object()))
  7933. {
  7934. return false;
  7935. }
  7936. // We are done with this object. Before we can parse a
  7937. // new value, we need to evaluate the new state first.
  7938. // By setting skip_to_state_evaluation to false, we
  7939. // are effectively jumping to the beginning of this if.
  7940. assert(not states.empty());
  7941. states.pop_back();
  7942. skip_to_state_evaluation = true;
  7943. continue;
  7944. }
  7945. return sax->parse_error(m_lexer.get_position(),
  7946. m_lexer.get_token_string(),
  7947. parse_error::create(101, m_lexer.get_position(),
  7948. exception_message(token_type::end_object, "object")));
  7949. }
  7950. }
  7951. }
  7952. /// get next token from lexer
  7953. token_type get_token()
  7954. {
  7955. return last_token = m_lexer.scan();
  7956. }
  7957. std::string exception_message(const token_type expected, const std::string& context)
  7958. {
  7959. std::string error_msg = "syntax error ";
  7960. if (not context.empty())
  7961. {
  7962. error_msg += "while parsing " + context + " ";
  7963. }
  7964. error_msg += "- ";
  7965. if (last_token == token_type::parse_error)
  7966. {
  7967. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  7968. m_lexer.get_token_string() + "'";
  7969. }
  7970. else
  7971. {
  7972. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  7973. }
  7974. if (expected != token_type::uninitialized)
  7975. {
  7976. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  7977. }
  7978. return error_msg;
  7979. }
  7980. private:
  7981. /// callback function
  7982. const parser_callback_t callback = nullptr;
  7983. /// the type of the last read token
  7984. token_type last_token = token_type::uninitialized;
  7985. /// the lexer
  7986. lexer_t m_lexer;
  7987. /// whether to throw exceptions in case of errors
  7988. const bool allow_exceptions = true;
  7989. };
  7990. } // namespace detail
  7991. } // namespace nlohmann
  7992. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  7993. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7994. #include <cstddef> // ptrdiff_t
  7995. #include <limits> // numeric_limits
  7996. namespace nlohmann
  7997. {
  7998. namespace detail
  7999. {
  8000. /*
  8001. @brief an iterator for primitive JSON types
  8002. This class models an iterator for primitive JSON types (boolean, number,
  8003. string). It's only purpose is to allow the iterator/const_iterator classes
  8004. to "iterate" over primitive values. Internally, the iterator is modeled by
  8005. a `difference_type` variable. Value begin_value (`0`) models the begin,
  8006. end_value (`1`) models past the end.
  8007. */
  8008. class primitive_iterator_t
  8009. {
  8010. private:
  8011. using difference_type = std::ptrdiff_t;
  8012. static constexpr difference_type begin_value = 0;
  8013. static constexpr difference_type end_value = begin_value + 1;
  8014. /// iterator as signed integer type
  8015. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8016. public:
  8017. constexpr difference_type get_value() const noexcept
  8018. {
  8019. return m_it;
  8020. }
  8021. /// set iterator to a defined beginning
  8022. void set_begin() noexcept
  8023. {
  8024. m_it = begin_value;
  8025. }
  8026. /// set iterator to a defined past the end
  8027. void set_end() noexcept
  8028. {
  8029. m_it = end_value;
  8030. }
  8031. /// return whether the iterator can be dereferenced
  8032. constexpr bool is_begin() const noexcept
  8033. {
  8034. return m_it == begin_value;
  8035. }
  8036. /// return whether the iterator is at end
  8037. constexpr bool is_end() const noexcept
  8038. {
  8039. return m_it == end_value;
  8040. }
  8041. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8042. {
  8043. return lhs.m_it == rhs.m_it;
  8044. }
  8045. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8046. {
  8047. return lhs.m_it < rhs.m_it;
  8048. }
  8049. primitive_iterator_t operator+(difference_type n) noexcept
  8050. {
  8051. auto result = *this;
  8052. result += n;
  8053. return result;
  8054. }
  8055. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8056. {
  8057. return lhs.m_it - rhs.m_it;
  8058. }
  8059. primitive_iterator_t& operator++() noexcept
  8060. {
  8061. ++m_it;
  8062. return *this;
  8063. }
  8064. primitive_iterator_t const operator++(int) noexcept
  8065. {
  8066. auto result = *this;
  8067. ++m_it;
  8068. return result;
  8069. }
  8070. primitive_iterator_t& operator--() noexcept
  8071. {
  8072. --m_it;
  8073. return *this;
  8074. }
  8075. primitive_iterator_t const operator--(int) noexcept
  8076. {
  8077. auto result = *this;
  8078. --m_it;
  8079. return result;
  8080. }
  8081. primitive_iterator_t& operator+=(difference_type n) noexcept
  8082. {
  8083. m_it += n;
  8084. return *this;
  8085. }
  8086. primitive_iterator_t& operator-=(difference_type n) noexcept
  8087. {
  8088. m_it -= n;
  8089. return *this;
  8090. }
  8091. };
  8092. } // namespace detail
  8093. } // namespace nlohmann
  8094. namespace nlohmann
  8095. {
  8096. namespace detail
  8097. {
  8098. /*!
  8099. @brief an iterator value
  8100. @note This structure could easily be a union, but MSVC currently does not allow
  8101. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  8102. */
  8103. template<typename BasicJsonType> struct internal_iterator
  8104. {
  8105. /// iterator for JSON objects
  8106. typename BasicJsonType::object_t::iterator object_iterator {};
  8107. /// iterator for JSON arrays
  8108. typename BasicJsonType::array_t::iterator array_iterator {};
  8109. /// generic iterator for all other types
  8110. primitive_iterator_t primitive_iterator {};
  8111. };
  8112. } // namespace detail
  8113. } // namespace nlohmann
  8114. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  8115. #include <ciso646> // not
  8116. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  8117. #include <type_traits> // conditional, is_const, remove_const
  8118. // #include <nlohmann/detail/exceptions.hpp>
  8119. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8120. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8121. // #include <nlohmann/detail/macro_scope.hpp>
  8122. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8123. // #include <nlohmann/detail/meta/type_traits.hpp>
  8124. // #include <nlohmann/detail/value_t.hpp>
  8125. namespace nlohmann
  8126. {
  8127. namespace detail
  8128. {
  8129. // forward declare, to be able to friend it later on
  8130. template<typename IteratorType> class iteration_proxy;
  8131. template<typename IteratorType> class iteration_proxy_value;
  8132. /*!
  8133. @brief a template for a bidirectional iterator for the @ref basic_json class
  8134. This class implements a both iterators (iterator and const_iterator) for the
  8135. @ref basic_json class.
  8136. @note An iterator is called *initialized* when a pointer to a JSON value has
  8137. been set (e.g., by a constructor or a copy assignment). If the iterator is
  8138. default-constructed, it is *uninitialized* and most methods are undefined.
  8139. **The library uses assertions to detect calls on uninitialized iterators.**
  8140. @requirement The class satisfies the following concept requirements:
  8141. -
  8142. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8143. The iterator that can be moved can be moved in both directions (i.e.
  8144. incremented and decremented).
  8145. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  8146. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  8147. */
  8148. template<typename BasicJsonType>
  8149. class iter_impl
  8150. {
  8151. /// allow basic_json to access private members
  8152. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  8153. friend BasicJsonType;
  8154. friend iteration_proxy<iter_impl>;
  8155. friend iteration_proxy_value<iter_impl>;
  8156. using object_t = typename BasicJsonType::object_t;
  8157. using array_t = typename BasicJsonType::array_t;
  8158. // make sure BasicJsonType is basic_json or const basic_json
  8159. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  8160. "iter_impl only accepts (const) basic_json");
  8161. public:
  8162. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  8163. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  8164. /// A user-defined iterator should provide publicly accessible typedefs named
  8165. /// iterator_category, value_type, difference_type, pointer, and reference.
  8166. /// Note that value_type is required to be non-const, even for constant iterators.
  8167. using iterator_category = std::bidirectional_iterator_tag;
  8168. /// the type of the values when the iterator is dereferenced
  8169. using value_type = typename BasicJsonType::value_type;
  8170. /// a type to represent differences between iterators
  8171. using difference_type = typename BasicJsonType::difference_type;
  8172. /// defines a pointer to the type iterated over (value_type)
  8173. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  8174. typename BasicJsonType::const_pointer,
  8175. typename BasicJsonType::pointer>::type;
  8176. /// defines a reference to the type iterated over (value_type)
  8177. using reference =
  8178. typename std::conditional<std::is_const<BasicJsonType>::value,
  8179. typename BasicJsonType::const_reference,
  8180. typename BasicJsonType::reference>::type;
  8181. /// default constructor
  8182. iter_impl() = default;
  8183. /*!
  8184. @brief constructor for a given JSON instance
  8185. @param[in] object pointer to a JSON object for this iterator
  8186. @pre object != nullptr
  8187. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8188. */
  8189. explicit iter_impl(pointer object) noexcept : m_object(object)
  8190. {
  8191. assert(m_object != nullptr);
  8192. switch (m_object->m_type)
  8193. {
  8194. case value_t::object:
  8195. {
  8196. m_it.object_iterator = typename object_t::iterator();
  8197. break;
  8198. }
  8199. case value_t::array:
  8200. {
  8201. m_it.array_iterator = typename array_t::iterator();
  8202. break;
  8203. }
  8204. default:
  8205. {
  8206. m_it.primitive_iterator = primitive_iterator_t();
  8207. break;
  8208. }
  8209. }
  8210. }
  8211. /*!
  8212. @note The conventional copy constructor and copy assignment are implicitly
  8213. defined. Combined with the following converting constructor and
  8214. assignment, they support: (1) copy from iterator to iterator, (2)
  8215. copy from const iterator to const iterator, and (3) conversion from
  8216. iterator to const iterator. However conversion from const iterator
  8217. to iterator is not defined.
  8218. */
  8219. /*!
  8220. @brief const copy constructor
  8221. @param[in] other const iterator to copy from
  8222. @note This copy constructor had to be defined explicitly to circumvent a bug
  8223. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  8224. information refer to: https://github.com/nlohmann/json/issues/1608
  8225. */
  8226. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  8227. : m_object(other.m_object), m_it(other.m_it)
  8228. {}
  8229. /*!
  8230. @brief converting assignment
  8231. @param[in] other const iterator to copy from
  8232. @return const/non-const iterator
  8233. @note It is not checked whether @a other is initialized.
  8234. */
  8235. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  8236. {
  8237. m_object = other.m_object;
  8238. m_it = other.m_it;
  8239. return *this;
  8240. }
  8241. /*!
  8242. @brief converting constructor
  8243. @param[in] other non-const iterator to copy from
  8244. @note It is not checked whether @a other is initialized.
  8245. */
  8246. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8247. : m_object(other.m_object), m_it(other.m_it)
  8248. {}
  8249. /*!
  8250. @brief converting assignment
  8251. @param[in] other non-const iterator to copy from
  8252. @return const/non-const iterator
  8253. @note It is not checked whether @a other is initialized.
  8254. */
  8255. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  8256. {
  8257. m_object = other.m_object;
  8258. m_it = other.m_it;
  8259. return *this;
  8260. }
  8261. private:
  8262. /*!
  8263. @brief set the iterator to the first value
  8264. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8265. */
  8266. void set_begin() noexcept
  8267. {
  8268. assert(m_object != nullptr);
  8269. switch (m_object->m_type)
  8270. {
  8271. case value_t::object:
  8272. {
  8273. m_it.object_iterator = m_object->m_value.object->begin();
  8274. break;
  8275. }
  8276. case value_t::array:
  8277. {
  8278. m_it.array_iterator = m_object->m_value.array->begin();
  8279. break;
  8280. }
  8281. case value_t::null:
  8282. {
  8283. // set to end so begin()==end() is true: null is empty
  8284. m_it.primitive_iterator.set_end();
  8285. break;
  8286. }
  8287. default:
  8288. {
  8289. m_it.primitive_iterator.set_begin();
  8290. break;
  8291. }
  8292. }
  8293. }
  8294. /*!
  8295. @brief set the iterator past the last value
  8296. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8297. */
  8298. void set_end() noexcept
  8299. {
  8300. assert(m_object != nullptr);
  8301. switch (m_object->m_type)
  8302. {
  8303. case value_t::object:
  8304. {
  8305. m_it.object_iterator = m_object->m_value.object->end();
  8306. break;
  8307. }
  8308. case value_t::array:
  8309. {
  8310. m_it.array_iterator = m_object->m_value.array->end();
  8311. break;
  8312. }
  8313. default:
  8314. {
  8315. m_it.primitive_iterator.set_end();
  8316. break;
  8317. }
  8318. }
  8319. }
  8320. public:
  8321. /*!
  8322. @brief return a reference to the value pointed to by the iterator
  8323. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8324. */
  8325. reference operator*() const
  8326. {
  8327. assert(m_object != nullptr);
  8328. switch (m_object->m_type)
  8329. {
  8330. case value_t::object:
  8331. {
  8332. assert(m_it.object_iterator != m_object->m_value.object->end());
  8333. return m_it.object_iterator->second;
  8334. }
  8335. case value_t::array:
  8336. {
  8337. assert(m_it.array_iterator != m_object->m_value.array->end());
  8338. return *m_it.array_iterator;
  8339. }
  8340. case value_t::null:
  8341. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8342. default:
  8343. {
  8344. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8345. {
  8346. return *m_object;
  8347. }
  8348. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8349. }
  8350. }
  8351. }
  8352. /*!
  8353. @brief dereference the iterator
  8354. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8355. */
  8356. pointer operator->() const
  8357. {
  8358. assert(m_object != nullptr);
  8359. switch (m_object->m_type)
  8360. {
  8361. case value_t::object:
  8362. {
  8363. assert(m_it.object_iterator != m_object->m_value.object->end());
  8364. return &(m_it.object_iterator->second);
  8365. }
  8366. case value_t::array:
  8367. {
  8368. assert(m_it.array_iterator != m_object->m_value.array->end());
  8369. return &*m_it.array_iterator;
  8370. }
  8371. default:
  8372. {
  8373. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  8374. {
  8375. return m_object;
  8376. }
  8377. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8378. }
  8379. }
  8380. }
  8381. /*!
  8382. @brief post-increment (it++)
  8383. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8384. */
  8385. iter_impl const operator++(int)
  8386. {
  8387. auto result = *this;
  8388. ++(*this);
  8389. return result;
  8390. }
  8391. /*!
  8392. @brief pre-increment (++it)
  8393. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8394. */
  8395. iter_impl& operator++()
  8396. {
  8397. assert(m_object != nullptr);
  8398. switch (m_object->m_type)
  8399. {
  8400. case value_t::object:
  8401. {
  8402. std::advance(m_it.object_iterator, 1);
  8403. break;
  8404. }
  8405. case value_t::array:
  8406. {
  8407. std::advance(m_it.array_iterator, 1);
  8408. break;
  8409. }
  8410. default:
  8411. {
  8412. ++m_it.primitive_iterator;
  8413. break;
  8414. }
  8415. }
  8416. return *this;
  8417. }
  8418. /*!
  8419. @brief post-decrement (it--)
  8420. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8421. */
  8422. iter_impl const operator--(int)
  8423. {
  8424. auto result = *this;
  8425. --(*this);
  8426. return result;
  8427. }
  8428. /*!
  8429. @brief pre-decrement (--it)
  8430. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8431. */
  8432. iter_impl& operator--()
  8433. {
  8434. assert(m_object != nullptr);
  8435. switch (m_object->m_type)
  8436. {
  8437. case value_t::object:
  8438. {
  8439. std::advance(m_it.object_iterator, -1);
  8440. break;
  8441. }
  8442. case value_t::array:
  8443. {
  8444. std::advance(m_it.array_iterator, -1);
  8445. break;
  8446. }
  8447. default:
  8448. {
  8449. --m_it.primitive_iterator;
  8450. break;
  8451. }
  8452. }
  8453. return *this;
  8454. }
  8455. /*!
  8456. @brief comparison: equal
  8457. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8458. */
  8459. bool operator==(const iter_impl& other) const
  8460. {
  8461. // if objects are not the same, the comparison is undefined
  8462. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8463. {
  8464. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8465. }
  8466. assert(m_object != nullptr);
  8467. switch (m_object->m_type)
  8468. {
  8469. case value_t::object:
  8470. return (m_it.object_iterator == other.m_it.object_iterator);
  8471. case value_t::array:
  8472. return (m_it.array_iterator == other.m_it.array_iterator);
  8473. default:
  8474. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  8475. }
  8476. }
  8477. /*!
  8478. @brief comparison: not equal
  8479. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8480. */
  8481. bool operator!=(const iter_impl& other) const
  8482. {
  8483. return not operator==(other);
  8484. }
  8485. /*!
  8486. @brief comparison: smaller
  8487. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8488. */
  8489. bool operator<(const iter_impl& other) const
  8490. {
  8491. // if objects are not the same, the comparison is undefined
  8492. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  8493. {
  8494. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8495. }
  8496. assert(m_object != nullptr);
  8497. switch (m_object->m_type)
  8498. {
  8499. case value_t::object:
  8500. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  8501. case value_t::array:
  8502. return (m_it.array_iterator < other.m_it.array_iterator);
  8503. default:
  8504. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  8505. }
  8506. }
  8507. /*!
  8508. @brief comparison: less than or equal
  8509. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8510. */
  8511. bool operator<=(const iter_impl& other) const
  8512. {
  8513. return not other.operator < (*this);
  8514. }
  8515. /*!
  8516. @brief comparison: greater than
  8517. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8518. */
  8519. bool operator>(const iter_impl& other) const
  8520. {
  8521. return not operator<=(other);
  8522. }
  8523. /*!
  8524. @brief comparison: greater than or equal
  8525. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8526. */
  8527. bool operator>=(const iter_impl& other) const
  8528. {
  8529. return not operator<(other);
  8530. }
  8531. /*!
  8532. @brief add to iterator
  8533. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8534. */
  8535. iter_impl& operator+=(difference_type i)
  8536. {
  8537. assert(m_object != nullptr);
  8538. switch (m_object->m_type)
  8539. {
  8540. case value_t::object:
  8541. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8542. case value_t::array:
  8543. {
  8544. std::advance(m_it.array_iterator, i);
  8545. break;
  8546. }
  8547. default:
  8548. {
  8549. m_it.primitive_iterator += i;
  8550. break;
  8551. }
  8552. }
  8553. return *this;
  8554. }
  8555. /*!
  8556. @brief subtract from iterator
  8557. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8558. */
  8559. iter_impl& operator-=(difference_type i)
  8560. {
  8561. return operator+=(-i);
  8562. }
  8563. /*!
  8564. @brief add to iterator
  8565. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8566. */
  8567. iter_impl operator+(difference_type i) const
  8568. {
  8569. auto result = *this;
  8570. result += i;
  8571. return result;
  8572. }
  8573. /*!
  8574. @brief addition of distance and iterator
  8575. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8576. */
  8577. friend iter_impl operator+(difference_type i, const iter_impl& it)
  8578. {
  8579. auto result = it;
  8580. result += i;
  8581. return result;
  8582. }
  8583. /*!
  8584. @brief subtract from iterator
  8585. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8586. */
  8587. iter_impl operator-(difference_type i) const
  8588. {
  8589. auto result = *this;
  8590. result -= i;
  8591. return result;
  8592. }
  8593. /*!
  8594. @brief return difference
  8595. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8596. */
  8597. difference_type operator-(const iter_impl& other) const
  8598. {
  8599. assert(m_object != nullptr);
  8600. switch (m_object->m_type)
  8601. {
  8602. case value_t::object:
  8603. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8604. case value_t::array:
  8605. return m_it.array_iterator - other.m_it.array_iterator;
  8606. default:
  8607. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  8608. }
  8609. }
  8610. /*!
  8611. @brief access to successor
  8612. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8613. */
  8614. reference operator[](difference_type n) const
  8615. {
  8616. assert(m_object != nullptr);
  8617. switch (m_object->m_type)
  8618. {
  8619. case value_t::object:
  8620. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  8621. case value_t::array:
  8622. return *std::next(m_it.array_iterator, n);
  8623. case value_t::null:
  8624. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8625. default:
  8626. {
  8627. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  8628. {
  8629. return *m_object;
  8630. }
  8631. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8632. }
  8633. }
  8634. }
  8635. /*!
  8636. @brief return the key of an object iterator
  8637. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8638. */
  8639. const typename object_t::key_type& key() const
  8640. {
  8641. assert(m_object != nullptr);
  8642. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  8643. {
  8644. return m_it.object_iterator->first;
  8645. }
  8646. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  8647. }
  8648. /*!
  8649. @brief return the value of an iterator
  8650. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8651. */
  8652. reference value() const
  8653. {
  8654. return operator*();
  8655. }
  8656. private:
  8657. /// associated JSON instance
  8658. pointer m_object = nullptr;
  8659. /// the actual iterator of the associated instance
  8660. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  8661. };
  8662. } // namespace detail
  8663. } // namespace nlohmann
  8664. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  8665. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  8666. #include <cstddef> // ptrdiff_t
  8667. #include <iterator> // reverse_iterator
  8668. #include <utility> // declval
  8669. namespace nlohmann
  8670. {
  8671. namespace detail
  8672. {
  8673. //////////////////////
  8674. // reverse_iterator //
  8675. //////////////////////
  8676. /*!
  8677. @brief a template for a reverse iterator class
  8678. @tparam Base the base iterator type to reverse. Valid types are @ref
  8679. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  8680. create @ref const_reverse_iterator).
  8681. @requirement The class satisfies the following concept requirements:
  8682. -
  8683. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  8684. The iterator that can be moved can be moved in both directions (i.e.
  8685. incremented and decremented).
  8686. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  8687. It is possible to write to the pointed-to element (only if @a Base is
  8688. @ref iterator).
  8689. @since version 1.0.0
  8690. */
  8691. template<typename Base>
  8692. class json_reverse_iterator : public std::reverse_iterator<Base>
  8693. {
  8694. public:
  8695. using difference_type = std::ptrdiff_t;
  8696. /// shortcut to the reverse iterator adapter
  8697. using base_iterator = std::reverse_iterator<Base>;
  8698. /// the reference type for the pointed-to element
  8699. using reference = typename Base::reference;
  8700. /// create reverse iterator from iterator
  8701. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  8702. : base_iterator(it) {}
  8703. /// create reverse iterator from base class
  8704. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  8705. /// post-increment (it++)
  8706. json_reverse_iterator const operator++(int)
  8707. {
  8708. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  8709. }
  8710. /// pre-increment (++it)
  8711. json_reverse_iterator& operator++()
  8712. {
  8713. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  8714. }
  8715. /// post-decrement (it--)
  8716. json_reverse_iterator const operator--(int)
  8717. {
  8718. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  8719. }
  8720. /// pre-decrement (--it)
  8721. json_reverse_iterator& operator--()
  8722. {
  8723. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  8724. }
  8725. /// add to iterator
  8726. json_reverse_iterator& operator+=(difference_type i)
  8727. {
  8728. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  8729. }
  8730. /// add to iterator
  8731. json_reverse_iterator operator+(difference_type i) const
  8732. {
  8733. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  8734. }
  8735. /// subtract from iterator
  8736. json_reverse_iterator operator-(difference_type i) const
  8737. {
  8738. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  8739. }
  8740. /// return difference
  8741. difference_type operator-(const json_reverse_iterator& other) const
  8742. {
  8743. return base_iterator(*this) - base_iterator(other);
  8744. }
  8745. /// access to successor
  8746. reference operator[](difference_type n) const
  8747. {
  8748. return *(this->operator+(n));
  8749. }
  8750. /// return the key of an object iterator
  8751. auto key() const -> decltype(std::declval<Base>().key())
  8752. {
  8753. auto it = --this->base();
  8754. return it.key();
  8755. }
  8756. /// return the value of an iterator
  8757. reference value() const
  8758. {
  8759. auto it = --this->base();
  8760. return it.operator * ();
  8761. }
  8762. };
  8763. } // namespace detail
  8764. } // namespace nlohmann
  8765. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8766. // #include <nlohmann/detail/json_pointer.hpp>
  8767. #include <algorithm> // all_of
  8768. #include <cassert> // assert
  8769. #include <cctype> // isdigit
  8770. #include <numeric> // accumulate
  8771. #include <string> // string
  8772. #include <utility> // move
  8773. #include <vector> // vector
  8774. // #include <nlohmann/detail/exceptions.hpp>
  8775. // #include <nlohmann/detail/macro_scope.hpp>
  8776. // #include <nlohmann/detail/value_t.hpp>
  8777. namespace nlohmann
  8778. {
  8779. template<typename BasicJsonType>
  8780. class json_pointer
  8781. {
  8782. // allow basic_json to access private members
  8783. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  8784. friend class basic_json;
  8785. public:
  8786. /*!
  8787. @brief create JSON pointer
  8788. Create a JSON pointer according to the syntax described in
  8789. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  8790. @param[in] s string representing the JSON pointer; if omitted, the empty
  8791. string is assumed which references the whole JSON value
  8792. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  8793. not begin with a slash (`/`); see example below
  8794. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  8795. not followed by `0` (representing `~`) or `1` (representing `/`); see
  8796. example below
  8797. @liveexample{The example shows the construction several valid JSON pointers
  8798. as well as the exceptional behavior.,json_pointer}
  8799. @since version 2.0.0
  8800. */
  8801. explicit json_pointer(const std::string& s = "")
  8802. : reference_tokens(split(s))
  8803. {}
  8804. /*!
  8805. @brief return a string representation of the JSON pointer
  8806. @invariant For each JSON pointer `ptr`, it holds:
  8807. @code {.cpp}
  8808. ptr == json_pointer(ptr.to_string());
  8809. @endcode
  8810. @return a string representation of the JSON pointer
  8811. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  8812. @since version 2.0.0
  8813. */
  8814. std::string to_string() const
  8815. {
  8816. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  8817. std::string{},
  8818. [](const std::string & a, const std::string & b)
  8819. {
  8820. return a + "/" + escape(b);
  8821. });
  8822. }
  8823. /// @copydoc to_string()
  8824. operator std::string() const
  8825. {
  8826. return to_string();
  8827. }
  8828. /*!
  8829. @brief append another JSON pointer at the end of this JSON pointer
  8830. @param[in] ptr JSON pointer to append
  8831. @return JSON pointer with @a ptr appended
  8832. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8833. @complexity Linear in the length of @a ptr.
  8834. @sa @ref operator/=(std::string) to append a reference token
  8835. @sa @ref operator/=(std::size_t) to append an array index
  8836. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  8837. @since version 3.6.0
  8838. */
  8839. json_pointer& operator/=(const json_pointer& ptr)
  8840. {
  8841. reference_tokens.insert(reference_tokens.end(),
  8842. ptr.reference_tokens.begin(),
  8843. ptr.reference_tokens.end());
  8844. return *this;
  8845. }
  8846. /*!
  8847. @brief append an unescaped reference token at the end of this JSON pointer
  8848. @param[in] token reference token to append
  8849. @return JSON pointer with @a token appended without escaping @a token
  8850. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8851. @complexity Amortized constant.
  8852. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8853. @sa @ref operator/=(std::size_t) to append an array index
  8854. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  8855. @since version 3.6.0
  8856. */
  8857. json_pointer& operator/=(std::string token)
  8858. {
  8859. push_back(std::move(token));
  8860. return *this;
  8861. }
  8862. /*!
  8863. @brief append an array index at the end of this JSON pointer
  8864. @param[in] array_index array index to append
  8865. @return JSON pointer with @a array_index appended
  8866. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  8867. @complexity Amortized constant.
  8868. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8869. @sa @ref operator/=(std::string) to append a reference token
  8870. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  8871. @since version 3.6.0
  8872. */
  8873. json_pointer& operator/=(std::size_t array_index)
  8874. {
  8875. return *this /= std::to_string(array_index);
  8876. }
  8877. /*!
  8878. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  8879. @param[in] lhs JSON pointer
  8880. @param[in] rhs JSON pointer
  8881. @return a new JSON pointer with @a rhs appended to @a lhs
  8882. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8883. @complexity Linear in the length of @a lhs and @a rhs.
  8884. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  8885. @since version 3.6.0
  8886. */
  8887. friend json_pointer operator/(const json_pointer& lhs,
  8888. const json_pointer& rhs)
  8889. {
  8890. return json_pointer(lhs) /= rhs;
  8891. }
  8892. /*!
  8893. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  8894. @param[in] ptr JSON pointer
  8895. @param[in] token reference token
  8896. @return a new JSON pointer with unescaped @a token appended to @a ptr
  8897. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8898. @complexity Linear in the length of @a ptr.
  8899. @sa @ref operator/=(std::string) to append a reference token
  8900. @since version 3.6.0
  8901. */
  8902. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  8903. {
  8904. return json_pointer(ptr) /= std::move(token);
  8905. }
  8906. /*!
  8907. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  8908. @param[in] ptr JSON pointer
  8909. @param[in] array_index array index
  8910. @return a new JSON pointer with @a array_index appended to @a ptr
  8911. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  8912. @complexity Linear in the length of @a ptr.
  8913. @sa @ref operator/=(std::size_t) to append an array index
  8914. @since version 3.6.0
  8915. */
  8916. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  8917. {
  8918. return json_pointer(ptr) /= array_index;
  8919. }
  8920. /*!
  8921. @brief returns the parent of this JSON pointer
  8922. @return parent of this JSON pointer; in case this JSON pointer is the root,
  8923. the root itself is returned
  8924. @complexity Linear in the length of the JSON pointer.
  8925. @liveexample{The example shows the result of `parent_pointer` for different
  8926. JSON Pointers.,json_pointer__parent_pointer}
  8927. @since version 3.6.0
  8928. */
  8929. json_pointer parent_pointer() const
  8930. {
  8931. if (empty())
  8932. {
  8933. return *this;
  8934. }
  8935. json_pointer res = *this;
  8936. res.pop_back();
  8937. return res;
  8938. }
  8939. /*!
  8940. @brief remove last reference token
  8941. @pre not `empty()`
  8942. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  8943. @complexity Constant.
  8944. @throw out_of_range.405 if JSON pointer has no parent
  8945. @since version 3.6.0
  8946. */
  8947. void pop_back()
  8948. {
  8949. if (JSON_HEDLEY_UNLIKELY(empty()))
  8950. {
  8951. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8952. }
  8953. reference_tokens.pop_back();
  8954. }
  8955. /*!
  8956. @brief return last reference token
  8957. @pre not `empty()`
  8958. @return last reference token
  8959. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  8960. @complexity Constant.
  8961. @throw out_of_range.405 if JSON pointer has no parent
  8962. @since version 3.6.0
  8963. */
  8964. const std::string& back() const
  8965. {
  8966. if (JSON_HEDLEY_UNLIKELY(empty()))
  8967. {
  8968. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  8969. }
  8970. return reference_tokens.back();
  8971. }
  8972. /*!
  8973. @brief append an unescaped token at the end of the reference pointer
  8974. @param[in] token token to add
  8975. @complexity Amortized constant.
  8976. @liveexample{The example shows the result of `push_back` for different
  8977. JSON Pointers.,json_pointer__push_back}
  8978. @since version 3.6.0
  8979. */
  8980. void push_back(const std::string& token)
  8981. {
  8982. reference_tokens.push_back(token);
  8983. }
  8984. /// @copydoc push_back(const std::string&)
  8985. void push_back(std::string&& token)
  8986. {
  8987. reference_tokens.push_back(std::move(token));
  8988. }
  8989. /*!
  8990. @brief return whether pointer points to the root document
  8991. @return true iff the JSON pointer points to the root document
  8992. @complexity Constant.
  8993. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  8994. @liveexample{The example shows the result of `empty` for different JSON
  8995. Pointers.,json_pointer__empty}
  8996. @since version 3.6.0
  8997. */
  8998. bool empty() const noexcept
  8999. {
  9000. return reference_tokens.empty();
  9001. }
  9002. private:
  9003. /*!
  9004. @param[in] s reference token to be converted into an array index
  9005. @return integer representation of @a s
  9006. @throw out_of_range.404 if string @a s could not be converted to an integer
  9007. */
  9008. static int array_index(const std::string& s)
  9009. {
  9010. std::size_t processed_chars = 0;
  9011. const int res = std::stoi(s, &processed_chars);
  9012. // check if the string was completely read
  9013. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9014. {
  9015. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9016. }
  9017. return res;
  9018. }
  9019. json_pointer top() const
  9020. {
  9021. if (JSON_HEDLEY_UNLIKELY(empty()))
  9022. {
  9023. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9024. }
  9025. json_pointer result = *this;
  9026. result.reference_tokens = {reference_tokens[0]};
  9027. return result;
  9028. }
  9029. /*!
  9030. @brief create and return a reference to the pointed to value
  9031. @complexity Linear in the number of reference tokens.
  9032. @throw parse_error.109 if array index is not a number
  9033. @throw type_error.313 if value cannot be unflattened
  9034. */
  9035. BasicJsonType& get_and_create(BasicJsonType& j) const
  9036. {
  9037. using size_type = typename BasicJsonType::size_type;
  9038. auto result = &j;
  9039. // in case no reference tokens exist, return a reference to the JSON value
  9040. // j which will be overwritten by a primitive value
  9041. for (const auto& reference_token : reference_tokens)
  9042. {
  9043. switch (result->type())
  9044. {
  9045. case detail::value_t::null:
  9046. {
  9047. if (reference_token == "0")
  9048. {
  9049. // start a new array if reference token is 0
  9050. result = &result->operator[](0);
  9051. }
  9052. else
  9053. {
  9054. // start a new object otherwise
  9055. result = &result->operator[](reference_token);
  9056. }
  9057. break;
  9058. }
  9059. case detail::value_t::object:
  9060. {
  9061. // create an entry in the object
  9062. result = &result->operator[](reference_token);
  9063. break;
  9064. }
  9065. case detail::value_t::array:
  9066. {
  9067. // create an entry in the array
  9068. JSON_TRY
  9069. {
  9070. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9071. }
  9072. JSON_CATCH(std::invalid_argument&)
  9073. {
  9074. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9075. }
  9076. break;
  9077. }
  9078. /*
  9079. The following code is only reached if there exists a reference
  9080. token _and_ the current value is primitive. In this case, we have
  9081. an error situation, because primitive values may only occur as
  9082. single value; that is, with an empty list of reference tokens.
  9083. */
  9084. default:
  9085. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9086. }
  9087. }
  9088. return *result;
  9089. }
  9090. /*!
  9091. @brief return a reference to the pointed to value
  9092. @note This version does not throw if a value is not present, but tries to
  9093. create nested values instead. For instance, calling this function
  9094. with pointer `"/this/that"` on a null value is equivalent to calling
  9095. `operator[]("this").operator[]("that")` on that value, effectively
  9096. changing the null value to an object.
  9097. @param[in] ptr a JSON value
  9098. @return reference to the JSON value pointed to by the JSON pointer
  9099. @complexity Linear in the length of the JSON pointer.
  9100. @throw parse_error.106 if an array index begins with '0'
  9101. @throw parse_error.109 if an array index was not a number
  9102. @throw out_of_range.404 if the JSON pointer can not be resolved
  9103. */
  9104. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9105. {
  9106. using size_type = typename BasicJsonType::size_type;
  9107. for (const auto& reference_token : reference_tokens)
  9108. {
  9109. // convert null values to arrays or objects before continuing
  9110. if (ptr->is_null())
  9111. {
  9112. // check if reference token is a number
  9113. const bool nums =
  9114. std::all_of(reference_token.begin(), reference_token.end(),
  9115. [](const unsigned char x)
  9116. {
  9117. return std::isdigit(x);
  9118. });
  9119. // change value to array for numbers or "-" or to object otherwise
  9120. *ptr = (nums or reference_token == "-")
  9121. ? detail::value_t::array
  9122. : detail::value_t::object;
  9123. }
  9124. switch (ptr->type())
  9125. {
  9126. case detail::value_t::object:
  9127. {
  9128. // use unchecked object access
  9129. ptr = &ptr->operator[](reference_token);
  9130. break;
  9131. }
  9132. case detail::value_t::array:
  9133. {
  9134. // error condition (cf. RFC 6901, Sect. 4)
  9135. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9136. {
  9137. JSON_THROW(detail::parse_error::create(106, 0,
  9138. "array index '" + reference_token +
  9139. "' must not begin with '0'"));
  9140. }
  9141. if (reference_token == "-")
  9142. {
  9143. // explicitly treat "-" as index beyond the end
  9144. ptr = &ptr->operator[](ptr->m_value.array->size());
  9145. }
  9146. else
  9147. {
  9148. // convert array index to number; unchecked access
  9149. JSON_TRY
  9150. {
  9151. ptr = &ptr->operator[](
  9152. static_cast<size_type>(array_index(reference_token)));
  9153. }
  9154. JSON_CATCH(std::invalid_argument&)
  9155. {
  9156. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9157. }
  9158. }
  9159. break;
  9160. }
  9161. default:
  9162. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9163. }
  9164. }
  9165. return *ptr;
  9166. }
  9167. /*!
  9168. @throw parse_error.106 if an array index begins with '0'
  9169. @throw parse_error.109 if an array index was not a number
  9170. @throw out_of_range.402 if the array index '-' is used
  9171. @throw out_of_range.404 if the JSON pointer can not be resolved
  9172. */
  9173. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9174. {
  9175. using size_type = typename BasicJsonType::size_type;
  9176. for (const auto& reference_token : reference_tokens)
  9177. {
  9178. switch (ptr->type())
  9179. {
  9180. case detail::value_t::object:
  9181. {
  9182. // note: at performs range check
  9183. ptr = &ptr->at(reference_token);
  9184. break;
  9185. }
  9186. case detail::value_t::array:
  9187. {
  9188. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9189. {
  9190. // "-" always fails the range check
  9191. JSON_THROW(detail::out_of_range::create(402,
  9192. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9193. ") is out of range"));
  9194. }
  9195. // error condition (cf. RFC 6901, Sect. 4)
  9196. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9197. {
  9198. JSON_THROW(detail::parse_error::create(106, 0,
  9199. "array index '" + reference_token +
  9200. "' must not begin with '0'"));
  9201. }
  9202. // note: at performs range check
  9203. JSON_TRY
  9204. {
  9205. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9206. }
  9207. JSON_CATCH(std::invalid_argument&)
  9208. {
  9209. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9210. }
  9211. break;
  9212. }
  9213. default:
  9214. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9215. }
  9216. }
  9217. return *ptr;
  9218. }
  9219. /*!
  9220. @brief return a const reference to the pointed to value
  9221. @param[in] ptr a JSON value
  9222. @return const reference to the JSON value pointed to by the JSON
  9223. pointer
  9224. @throw parse_error.106 if an array index begins with '0'
  9225. @throw parse_error.109 if an array index was not a number
  9226. @throw out_of_range.402 if the array index '-' is used
  9227. @throw out_of_range.404 if the JSON pointer can not be resolved
  9228. */
  9229. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9230. {
  9231. using size_type = typename BasicJsonType::size_type;
  9232. for (const auto& reference_token : reference_tokens)
  9233. {
  9234. switch (ptr->type())
  9235. {
  9236. case detail::value_t::object:
  9237. {
  9238. // use unchecked object access
  9239. ptr = &ptr->operator[](reference_token);
  9240. break;
  9241. }
  9242. case detail::value_t::array:
  9243. {
  9244. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9245. {
  9246. // "-" cannot be used for const access
  9247. JSON_THROW(detail::out_of_range::create(402,
  9248. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9249. ") is out of range"));
  9250. }
  9251. // error condition (cf. RFC 6901, Sect. 4)
  9252. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9253. {
  9254. JSON_THROW(detail::parse_error::create(106, 0,
  9255. "array index '" + reference_token +
  9256. "' must not begin with '0'"));
  9257. }
  9258. // use unchecked array access
  9259. JSON_TRY
  9260. {
  9261. ptr = &ptr->operator[](
  9262. static_cast<size_type>(array_index(reference_token)));
  9263. }
  9264. JSON_CATCH(std::invalid_argument&)
  9265. {
  9266. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9267. }
  9268. break;
  9269. }
  9270. default:
  9271. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9272. }
  9273. }
  9274. return *ptr;
  9275. }
  9276. /*!
  9277. @throw parse_error.106 if an array index begins with '0'
  9278. @throw parse_error.109 if an array index was not a number
  9279. @throw out_of_range.402 if the array index '-' is used
  9280. @throw out_of_range.404 if the JSON pointer can not be resolved
  9281. */
  9282. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9283. {
  9284. using size_type = typename BasicJsonType::size_type;
  9285. for (const auto& reference_token : reference_tokens)
  9286. {
  9287. switch (ptr->type())
  9288. {
  9289. case detail::value_t::object:
  9290. {
  9291. // note: at performs range check
  9292. ptr = &ptr->at(reference_token);
  9293. break;
  9294. }
  9295. case detail::value_t::array:
  9296. {
  9297. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9298. {
  9299. // "-" always fails the range check
  9300. JSON_THROW(detail::out_of_range::create(402,
  9301. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9302. ") is out of range"));
  9303. }
  9304. // error condition (cf. RFC 6901, Sect. 4)
  9305. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9306. {
  9307. JSON_THROW(detail::parse_error::create(106, 0,
  9308. "array index '" + reference_token +
  9309. "' must not begin with '0'"));
  9310. }
  9311. // note: at performs range check
  9312. JSON_TRY
  9313. {
  9314. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9315. }
  9316. JSON_CATCH(std::invalid_argument&)
  9317. {
  9318. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9319. }
  9320. break;
  9321. }
  9322. default:
  9323. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9324. }
  9325. }
  9326. return *ptr;
  9327. }
  9328. /*!
  9329. @throw parse_error.106 if an array index begins with '0'
  9330. @throw parse_error.109 if an array index was not a number
  9331. */
  9332. bool contains(const BasicJsonType* ptr) const
  9333. {
  9334. using size_type = typename BasicJsonType::size_type;
  9335. for (const auto& reference_token : reference_tokens)
  9336. {
  9337. switch (ptr->type())
  9338. {
  9339. case detail::value_t::object:
  9340. {
  9341. if (not ptr->contains(reference_token))
  9342. {
  9343. // we did not find the key in the object
  9344. return false;
  9345. }
  9346. ptr = &ptr->operator[](reference_token);
  9347. break;
  9348. }
  9349. case detail::value_t::array:
  9350. {
  9351. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  9352. {
  9353. // "-" always fails the range check
  9354. return false;
  9355. }
  9356. // error condition (cf. RFC 6901, Sect. 4)
  9357. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9358. {
  9359. JSON_THROW(detail::parse_error::create(106, 0,
  9360. "array index '" + reference_token +
  9361. "' must not begin with '0'"));
  9362. }
  9363. JSON_TRY
  9364. {
  9365. const auto idx = static_cast<size_type>(array_index(reference_token));
  9366. if (idx >= ptr->size())
  9367. {
  9368. // index out of range
  9369. return false;
  9370. }
  9371. ptr = &ptr->operator[](idx);
  9372. break;
  9373. }
  9374. JSON_CATCH(std::invalid_argument&)
  9375. {
  9376. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9377. }
  9378. break;
  9379. }
  9380. default:
  9381. {
  9382. // we do not expect primitive values if there is still a
  9383. // reference token to process
  9384. return false;
  9385. }
  9386. }
  9387. }
  9388. // no reference token left means we found a primitive value
  9389. return true;
  9390. }
  9391. /*!
  9392. @brief split the string input to reference tokens
  9393. @note This function is only called by the json_pointer constructor.
  9394. All exceptions below are documented there.
  9395. @throw parse_error.107 if the pointer is not empty or begins with '/'
  9396. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  9397. */
  9398. static std::vector<std::string> split(const std::string& reference_string)
  9399. {
  9400. std::vector<std::string> result;
  9401. // special case: empty reference string -> no reference tokens
  9402. if (reference_string.empty())
  9403. {
  9404. return result;
  9405. }
  9406. // check if nonempty reference string begins with slash
  9407. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  9408. {
  9409. JSON_THROW(detail::parse_error::create(107, 1,
  9410. "JSON pointer must be empty or begin with '/' - was: '" +
  9411. reference_string + "'"));
  9412. }
  9413. // extract the reference tokens:
  9414. // - slash: position of the last read slash (or end of string)
  9415. // - start: position after the previous slash
  9416. for (
  9417. // search for the first slash after the first character
  9418. std::size_t slash = reference_string.find_first_of('/', 1),
  9419. // set the beginning of the first reference token
  9420. start = 1;
  9421. // we can stop if start == 0 (if slash == std::string::npos)
  9422. start != 0;
  9423. // set the beginning of the next reference token
  9424. // (will eventually be 0 if slash == std::string::npos)
  9425. start = (slash == std::string::npos) ? 0 : slash + 1,
  9426. // find next slash
  9427. slash = reference_string.find_first_of('/', start))
  9428. {
  9429. // use the text between the beginning of the reference token
  9430. // (start) and the last slash (slash).
  9431. auto reference_token = reference_string.substr(start, slash - start);
  9432. // check reference tokens are properly escaped
  9433. for (std::size_t pos = reference_token.find_first_of('~');
  9434. pos != std::string::npos;
  9435. pos = reference_token.find_first_of('~', pos + 1))
  9436. {
  9437. assert(reference_token[pos] == '~');
  9438. // ~ must be followed by 0 or 1
  9439. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 or
  9440. (reference_token[pos + 1] != '0' and
  9441. reference_token[pos + 1] != '1')))
  9442. {
  9443. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  9444. }
  9445. }
  9446. // finally, store the reference token
  9447. unescape(reference_token);
  9448. result.push_back(reference_token);
  9449. }
  9450. return result;
  9451. }
  9452. /*!
  9453. @brief replace all occurrences of a substring by another string
  9454. @param[in,out] s the string to manipulate; changed so that all
  9455. occurrences of @a f are replaced with @a t
  9456. @param[in] f the substring to replace with @a t
  9457. @param[in] t the string to replace @a f
  9458. @pre The search string @a f must not be empty. **This precondition is
  9459. enforced with an assertion.**
  9460. @since version 2.0.0
  9461. */
  9462. static void replace_substring(std::string& s, const std::string& f,
  9463. const std::string& t)
  9464. {
  9465. assert(not f.empty());
  9466. for (auto pos = s.find(f); // find first occurrence of f
  9467. pos != std::string::npos; // make sure f was found
  9468. s.replace(pos, f.size(), t), // replace with t, and
  9469. pos = s.find(f, pos + t.size())) // find next occurrence of f
  9470. {}
  9471. }
  9472. /// escape "~" to "~0" and "/" to "~1"
  9473. static std::string escape(std::string s)
  9474. {
  9475. replace_substring(s, "~", "~0");
  9476. replace_substring(s, "/", "~1");
  9477. return s;
  9478. }
  9479. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  9480. static void unescape(std::string& s)
  9481. {
  9482. replace_substring(s, "~1", "/");
  9483. replace_substring(s, "~0", "~");
  9484. }
  9485. /*!
  9486. @param[in] reference_string the reference string to the current value
  9487. @param[in] value the value to consider
  9488. @param[in,out] result the result object to insert values to
  9489. @note Empty objects or arrays are flattened to `null`.
  9490. */
  9491. static void flatten(const std::string& reference_string,
  9492. const BasicJsonType& value,
  9493. BasicJsonType& result)
  9494. {
  9495. switch (value.type())
  9496. {
  9497. case detail::value_t::array:
  9498. {
  9499. if (value.m_value.array->empty())
  9500. {
  9501. // flatten empty array as null
  9502. result[reference_string] = nullptr;
  9503. }
  9504. else
  9505. {
  9506. // iterate array and use index as reference string
  9507. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  9508. {
  9509. flatten(reference_string + "/" + std::to_string(i),
  9510. value.m_value.array->operator[](i), result);
  9511. }
  9512. }
  9513. break;
  9514. }
  9515. case detail::value_t::object:
  9516. {
  9517. if (value.m_value.object->empty())
  9518. {
  9519. // flatten empty object as null
  9520. result[reference_string] = nullptr;
  9521. }
  9522. else
  9523. {
  9524. // iterate object and use keys as reference string
  9525. for (const auto& element : *value.m_value.object)
  9526. {
  9527. flatten(reference_string + "/" + escape(element.first), element.second, result);
  9528. }
  9529. }
  9530. break;
  9531. }
  9532. default:
  9533. {
  9534. // add primitive value with its reference string
  9535. result[reference_string] = value;
  9536. break;
  9537. }
  9538. }
  9539. }
  9540. /*!
  9541. @param[in] value flattened JSON
  9542. @return unflattened JSON
  9543. @throw parse_error.109 if array index is not a number
  9544. @throw type_error.314 if value is not an object
  9545. @throw type_error.315 if object values are not primitive
  9546. @throw type_error.313 if value cannot be unflattened
  9547. */
  9548. static BasicJsonType
  9549. unflatten(const BasicJsonType& value)
  9550. {
  9551. if (JSON_HEDLEY_UNLIKELY(not value.is_object()))
  9552. {
  9553. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  9554. }
  9555. BasicJsonType result;
  9556. // iterate the JSON object values
  9557. for (const auto& element : *value.m_value.object)
  9558. {
  9559. if (JSON_HEDLEY_UNLIKELY(not element.second.is_primitive()))
  9560. {
  9561. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  9562. }
  9563. // assign value to reference pointed to by JSON pointer; Note that if
  9564. // the JSON pointer is "" (i.e., points to the whole value), function
  9565. // get_and_create returns a reference to result itself. An assignment
  9566. // will then create a primitive value.
  9567. json_pointer(element.first).get_and_create(result) = element.second;
  9568. }
  9569. return result;
  9570. }
  9571. /*!
  9572. @brief compares two JSON pointers for equality
  9573. @param[in] lhs JSON pointer to compare
  9574. @param[in] rhs JSON pointer to compare
  9575. @return whether @a lhs is equal to @a rhs
  9576. @complexity Linear in the length of the JSON pointer
  9577. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9578. */
  9579. friend bool operator==(json_pointer const& lhs,
  9580. json_pointer const& rhs) noexcept
  9581. {
  9582. return lhs.reference_tokens == rhs.reference_tokens;
  9583. }
  9584. /*!
  9585. @brief compares two JSON pointers for inequality
  9586. @param[in] lhs JSON pointer to compare
  9587. @param[in] rhs JSON pointer to compare
  9588. @return whether @a lhs is not equal @a rhs
  9589. @complexity Linear in the length of the JSON pointer
  9590. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9591. */
  9592. friend bool operator!=(json_pointer const& lhs,
  9593. json_pointer const& rhs) noexcept
  9594. {
  9595. return not (lhs == rhs);
  9596. }
  9597. /// the reference tokens
  9598. std::vector<std::string> reference_tokens;
  9599. };
  9600. } // namespace nlohmann
  9601. // #include <nlohmann/detail/json_ref.hpp>
  9602. #include <initializer_list>
  9603. #include <utility>
  9604. // #include <nlohmann/detail/meta/type_traits.hpp>
  9605. namespace nlohmann
  9606. {
  9607. namespace detail
  9608. {
  9609. template<typename BasicJsonType>
  9610. class json_ref
  9611. {
  9612. public:
  9613. using value_type = BasicJsonType;
  9614. json_ref(value_type&& value)
  9615. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  9616. {}
  9617. json_ref(const value_type& value)
  9618. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  9619. {}
  9620. json_ref(std::initializer_list<json_ref> init)
  9621. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  9622. {}
  9623. template <
  9624. class... Args,
  9625. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  9626. json_ref(Args && ... args)
  9627. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  9628. is_rvalue(true) {}
  9629. // class should be movable only
  9630. json_ref(json_ref&&) = default;
  9631. json_ref(const json_ref&) = delete;
  9632. json_ref& operator=(const json_ref&) = delete;
  9633. json_ref& operator=(json_ref&&) = delete;
  9634. ~json_ref() = default;
  9635. value_type moved_or_copied() const
  9636. {
  9637. if (is_rvalue)
  9638. {
  9639. return std::move(*value_ref);
  9640. }
  9641. return *value_ref;
  9642. }
  9643. value_type const& operator*() const
  9644. {
  9645. return *static_cast<value_type const*>(value_ref);
  9646. }
  9647. value_type const* operator->() const
  9648. {
  9649. return static_cast<value_type const*>(value_ref);
  9650. }
  9651. private:
  9652. mutable value_type owned_value = nullptr;
  9653. value_type* value_ref = nullptr;
  9654. const bool is_rvalue;
  9655. };
  9656. } // namespace detail
  9657. } // namespace nlohmann
  9658. // #include <nlohmann/detail/macro_scope.hpp>
  9659. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9660. // #include <nlohmann/detail/meta/type_traits.hpp>
  9661. // #include <nlohmann/detail/output/binary_writer.hpp>
  9662. #include <algorithm> // reverse
  9663. #include <array> // array
  9664. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  9665. #include <cstring> // memcpy
  9666. #include <limits> // numeric_limits
  9667. #include <string> // string
  9668. // #include <nlohmann/detail/input/binary_reader.hpp>
  9669. // #include <nlohmann/detail/macro_scope.hpp>
  9670. // #include <nlohmann/detail/output/output_adapters.hpp>
  9671. #include <algorithm> // copy
  9672. #include <cstddef> // size_t
  9673. #include <ios> // streamsize
  9674. #include <iterator> // back_inserter
  9675. #include <memory> // shared_ptr, make_shared
  9676. #include <ostream> // basic_ostream
  9677. #include <string> // basic_string
  9678. #include <vector> // vector
  9679. // #include <nlohmann/detail/macro_scope.hpp>
  9680. namespace nlohmann
  9681. {
  9682. namespace detail
  9683. {
  9684. /// abstract output adapter interface
  9685. template<typename CharType> struct output_adapter_protocol
  9686. {
  9687. virtual void write_character(CharType c) = 0;
  9688. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  9689. virtual ~output_adapter_protocol() = default;
  9690. };
  9691. /// a type to simplify interfaces
  9692. template<typename CharType>
  9693. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  9694. /// output adapter for byte vectors
  9695. template<typename CharType>
  9696. class output_vector_adapter : public output_adapter_protocol<CharType>
  9697. {
  9698. public:
  9699. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  9700. : v(vec)
  9701. {}
  9702. void write_character(CharType c) override
  9703. {
  9704. v.push_back(c);
  9705. }
  9706. JSON_HEDLEY_NON_NULL(2)
  9707. void write_characters(const CharType* s, std::size_t length) override
  9708. {
  9709. std::copy(s, s + length, std::back_inserter(v));
  9710. }
  9711. private:
  9712. std::vector<CharType>& v;
  9713. };
  9714. /// output adapter for output streams
  9715. template<typename CharType>
  9716. class output_stream_adapter : public output_adapter_protocol<CharType>
  9717. {
  9718. public:
  9719. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  9720. : stream(s)
  9721. {}
  9722. void write_character(CharType c) override
  9723. {
  9724. stream.put(c);
  9725. }
  9726. JSON_HEDLEY_NON_NULL(2)
  9727. void write_characters(const CharType* s, std::size_t length) override
  9728. {
  9729. stream.write(s, static_cast<std::streamsize>(length));
  9730. }
  9731. private:
  9732. std::basic_ostream<CharType>& stream;
  9733. };
  9734. /// output adapter for basic_string
  9735. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9736. class output_string_adapter : public output_adapter_protocol<CharType>
  9737. {
  9738. public:
  9739. explicit output_string_adapter(StringType& s) noexcept
  9740. : str(s)
  9741. {}
  9742. void write_character(CharType c) override
  9743. {
  9744. str.push_back(c);
  9745. }
  9746. JSON_HEDLEY_NON_NULL(2)
  9747. void write_characters(const CharType* s, std::size_t length) override
  9748. {
  9749. str.append(s, length);
  9750. }
  9751. private:
  9752. StringType& str;
  9753. };
  9754. template<typename CharType, typename StringType = std::basic_string<CharType>>
  9755. class output_adapter
  9756. {
  9757. public:
  9758. output_adapter(std::vector<CharType>& vec)
  9759. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  9760. output_adapter(std::basic_ostream<CharType>& s)
  9761. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  9762. output_adapter(StringType& s)
  9763. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  9764. operator output_adapter_t<CharType>()
  9765. {
  9766. return oa;
  9767. }
  9768. private:
  9769. output_adapter_t<CharType> oa = nullptr;
  9770. };
  9771. } // namespace detail
  9772. } // namespace nlohmann
  9773. namespace nlohmann
  9774. {
  9775. namespace detail
  9776. {
  9777. ///////////////////
  9778. // binary writer //
  9779. ///////////////////
  9780. /*!
  9781. @brief serialization to CBOR and MessagePack values
  9782. */
  9783. template<typename BasicJsonType, typename CharType>
  9784. class binary_writer
  9785. {
  9786. using string_t = typename BasicJsonType::string_t;
  9787. public:
  9788. /*!
  9789. @brief create a binary writer
  9790. @param[in] adapter output adapter to write to
  9791. */
  9792. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  9793. {
  9794. assert(oa);
  9795. }
  9796. /*!
  9797. @param[in] j JSON value to serialize
  9798. @pre j.type() == value_t::object
  9799. */
  9800. void write_bson(const BasicJsonType& j)
  9801. {
  9802. switch (j.type())
  9803. {
  9804. case value_t::object:
  9805. {
  9806. write_bson_object(*j.m_value.object);
  9807. break;
  9808. }
  9809. default:
  9810. {
  9811. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  9812. }
  9813. }
  9814. }
  9815. /*!
  9816. @param[in] j JSON value to serialize
  9817. */
  9818. void write_cbor(const BasicJsonType& j)
  9819. {
  9820. switch (j.type())
  9821. {
  9822. case value_t::null:
  9823. {
  9824. oa->write_character(to_char_type(0xF6));
  9825. break;
  9826. }
  9827. case value_t::boolean:
  9828. {
  9829. oa->write_character(j.m_value.boolean
  9830. ? to_char_type(0xF5)
  9831. : to_char_type(0xF4));
  9832. break;
  9833. }
  9834. case value_t::number_integer:
  9835. {
  9836. if (j.m_value.number_integer >= 0)
  9837. {
  9838. // CBOR does not differentiate between positive signed
  9839. // integers and unsigned integers. Therefore, we used the
  9840. // code from the value_t::number_unsigned case here.
  9841. if (j.m_value.number_integer <= 0x17)
  9842. {
  9843. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9844. }
  9845. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  9846. {
  9847. oa->write_character(to_char_type(0x18));
  9848. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  9849. }
  9850. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  9851. {
  9852. oa->write_character(to_char_type(0x19));
  9853. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  9854. }
  9855. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  9856. {
  9857. oa->write_character(to_char_type(0x1A));
  9858. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  9859. }
  9860. else
  9861. {
  9862. oa->write_character(to_char_type(0x1B));
  9863. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  9864. }
  9865. }
  9866. else
  9867. {
  9868. // The conversions below encode the sign in the first
  9869. // byte, and the value is converted to a positive number.
  9870. const auto positive_number = -1 - j.m_value.number_integer;
  9871. if (j.m_value.number_integer >= -24)
  9872. {
  9873. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  9874. }
  9875. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  9876. {
  9877. oa->write_character(to_char_type(0x38));
  9878. write_number(static_cast<std::uint8_t>(positive_number));
  9879. }
  9880. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  9881. {
  9882. oa->write_character(to_char_type(0x39));
  9883. write_number(static_cast<std::uint16_t>(positive_number));
  9884. }
  9885. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  9886. {
  9887. oa->write_character(to_char_type(0x3A));
  9888. write_number(static_cast<std::uint32_t>(positive_number));
  9889. }
  9890. else
  9891. {
  9892. oa->write_character(to_char_type(0x3B));
  9893. write_number(static_cast<std::uint64_t>(positive_number));
  9894. }
  9895. }
  9896. break;
  9897. }
  9898. case value_t::number_unsigned:
  9899. {
  9900. if (j.m_value.number_unsigned <= 0x17)
  9901. {
  9902. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9903. }
  9904. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9905. {
  9906. oa->write_character(to_char_type(0x18));
  9907. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  9908. }
  9909. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  9910. {
  9911. oa->write_character(to_char_type(0x19));
  9912. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  9913. }
  9914. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  9915. {
  9916. oa->write_character(to_char_type(0x1A));
  9917. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  9918. }
  9919. else
  9920. {
  9921. oa->write_character(to_char_type(0x1B));
  9922. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  9923. }
  9924. break;
  9925. }
  9926. case value_t::number_float:
  9927. {
  9928. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  9929. write_number(j.m_value.number_float);
  9930. break;
  9931. }
  9932. case value_t::string:
  9933. {
  9934. // step 1: write control byte and the string length
  9935. const auto N = j.m_value.string->size();
  9936. if (N <= 0x17)
  9937. {
  9938. write_number(static_cast<std::uint8_t>(0x60 + N));
  9939. }
  9940. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9941. {
  9942. oa->write_character(to_char_type(0x78));
  9943. write_number(static_cast<std::uint8_t>(N));
  9944. }
  9945. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9946. {
  9947. oa->write_character(to_char_type(0x79));
  9948. write_number(static_cast<std::uint16_t>(N));
  9949. }
  9950. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9951. {
  9952. oa->write_character(to_char_type(0x7A));
  9953. write_number(static_cast<std::uint32_t>(N));
  9954. }
  9955. // LCOV_EXCL_START
  9956. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9957. {
  9958. oa->write_character(to_char_type(0x7B));
  9959. write_number(static_cast<std::uint64_t>(N));
  9960. }
  9961. // LCOV_EXCL_STOP
  9962. // step 2: write the string
  9963. oa->write_characters(
  9964. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  9965. j.m_value.string->size());
  9966. break;
  9967. }
  9968. case value_t::array:
  9969. {
  9970. // step 1: write control byte and the array size
  9971. const auto N = j.m_value.array->size();
  9972. if (N <= 0x17)
  9973. {
  9974. write_number(static_cast<std::uint8_t>(0x80 + N));
  9975. }
  9976. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  9977. {
  9978. oa->write_character(to_char_type(0x98));
  9979. write_number(static_cast<std::uint8_t>(N));
  9980. }
  9981. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  9982. {
  9983. oa->write_character(to_char_type(0x99));
  9984. write_number(static_cast<std::uint16_t>(N));
  9985. }
  9986. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  9987. {
  9988. oa->write_character(to_char_type(0x9A));
  9989. write_number(static_cast<std::uint32_t>(N));
  9990. }
  9991. // LCOV_EXCL_START
  9992. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  9993. {
  9994. oa->write_character(to_char_type(0x9B));
  9995. write_number(static_cast<std::uint64_t>(N));
  9996. }
  9997. // LCOV_EXCL_STOP
  9998. // step 2: write each element
  9999. for (const auto& el : *j.m_value.array)
  10000. {
  10001. write_cbor(el);
  10002. }
  10003. break;
  10004. }
  10005. case value_t::object:
  10006. {
  10007. // step 1: write control byte and the object size
  10008. const auto N = j.m_value.object->size();
  10009. if (N <= 0x17)
  10010. {
  10011. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10012. }
  10013. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10014. {
  10015. oa->write_character(to_char_type(0xB8));
  10016. write_number(static_cast<std::uint8_t>(N));
  10017. }
  10018. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10019. {
  10020. oa->write_character(to_char_type(0xB9));
  10021. write_number(static_cast<std::uint16_t>(N));
  10022. }
  10023. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10024. {
  10025. oa->write_character(to_char_type(0xBA));
  10026. write_number(static_cast<std::uint32_t>(N));
  10027. }
  10028. // LCOV_EXCL_START
  10029. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10030. {
  10031. oa->write_character(to_char_type(0xBB));
  10032. write_number(static_cast<std::uint64_t>(N));
  10033. }
  10034. // LCOV_EXCL_STOP
  10035. // step 2: write each element
  10036. for (const auto& el : *j.m_value.object)
  10037. {
  10038. write_cbor(el.first);
  10039. write_cbor(el.second);
  10040. }
  10041. break;
  10042. }
  10043. default:
  10044. break;
  10045. }
  10046. }
  10047. /*!
  10048. @param[in] j JSON value to serialize
  10049. */
  10050. void write_msgpack(const BasicJsonType& j)
  10051. {
  10052. switch (j.type())
  10053. {
  10054. case value_t::null: // nil
  10055. {
  10056. oa->write_character(to_char_type(0xC0));
  10057. break;
  10058. }
  10059. case value_t::boolean: // true and false
  10060. {
  10061. oa->write_character(j.m_value.boolean
  10062. ? to_char_type(0xC3)
  10063. : to_char_type(0xC2));
  10064. break;
  10065. }
  10066. case value_t::number_integer:
  10067. {
  10068. if (j.m_value.number_integer >= 0)
  10069. {
  10070. // MessagePack does not differentiate between positive
  10071. // signed integers and unsigned integers. Therefore, we used
  10072. // the code from the value_t::number_unsigned case here.
  10073. if (j.m_value.number_unsigned < 128)
  10074. {
  10075. // positive fixnum
  10076. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10077. }
  10078. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10079. {
  10080. // uint 8
  10081. oa->write_character(to_char_type(0xCC));
  10082. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10083. }
  10084. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10085. {
  10086. // uint 16
  10087. oa->write_character(to_char_type(0xCD));
  10088. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10089. }
  10090. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10091. {
  10092. // uint 32
  10093. oa->write_character(to_char_type(0xCE));
  10094. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10095. }
  10096. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10097. {
  10098. // uint 64
  10099. oa->write_character(to_char_type(0xCF));
  10100. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10101. }
  10102. }
  10103. else
  10104. {
  10105. if (j.m_value.number_integer >= -32)
  10106. {
  10107. // negative fixnum
  10108. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10109. }
  10110. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  10111. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10112. {
  10113. // int 8
  10114. oa->write_character(to_char_type(0xD0));
  10115. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  10116. }
  10117. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  10118. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10119. {
  10120. // int 16
  10121. oa->write_character(to_char_type(0xD1));
  10122. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  10123. }
  10124. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  10125. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10126. {
  10127. // int 32
  10128. oa->write_character(to_char_type(0xD2));
  10129. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  10130. }
  10131. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  10132. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  10133. {
  10134. // int 64
  10135. oa->write_character(to_char_type(0xD3));
  10136. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  10137. }
  10138. }
  10139. break;
  10140. }
  10141. case value_t::number_unsigned:
  10142. {
  10143. if (j.m_value.number_unsigned < 128)
  10144. {
  10145. // positive fixnum
  10146. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10147. }
  10148. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10149. {
  10150. // uint 8
  10151. oa->write_character(to_char_type(0xCC));
  10152. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10153. }
  10154. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10155. {
  10156. // uint 16
  10157. oa->write_character(to_char_type(0xCD));
  10158. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10159. }
  10160. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10161. {
  10162. // uint 32
  10163. oa->write_character(to_char_type(0xCE));
  10164. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10165. }
  10166. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  10167. {
  10168. // uint 64
  10169. oa->write_character(to_char_type(0xCF));
  10170. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10171. }
  10172. break;
  10173. }
  10174. case value_t::number_float:
  10175. {
  10176. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  10177. write_number(j.m_value.number_float);
  10178. break;
  10179. }
  10180. case value_t::string:
  10181. {
  10182. // step 1: write control byte and the string length
  10183. const auto N = j.m_value.string->size();
  10184. if (N <= 31)
  10185. {
  10186. // fixstr
  10187. write_number(static_cast<std::uint8_t>(0xA0 | N));
  10188. }
  10189. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10190. {
  10191. // str 8
  10192. oa->write_character(to_char_type(0xD9));
  10193. write_number(static_cast<std::uint8_t>(N));
  10194. }
  10195. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10196. {
  10197. // str 16
  10198. oa->write_character(to_char_type(0xDA));
  10199. write_number(static_cast<std::uint16_t>(N));
  10200. }
  10201. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10202. {
  10203. // str 32
  10204. oa->write_character(to_char_type(0xDB));
  10205. write_number(static_cast<std::uint32_t>(N));
  10206. }
  10207. // step 2: write the string
  10208. oa->write_characters(
  10209. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10210. j.m_value.string->size());
  10211. break;
  10212. }
  10213. case value_t::array:
  10214. {
  10215. // step 1: write control byte and the array size
  10216. const auto N = j.m_value.array->size();
  10217. if (N <= 15)
  10218. {
  10219. // fixarray
  10220. write_number(static_cast<std::uint8_t>(0x90 | N));
  10221. }
  10222. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10223. {
  10224. // array 16
  10225. oa->write_character(to_char_type(0xDC));
  10226. write_number(static_cast<std::uint16_t>(N));
  10227. }
  10228. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10229. {
  10230. // array 32
  10231. oa->write_character(to_char_type(0xDD));
  10232. write_number(static_cast<std::uint32_t>(N));
  10233. }
  10234. // step 2: write each element
  10235. for (const auto& el : *j.m_value.array)
  10236. {
  10237. write_msgpack(el);
  10238. }
  10239. break;
  10240. }
  10241. case value_t::object:
  10242. {
  10243. // step 1: write control byte and the object size
  10244. const auto N = j.m_value.object->size();
  10245. if (N <= 15)
  10246. {
  10247. // fixmap
  10248. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  10249. }
  10250. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10251. {
  10252. // map 16
  10253. oa->write_character(to_char_type(0xDE));
  10254. write_number(static_cast<std::uint16_t>(N));
  10255. }
  10256. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10257. {
  10258. // map 32
  10259. oa->write_character(to_char_type(0xDF));
  10260. write_number(static_cast<std::uint32_t>(N));
  10261. }
  10262. // step 2: write each element
  10263. for (const auto& el : *j.m_value.object)
  10264. {
  10265. write_msgpack(el.first);
  10266. write_msgpack(el.second);
  10267. }
  10268. break;
  10269. }
  10270. default:
  10271. break;
  10272. }
  10273. }
  10274. /*!
  10275. @param[in] j JSON value to serialize
  10276. @param[in] use_count whether to use '#' prefixes (optimized format)
  10277. @param[in] use_type whether to use '$' prefixes (optimized format)
  10278. @param[in] add_prefix whether prefixes need to be used for this value
  10279. */
  10280. void write_ubjson(const BasicJsonType& j, const bool use_count,
  10281. const bool use_type, const bool add_prefix = true)
  10282. {
  10283. switch (j.type())
  10284. {
  10285. case value_t::null:
  10286. {
  10287. if (add_prefix)
  10288. {
  10289. oa->write_character(to_char_type('Z'));
  10290. }
  10291. break;
  10292. }
  10293. case value_t::boolean:
  10294. {
  10295. if (add_prefix)
  10296. {
  10297. oa->write_character(j.m_value.boolean
  10298. ? to_char_type('T')
  10299. : to_char_type('F'));
  10300. }
  10301. break;
  10302. }
  10303. case value_t::number_integer:
  10304. {
  10305. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  10306. break;
  10307. }
  10308. case value_t::number_unsigned:
  10309. {
  10310. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  10311. break;
  10312. }
  10313. case value_t::number_float:
  10314. {
  10315. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  10316. break;
  10317. }
  10318. case value_t::string:
  10319. {
  10320. if (add_prefix)
  10321. {
  10322. oa->write_character(to_char_type('S'));
  10323. }
  10324. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  10325. oa->write_characters(
  10326. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10327. j.m_value.string->size());
  10328. break;
  10329. }
  10330. case value_t::array:
  10331. {
  10332. if (add_prefix)
  10333. {
  10334. oa->write_character(to_char_type('['));
  10335. }
  10336. bool prefix_required = true;
  10337. if (use_type and not j.m_value.array->empty())
  10338. {
  10339. assert(use_count);
  10340. const CharType first_prefix = ubjson_prefix(j.front());
  10341. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  10342. [this, first_prefix](const BasicJsonType & v)
  10343. {
  10344. return ubjson_prefix(v) == first_prefix;
  10345. });
  10346. if (same_prefix)
  10347. {
  10348. prefix_required = false;
  10349. oa->write_character(to_char_type('$'));
  10350. oa->write_character(first_prefix);
  10351. }
  10352. }
  10353. if (use_count)
  10354. {
  10355. oa->write_character(to_char_type('#'));
  10356. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  10357. }
  10358. for (const auto& el : *j.m_value.array)
  10359. {
  10360. write_ubjson(el, use_count, use_type, prefix_required);
  10361. }
  10362. if (not use_count)
  10363. {
  10364. oa->write_character(to_char_type(']'));
  10365. }
  10366. break;
  10367. }
  10368. case value_t::object:
  10369. {
  10370. if (add_prefix)
  10371. {
  10372. oa->write_character(to_char_type('{'));
  10373. }
  10374. bool prefix_required = true;
  10375. if (use_type and not j.m_value.object->empty())
  10376. {
  10377. assert(use_count);
  10378. const CharType first_prefix = ubjson_prefix(j.front());
  10379. const bool same_prefix = std::all_of(j.begin(), j.end(),
  10380. [this, first_prefix](const BasicJsonType & v)
  10381. {
  10382. return ubjson_prefix(v) == first_prefix;
  10383. });
  10384. if (same_prefix)
  10385. {
  10386. prefix_required = false;
  10387. oa->write_character(to_char_type('$'));
  10388. oa->write_character(first_prefix);
  10389. }
  10390. }
  10391. if (use_count)
  10392. {
  10393. oa->write_character(to_char_type('#'));
  10394. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  10395. }
  10396. for (const auto& el : *j.m_value.object)
  10397. {
  10398. write_number_with_ubjson_prefix(el.first.size(), true);
  10399. oa->write_characters(
  10400. reinterpret_cast<const CharType*>(el.first.c_str()),
  10401. el.first.size());
  10402. write_ubjson(el.second, use_count, use_type, prefix_required);
  10403. }
  10404. if (not use_count)
  10405. {
  10406. oa->write_character(to_char_type('}'));
  10407. }
  10408. break;
  10409. }
  10410. default:
  10411. break;
  10412. }
  10413. }
  10414. private:
  10415. //////////
  10416. // BSON //
  10417. //////////
  10418. /*!
  10419. @return The size of a BSON document entry header, including the id marker
  10420. and the entry name size (and its null-terminator).
  10421. */
  10422. static std::size_t calc_bson_entry_header_size(const string_t& name)
  10423. {
  10424. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  10425. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  10426. {
  10427. JSON_THROW(out_of_range::create(409,
  10428. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  10429. }
  10430. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  10431. }
  10432. /*!
  10433. @brief Writes the given @a element_type and @a name to the output adapter
  10434. */
  10435. void write_bson_entry_header(const string_t& name,
  10436. const std::uint8_t element_type)
  10437. {
  10438. oa->write_character(to_char_type(element_type)); // boolean
  10439. oa->write_characters(
  10440. reinterpret_cast<const CharType*>(name.c_str()),
  10441. name.size() + 1u);
  10442. }
  10443. /*!
  10444. @brief Writes a BSON element with key @a name and boolean value @a value
  10445. */
  10446. void write_bson_boolean(const string_t& name,
  10447. const bool value)
  10448. {
  10449. write_bson_entry_header(name, 0x08);
  10450. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  10451. }
  10452. /*!
  10453. @brief Writes a BSON element with key @a name and double value @a value
  10454. */
  10455. void write_bson_double(const string_t& name,
  10456. const double value)
  10457. {
  10458. write_bson_entry_header(name, 0x01);
  10459. write_number<double, true>(value);
  10460. }
  10461. /*!
  10462. @return The size of the BSON-encoded string in @a value
  10463. */
  10464. static std::size_t calc_bson_string_size(const string_t& value)
  10465. {
  10466. return sizeof(std::int32_t) + value.size() + 1ul;
  10467. }
  10468. /*!
  10469. @brief Writes a BSON element with key @a name and string value @a value
  10470. */
  10471. void write_bson_string(const string_t& name,
  10472. const string_t& value)
  10473. {
  10474. write_bson_entry_header(name, 0x02);
  10475. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  10476. oa->write_characters(
  10477. reinterpret_cast<const CharType*>(value.c_str()),
  10478. value.size() + 1);
  10479. }
  10480. /*!
  10481. @brief Writes a BSON element with key @a name and null value
  10482. */
  10483. void write_bson_null(const string_t& name)
  10484. {
  10485. write_bson_entry_header(name, 0x0A);
  10486. }
  10487. /*!
  10488. @return The size of the BSON-encoded integer @a value
  10489. */
  10490. static std::size_t calc_bson_integer_size(const std::int64_t value)
  10491. {
  10492. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  10493. ? sizeof(std::int32_t)
  10494. : sizeof(std::int64_t);
  10495. }
  10496. /*!
  10497. @brief Writes a BSON element with key @a name and integer @a value
  10498. */
  10499. void write_bson_integer(const string_t& name,
  10500. const std::int64_t value)
  10501. {
  10502. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  10503. {
  10504. write_bson_entry_header(name, 0x10); // int32
  10505. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10506. }
  10507. else
  10508. {
  10509. write_bson_entry_header(name, 0x12); // int64
  10510. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10511. }
  10512. }
  10513. /*!
  10514. @return The size of the BSON-encoded unsigned integer in @a j
  10515. */
  10516. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  10517. {
  10518. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10519. ? sizeof(std::int32_t)
  10520. : sizeof(std::int64_t);
  10521. }
  10522. /*!
  10523. @brief Writes a BSON element with key @a name and unsigned @a value
  10524. */
  10525. void write_bson_unsigned(const string_t& name,
  10526. const std::uint64_t value)
  10527. {
  10528. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10529. {
  10530. write_bson_entry_header(name, 0x10 /* int32 */);
  10531. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  10532. }
  10533. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10534. {
  10535. write_bson_entry_header(name, 0x12 /* int64 */);
  10536. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  10537. }
  10538. else
  10539. {
  10540. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  10541. }
  10542. }
  10543. /*!
  10544. @brief Writes a BSON element with key @a name and object @a value
  10545. */
  10546. void write_bson_object_entry(const string_t& name,
  10547. const typename BasicJsonType::object_t& value)
  10548. {
  10549. write_bson_entry_header(name, 0x03); // object
  10550. write_bson_object(value);
  10551. }
  10552. /*!
  10553. @return The size of the BSON-encoded array @a value
  10554. */
  10555. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  10556. {
  10557. std::size_t array_index = 0ul;
  10558. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), 0ul, [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  10559. {
  10560. return result + calc_bson_element_size(std::to_string(array_index++), el);
  10561. });
  10562. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  10563. }
  10564. /*!
  10565. @brief Writes a BSON element with key @a name and array @a value
  10566. */
  10567. void write_bson_array(const string_t& name,
  10568. const typename BasicJsonType::array_t& value)
  10569. {
  10570. write_bson_entry_header(name, 0x04); // array
  10571. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  10572. std::size_t array_index = 0ul;
  10573. for (const auto& el : value)
  10574. {
  10575. write_bson_element(std::to_string(array_index++), el);
  10576. }
  10577. oa->write_character(to_char_type(0x00));
  10578. }
  10579. /*!
  10580. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  10581. @return The calculated size for the BSON document entry for @a j with the given @a name.
  10582. */
  10583. static std::size_t calc_bson_element_size(const string_t& name,
  10584. const BasicJsonType& j)
  10585. {
  10586. const auto header_size = calc_bson_entry_header_size(name);
  10587. switch (j.type())
  10588. {
  10589. case value_t::object:
  10590. return header_size + calc_bson_object_size(*j.m_value.object);
  10591. case value_t::array:
  10592. return header_size + calc_bson_array_size(*j.m_value.array);
  10593. case value_t::boolean:
  10594. return header_size + 1ul;
  10595. case value_t::number_float:
  10596. return header_size + 8ul;
  10597. case value_t::number_integer:
  10598. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  10599. case value_t::number_unsigned:
  10600. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  10601. case value_t::string:
  10602. return header_size + calc_bson_string_size(*j.m_value.string);
  10603. case value_t::null:
  10604. return header_size + 0ul;
  10605. // LCOV_EXCL_START
  10606. default:
  10607. assert(false);
  10608. return 0ul;
  10609. // LCOV_EXCL_STOP
  10610. }
  10611. }
  10612. /*!
  10613. @brief Serializes the JSON value @a j to BSON and associates it with the
  10614. key @a name.
  10615. @param name The name to associate with the JSON entity @a j within the
  10616. current BSON document
  10617. @return The size of the BSON entry
  10618. */
  10619. void write_bson_element(const string_t& name,
  10620. const BasicJsonType& j)
  10621. {
  10622. switch (j.type())
  10623. {
  10624. case value_t::object:
  10625. return write_bson_object_entry(name, *j.m_value.object);
  10626. case value_t::array:
  10627. return write_bson_array(name, *j.m_value.array);
  10628. case value_t::boolean:
  10629. return write_bson_boolean(name, j.m_value.boolean);
  10630. case value_t::number_float:
  10631. return write_bson_double(name, j.m_value.number_float);
  10632. case value_t::number_integer:
  10633. return write_bson_integer(name, j.m_value.number_integer);
  10634. case value_t::number_unsigned:
  10635. return write_bson_unsigned(name, j.m_value.number_unsigned);
  10636. case value_t::string:
  10637. return write_bson_string(name, *j.m_value.string);
  10638. case value_t::null:
  10639. return write_bson_null(name);
  10640. // LCOV_EXCL_START
  10641. default:
  10642. assert(false);
  10643. return;
  10644. // LCOV_EXCL_STOP
  10645. }
  10646. }
  10647. /*!
  10648. @brief Calculates the size of the BSON serialization of the given
  10649. JSON-object @a j.
  10650. @param[in] j JSON value to serialize
  10651. @pre j.type() == value_t::object
  10652. */
  10653. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  10654. {
  10655. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  10656. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  10657. {
  10658. return result += calc_bson_element_size(el.first, el.second);
  10659. });
  10660. return sizeof(std::int32_t) + document_size + 1ul;
  10661. }
  10662. /*!
  10663. @param[in] j JSON value to serialize
  10664. @pre j.type() == value_t::object
  10665. */
  10666. void write_bson_object(const typename BasicJsonType::object_t& value)
  10667. {
  10668. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  10669. for (const auto& el : value)
  10670. {
  10671. write_bson_element(el.first, el.second);
  10672. }
  10673. oa->write_character(to_char_type(0x00));
  10674. }
  10675. //////////
  10676. // CBOR //
  10677. //////////
  10678. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  10679. {
  10680. return to_char_type(0xFA); // Single-Precision Float
  10681. }
  10682. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  10683. {
  10684. return to_char_type(0xFB); // Double-Precision Float
  10685. }
  10686. /////////////
  10687. // MsgPack //
  10688. /////////////
  10689. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  10690. {
  10691. return to_char_type(0xCA); // float 32
  10692. }
  10693. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  10694. {
  10695. return to_char_type(0xCB); // float 64
  10696. }
  10697. ////////////
  10698. // UBJSON //
  10699. ////////////
  10700. // UBJSON: write number (floating point)
  10701. template<typename NumberType, typename std::enable_if<
  10702. std::is_floating_point<NumberType>::value, int>::type = 0>
  10703. void write_number_with_ubjson_prefix(const NumberType n,
  10704. const bool add_prefix)
  10705. {
  10706. if (add_prefix)
  10707. {
  10708. oa->write_character(get_ubjson_float_prefix(n));
  10709. }
  10710. write_number(n);
  10711. }
  10712. // UBJSON: write number (unsigned integer)
  10713. template<typename NumberType, typename std::enable_if<
  10714. std::is_unsigned<NumberType>::value, int>::type = 0>
  10715. void write_number_with_ubjson_prefix(const NumberType n,
  10716. const bool add_prefix)
  10717. {
  10718. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10719. {
  10720. if (add_prefix)
  10721. {
  10722. oa->write_character(to_char_type('i')); // int8
  10723. }
  10724. write_number(static_cast<std::uint8_t>(n));
  10725. }
  10726. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  10727. {
  10728. if (add_prefix)
  10729. {
  10730. oa->write_character(to_char_type('U')); // uint8
  10731. }
  10732. write_number(static_cast<std::uint8_t>(n));
  10733. }
  10734. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10735. {
  10736. if (add_prefix)
  10737. {
  10738. oa->write_character(to_char_type('I')); // int16
  10739. }
  10740. write_number(static_cast<std::int16_t>(n));
  10741. }
  10742. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10743. {
  10744. if (add_prefix)
  10745. {
  10746. oa->write_character(to_char_type('l')); // int32
  10747. }
  10748. write_number(static_cast<std::int32_t>(n));
  10749. }
  10750. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  10751. {
  10752. if (add_prefix)
  10753. {
  10754. oa->write_character(to_char_type('L')); // int64
  10755. }
  10756. write_number(static_cast<std::int64_t>(n));
  10757. }
  10758. else
  10759. {
  10760. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10761. }
  10762. }
  10763. // UBJSON: write number (signed integer)
  10764. template<typename NumberType, typename std::enable_if<
  10765. std::is_signed<NumberType>::value and
  10766. not std::is_floating_point<NumberType>::value, int>::type = 0>
  10767. void write_number_with_ubjson_prefix(const NumberType n,
  10768. const bool add_prefix)
  10769. {
  10770. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  10771. {
  10772. if (add_prefix)
  10773. {
  10774. oa->write_character(to_char_type('i')); // int8
  10775. }
  10776. write_number(static_cast<std::int8_t>(n));
  10777. }
  10778. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10779. {
  10780. if (add_prefix)
  10781. {
  10782. oa->write_character(to_char_type('U')); // uint8
  10783. }
  10784. write_number(static_cast<std::uint8_t>(n));
  10785. }
  10786. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  10787. {
  10788. if (add_prefix)
  10789. {
  10790. oa->write_character(to_char_type('I')); // int16
  10791. }
  10792. write_number(static_cast<std::int16_t>(n));
  10793. }
  10794. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  10795. {
  10796. if (add_prefix)
  10797. {
  10798. oa->write_character(to_char_type('l')); // int32
  10799. }
  10800. write_number(static_cast<std::int32_t>(n));
  10801. }
  10802. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  10803. {
  10804. if (add_prefix)
  10805. {
  10806. oa->write_character(to_char_type('L')); // int64
  10807. }
  10808. write_number(static_cast<std::int64_t>(n));
  10809. }
  10810. // LCOV_EXCL_START
  10811. else
  10812. {
  10813. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  10814. }
  10815. // LCOV_EXCL_STOP
  10816. }
  10817. /*!
  10818. @brief determine the type prefix of container values
  10819. @note This function does not need to be 100% accurate when it comes to
  10820. integer limits. In case a number exceeds the limits of int64_t,
  10821. this will be detected by a later call to function
  10822. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  10823. value that does not fit the previous limits.
  10824. */
  10825. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  10826. {
  10827. switch (j.type())
  10828. {
  10829. case value_t::null:
  10830. return 'Z';
  10831. case value_t::boolean:
  10832. return j.m_value.boolean ? 'T' : 'F';
  10833. case value_t::number_integer:
  10834. {
  10835. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  10836. {
  10837. return 'i';
  10838. }
  10839. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10840. {
  10841. return 'U';
  10842. }
  10843. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  10844. {
  10845. return 'I';
  10846. }
  10847. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  10848. {
  10849. return 'l';
  10850. }
  10851. // no check and assume int64_t (see note above)
  10852. return 'L';
  10853. }
  10854. case value_t::number_unsigned:
  10855. {
  10856. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  10857. {
  10858. return 'i';
  10859. }
  10860. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  10861. {
  10862. return 'U';
  10863. }
  10864. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  10865. {
  10866. return 'I';
  10867. }
  10868. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  10869. {
  10870. return 'l';
  10871. }
  10872. // no check and assume int64_t (see note above)
  10873. return 'L';
  10874. }
  10875. case value_t::number_float:
  10876. return get_ubjson_float_prefix(j.m_value.number_float);
  10877. case value_t::string:
  10878. return 'S';
  10879. case value_t::array:
  10880. return '[';
  10881. case value_t::object:
  10882. return '{';
  10883. default: // discarded values
  10884. return 'N';
  10885. }
  10886. }
  10887. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  10888. {
  10889. return 'd'; // float 32
  10890. }
  10891. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  10892. {
  10893. return 'D'; // float 64
  10894. }
  10895. ///////////////////////
  10896. // Utility functions //
  10897. ///////////////////////
  10898. /*
  10899. @brief write a number to output input
  10900. @param[in] n number of type @a NumberType
  10901. @tparam NumberType the type of the number
  10902. @tparam OutputIsLittleEndian Set to true if output data is
  10903. required to be little endian
  10904. @note This function needs to respect the system's endianess, because bytes
  10905. in CBOR, MessagePack, and UBJSON are stored in network order (big
  10906. endian) and therefore need reordering on little endian systems.
  10907. */
  10908. template<typename NumberType, bool OutputIsLittleEndian = false>
  10909. void write_number(const NumberType n)
  10910. {
  10911. // step 1: write number to array of length NumberType
  10912. std::array<CharType, sizeof(NumberType)> vec;
  10913. std::memcpy(vec.data(), &n, sizeof(NumberType));
  10914. // step 2: write array to output (with possible reordering)
  10915. if (is_little_endian != OutputIsLittleEndian)
  10916. {
  10917. // reverse byte order prior to conversion if necessary
  10918. std::reverse(vec.begin(), vec.end());
  10919. }
  10920. oa->write_characters(vec.data(), sizeof(NumberType));
  10921. }
  10922. public:
  10923. // The following to_char_type functions are implement the conversion
  10924. // between uint8_t and CharType. In case CharType is not unsigned,
  10925. // such a conversion is required to allow values greater than 128.
  10926. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  10927. template < typename C = CharType,
  10928. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  10929. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10930. {
  10931. return *reinterpret_cast<char*>(&x);
  10932. }
  10933. template < typename C = CharType,
  10934. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  10935. static CharType to_char_type(std::uint8_t x) noexcept
  10936. {
  10937. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  10938. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  10939. CharType result;
  10940. std::memcpy(&result, &x, sizeof(x));
  10941. return result;
  10942. }
  10943. template<typename C = CharType,
  10944. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  10945. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  10946. {
  10947. return x;
  10948. }
  10949. template < typename InputCharType, typename C = CharType,
  10950. enable_if_t <
  10951. std::is_signed<C>::value and
  10952. std::is_signed<char>::value and
  10953. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  10954. > * = nullptr >
  10955. static constexpr CharType to_char_type(InputCharType x) noexcept
  10956. {
  10957. return x;
  10958. }
  10959. private:
  10960. /// whether we can assume little endianess
  10961. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  10962. /// the output
  10963. output_adapter_t<CharType> oa = nullptr;
  10964. };
  10965. } // namespace detail
  10966. } // namespace nlohmann
  10967. // #include <nlohmann/detail/output/output_adapters.hpp>
  10968. // #include <nlohmann/detail/output/serializer.hpp>
  10969. #include <algorithm> // reverse, remove, fill, find, none_of
  10970. #include <array> // array
  10971. #include <cassert> // assert
  10972. #include <ciso646> // and, or
  10973. #include <clocale> // localeconv, lconv
  10974. #include <cmath> // labs, isfinite, isnan, signbit
  10975. #include <cstddef> // size_t, ptrdiff_t
  10976. #include <cstdint> // uint8_t
  10977. #include <cstdio> // snprintf
  10978. #include <limits> // numeric_limits
  10979. #include <string> // string
  10980. #include <type_traits> // is_same
  10981. #include <utility> // move
  10982. // #include <nlohmann/detail/conversions/to_chars.hpp>
  10983. #include <array> // array
  10984. #include <cassert> // assert
  10985. #include <ciso646> // or, and, not
  10986. #include <cmath> // signbit, isfinite
  10987. #include <cstdint> // intN_t, uintN_t
  10988. #include <cstring> // memcpy, memmove
  10989. #include <limits> // numeric_limits
  10990. #include <type_traits> // conditional
  10991. // #include <nlohmann/detail/macro_scope.hpp>
  10992. namespace nlohmann
  10993. {
  10994. namespace detail
  10995. {
  10996. /*!
  10997. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  10998. conversion.
  10999. This implementation is a slightly modified version of the reference
  11000. implementation which may be obtained from
  11001. http://florian.loitsch.com/publications (bench.tar.gz).
  11002. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  11003. For a detailed description of the algorithm see:
  11004. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  11005. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  11006. Language Design and Implementation, PLDI 2010
  11007. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  11008. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  11009. Design and Implementation, PLDI 1996
  11010. */
  11011. namespace dtoa_impl
  11012. {
  11013. template <typename Target, typename Source>
  11014. Target reinterpret_bits(const Source source)
  11015. {
  11016. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  11017. Target target;
  11018. std::memcpy(&target, &source, sizeof(Source));
  11019. return target;
  11020. }
  11021. struct diyfp // f * 2^e
  11022. {
  11023. static constexpr int kPrecision = 64; // = q
  11024. std::uint64_t f = 0;
  11025. int e = 0;
  11026. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  11027. /*!
  11028. @brief returns x - y
  11029. @pre x.e == y.e and x.f >= y.f
  11030. */
  11031. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  11032. {
  11033. assert(x.e == y.e);
  11034. assert(x.f >= y.f);
  11035. return {x.f - y.f, x.e};
  11036. }
  11037. /*!
  11038. @brief returns x * y
  11039. @note The result is rounded. (Only the upper q bits are returned.)
  11040. */
  11041. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  11042. {
  11043. static_assert(kPrecision == 64, "internal error");
  11044. // Computes:
  11045. // f = round((x.f * y.f) / 2^q)
  11046. // e = x.e + y.e + q
  11047. // Emulate the 64-bit * 64-bit multiplication:
  11048. //
  11049. // p = u * v
  11050. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  11051. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  11052. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  11053. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  11054. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  11055. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  11056. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  11057. //
  11058. // (Since Q might be larger than 2^32 - 1)
  11059. //
  11060. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  11061. //
  11062. // (Q_hi + H does not overflow a 64-bit int)
  11063. //
  11064. // = p_lo + 2^64 p_hi
  11065. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  11066. const std::uint64_t u_hi = x.f >> 32u;
  11067. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  11068. const std::uint64_t v_hi = y.f >> 32u;
  11069. const std::uint64_t p0 = u_lo * v_lo;
  11070. const std::uint64_t p1 = u_lo * v_hi;
  11071. const std::uint64_t p2 = u_hi * v_lo;
  11072. const std::uint64_t p3 = u_hi * v_hi;
  11073. const std::uint64_t p0_hi = p0 >> 32u;
  11074. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  11075. const std::uint64_t p1_hi = p1 >> 32u;
  11076. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  11077. const std::uint64_t p2_hi = p2 >> 32u;
  11078. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  11079. // The full product might now be computed as
  11080. //
  11081. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  11082. // p_lo = p0_lo + (Q << 32)
  11083. //
  11084. // But in this particular case here, the full p_lo is not required.
  11085. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  11086. // Q_hi + 1 does not overflow).
  11087. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  11088. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  11089. return {h, x.e + y.e + 64};
  11090. }
  11091. /*!
  11092. @brief normalize x such that the significand is >= 2^(q-1)
  11093. @pre x.f != 0
  11094. */
  11095. static diyfp normalize(diyfp x) noexcept
  11096. {
  11097. assert(x.f != 0);
  11098. while ((x.f >> 63u) == 0)
  11099. {
  11100. x.f <<= 1u;
  11101. x.e--;
  11102. }
  11103. return x;
  11104. }
  11105. /*!
  11106. @brief normalize x such that the result has the exponent E
  11107. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  11108. */
  11109. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  11110. {
  11111. const int delta = x.e - target_exponent;
  11112. assert(delta >= 0);
  11113. assert(((x.f << delta) >> delta) == x.f);
  11114. return {x.f << delta, target_exponent};
  11115. }
  11116. };
  11117. struct boundaries
  11118. {
  11119. diyfp w;
  11120. diyfp minus;
  11121. diyfp plus;
  11122. };
  11123. /*!
  11124. Compute the (normalized) diyfp representing the input number 'value' and its
  11125. boundaries.
  11126. @pre value must be finite and positive
  11127. */
  11128. template <typename FloatType>
  11129. boundaries compute_boundaries(FloatType value)
  11130. {
  11131. assert(std::isfinite(value));
  11132. assert(value > 0);
  11133. // Convert the IEEE representation into a diyfp.
  11134. //
  11135. // If v is denormal:
  11136. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  11137. // If v is normalized:
  11138. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  11139. static_assert(std::numeric_limits<FloatType>::is_iec559,
  11140. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  11141. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  11142. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  11143. constexpr int kMinExp = 1 - kBias;
  11144. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  11145. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  11146. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  11147. const std::uint64_t E = bits >> (kPrecision - 1);
  11148. const std::uint64_t F = bits & (kHiddenBit - 1);
  11149. const bool is_denormal = E == 0;
  11150. const diyfp v = is_denormal
  11151. ? diyfp(F, kMinExp)
  11152. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  11153. // Compute the boundaries m- and m+ of the floating-point value
  11154. // v = f * 2^e.
  11155. //
  11156. // Determine v- and v+, the floating-point predecessor and successor if v,
  11157. // respectively.
  11158. //
  11159. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  11160. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  11161. //
  11162. // v+ = v + 2^e
  11163. //
  11164. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  11165. // between m- and m+ round to v, regardless of how the input rounding
  11166. // algorithm breaks ties.
  11167. //
  11168. // ---+-------------+-------------+-------------+-------------+--- (A)
  11169. // v- m- v m+ v+
  11170. //
  11171. // -----------------+------+------+-------------+-------------+--- (B)
  11172. // v- m- v m+ v+
  11173. const bool lower_boundary_is_closer = F == 0 and E > 1;
  11174. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  11175. const diyfp m_minus = lower_boundary_is_closer
  11176. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  11177. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  11178. // Determine the normalized w+ = m+.
  11179. const diyfp w_plus = diyfp::normalize(m_plus);
  11180. // Determine w- = m- such that e_(w-) = e_(w+).
  11181. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  11182. return {diyfp::normalize(v), w_minus, w_plus};
  11183. }
  11184. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  11185. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  11186. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  11187. //
  11188. // alpha <= e = e_c + e_w + q <= gamma
  11189. //
  11190. // or
  11191. //
  11192. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  11193. // <= f_c * f_w * 2^gamma
  11194. //
  11195. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  11196. //
  11197. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  11198. //
  11199. // or
  11200. //
  11201. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  11202. //
  11203. // The choice of (alpha,gamma) determines the size of the table and the form of
  11204. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  11205. // in practice:
  11206. //
  11207. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  11208. // processed independently: An integral part p1, and a fractional part p2:
  11209. //
  11210. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  11211. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  11212. // = p1 + p2 * 2^e
  11213. //
  11214. // The conversion of p1 into decimal form requires a series of divisions and
  11215. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  11216. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  11217. // achieved by choosing
  11218. //
  11219. // -e >= 32 or e <= -32 := gamma
  11220. //
  11221. // In order to convert the fractional part
  11222. //
  11223. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11224. //
  11225. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  11226. // d[-i] are extracted in order:
  11227. //
  11228. // (10 * p2) div 2^-e = d[-1]
  11229. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  11230. //
  11231. // The multiplication by 10 must not overflow. It is sufficient to choose
  11232. //
  11233. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  11234. //
  11235. // Since p2 = f mod 2^-e < 2^-e,
  11236. //
  11237. // -e <= 60 or e >= -60 := alpha
  11238. constexpr int kAlpha = -60;
  11239. constexpr int kGamma = -32;
  11240. struct cached_power // c = f * 2^e ~= 10^k
  11241. {
  11242. std::uint64_t f;
  11243. int e;
  11244. int k;
  11245. };
  11246. /*!
  11247. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  11248. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  11249. satisfies (Definition 3.2 from [1])
  11250. alpha <= e_c + e + q <= gamma.
  11251. */
  11252. inline cached_power get_cached_power_for_binary_exponent(int e)
  11253. {
  11254. // Now
  11255. //
  11256. // alpha <= e_c + e + q <= gamma (1)
  11257. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  11258. //
  11259. // and since the c's are normalized, 2^(q-1) <= f_c,
  11260. //
  11261. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  11262. // ==> 2^(alpha - e - 1) <= c
  11263. //
  11264. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  11265. //
  11266. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  11267. // = ceil( (alpha - e - 1) * log_10(2) )
  11268. //
  11269. // From the paper:
  11270. // "In theory the result of the procedure could be wrong since c is rounded,
  11271. // and the computation itself is approximated [...]. In practice, however,
  11272. // this simple function is sufficient."
  11273. //
  11274. // For IEEE double precision floating-point numbers converted into
  11275. // normalized diyfp's w = f * 2^e, with q = 64,
  11276. //
  11277. // e >= -1022 (min IEEE exponent)
  11278. // -52 (p - 1)
  11279. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  11280. // -11 (normalize the diyfp)
  11281. // = -1137
  11282. //
  11283. // and
  11284. //
  11285. // e <= +1023 (max IEEE exponent)
  11286. // -52 (p - 1)
  11287. // -11 (normalize the diyfp)
  11288. // = 960
  11289. //
  11290. // This binary exponent range [-1137,960] results in a decimal exponent
  11291. // range [-307,324]. One does not need to store a cached power for each
  11292. // k in this range. For each such k it suffices to find a cached power
  11293. // such that the exponent of the product lies in [alpha,gamma].
  11294. // This implies that the difference of the decimal exponents of adjacent
  11295. // table entries must be less than or equal to
  11296. //
  11297. // floor( (gamma - alpha) * log_10(2) ) = 8.
  11298. //
  11299. // (A smaller distance gamma-alpha would require a larger table.)
  11300. // NB:
  11301. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  11302. constexpr int kCachedPowersMinDecExp = -300;
  11303. constexpr int kCachedPowersDecStep = 8;
  11304. static constexpr std::array<cached_power, 79> kCachedPowers =
  11305. {
  11306. {
  11307. { 0xAB70FE17C79AC6CA, -1060, -300 },
  11308. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  11309. { 0xBE5691EF416BD60C, -1007, -284 },
  11310. { 0x8DD01FAD907FFC3C, -980, -276 },
  11311. { 0xD3515C2831559A83, -954, -268 },
  11312. { 0x9D71AC8FADA6C9B5, -927, -260 },
  11313. { 0xEA9C227723EE8BCB, -901, -252 },
  11314. { 0xAECC49914078536D, -874, -244 },
  11315. { 0x823C12795DB6CE57, -847, -236 },
  11316. { 0xC21094364DFB5637, -821, -228 },
  11317. { 0x9096EA6F3848984F, -794, -220 },
  11318. { 0xD77485CB25823AC7, -768, -212 },
  11319. { 0xA086CFCD97BF97F4, -741, -204 },
  11320. { 0xEF340A98172AACE5, -715, -196 },
  11321. { 0xB23867FB2A35B28E, -688, -188 },
  11322. { 0x84C8D4DFD2C63F3B, -661, -180 },
  11323. { 0xC5DD44271AD3CDBA, -635, -172 },
  11324. { 0x936B9FCEBB25C996, -608, -164 },
  11325. { 0xDBAC6C247D62A584, -582, -156 },
  11326. { 0xA3AB66580D5FDAF6, -555, -148 },
  11327. { 0xF3E2F893DEC3F126, -529, -140 },
  11328. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  11329. { 0x87625F056C7C4A8B, -475, -124 },
  11330. { 0xC9BCFF6034C13053, -449, -116 },
  11331. { 0x964E858C91BA2655, -422, -108 },
  11332. { 0xDFF9772470297EBD, -396, -100 },
  11333. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  11334. { 0xF8A95FCF88747D94, -343, -84 },
  11335. { 0xB94470938FA89BCF, -316, -76 },
  11336. { 0x8A08F0F8BF0F156B, -289, -68 },
  11337. { 0xCDB02555653131B6, -263, -60 },
  11338. { 0x993FE2C6D07B7FAC, -236, -52 },
  11339. { 0xE45C10C42A2B3B06, -210, -44 },
  11340. { 0xAA242499697392D3, -183, -36 },
  11341. { 0xFD87B5F28300CA0E, -157, -28 },
  11342. { 0xBCE5086492111AEB, -130, -20 },
  11343. { 0x8CBCCC096F5088CC, -103, -12 },
  11344. { 0xD1B71758E219652C, -77, -4 },
  11345. { 0x9C40000000000000, -50, 4 },
  11346. { 0xE8D4A51000000000, -24, 12 },
  11347. { 0xAD78EBC5AC620000, 3, 20 },
  11348. { 0x813F3978F8940984, 30, 28 },
  11349. { 0xC097CE7BC90715B3, 56, 36 },
  11350. { 0x8F7E32CE7BEA5C70, 83, 44 },
  11351. { 0xD5D238A4ABE98068, 109, 52 },
  11352. { 0x9F4F2726179A2245, 136, 60 },
  11353. { 0xED63A231D4C4FB27, 162, 68 },
  11354. { 0xB0DE65388CC8ADA8, 189, 76 },
  11355. { 0x83C7088E1AAB65DB, 216, 84 },
  11356. { 0xC45D1DF942711D9A, 242, 92 },
  11357. { 0x924D692CA61BE758, 269, 100 },
  11358. { 0xDA01EE641A708DEA, 295, 108 },
  11359. { 0xA26DA3999AEF774A, 322, 116 },
  11360. { 0xF209787BB47D6B85, 348, 124 },
  11361. { 0xB454E4A179DD1877, 375, 132 },
  11362. { 0x865B86925B9BC5C2, 402, 140 },
  11363. { 0xC83553C5C8965D3D, 428, 148 },
  11364. { 0x952AB45CFA97A0B3, 455, 156 },
  11365. { 0xDE469FBD99A05FE3, 481, 164 },
  11366. { 0xA59BC234DB398C25, 508, 172 },
  11367. { 0xF6C69A72A3989F5C, 534, 180 },
  11368. { 0xB7DCBF5354E9BECE, 561, 188 },
  11369. { 0x88FCF317F22241E2, 588, 196 },
  11370. { 0xCC20CE9BD35C78A5, 614, 204 },
  11371. { 0x98165AF37B2153DF, 641, 212 },
  11372. { 0xE2A0B5DC971F303A, 667, 220 },
  11373. { 0xA8D9D1535CE3B396, 694, 228 },
  11374. { 0xFB9B7CD9A4A7443C, 720, 236 },
  11375. { 0xBB764C4CA7A44410, 747, 244 },
  11376. { 0x8BAB8EEFB6409C1A, 774, 252 },
  11377. { 0xD01FEF10A657842C, 800, 260 },
  11378. { 0x9B10A4E5E9913129, 827, 268 },
  11379. { 0xE7109BFBA19C0C9D, 853, 276 },
  11380. { 0xAC2820D9623BF429, 880, 284 },
  11381. { 0x80444B5E7AA7CF85, 907, 292 },
  11382. { 0xBF21E44003ACDD2D, 933, 300 },
  11383. { 0x8E679C2F5E44FF8F, 960, 308 },
  11384. { 0xD433179D9C8CB841, 986, 316 },
  11385. { 0x9E19DB92B4E31BA9, 1013, 324 },
  11386. }
  11387. };
  11388. // This computation gives exactly the same results for k as
  11389. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  11390. // for |e| <= 1500, but doesn't require floating-point operations.
  11391. // NB: log_10(2) ~= 78913 / 2^18
  11392. assert(e >= -1500);
  11393. assert(e <= 1500);
  11394. const int f = kAlpha - e - 1;
  11395. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  11396. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  11397. assert(index >= 0);
  11398. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  11399. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  11400. assert(kAlpha <= cached.e + e + 64);
  11401. assert(kGamma >= cached.e + e + 64);
  11402. return cached;
  11403. }
  11404. /*!
  11405. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  11406. For n == 0, returns 1 and sets pow10 := 1.
  11407. */
  11408. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  11409. {
  11410. // LCOV_EXCL_START
  11411. if (n >= 1000000000)
  11412. {
  11413. pow10 = 1000000000;
  11414. return 10;
  11415. }
  11416. // LCOV_EXCL_STOP
  11417. else if (n >= 100000000)
  11418. {
  11419. pow10 = 100000000;
  11420. return 9;
  11421. }
  11422. else if (n >= 10000000)
  11423. {
  11424. pow10 = 10000000;
  11425. return 8;
  11426. }
  11427. else if (n >= 1000000)
  11428. {
  11429. pow10 = 1000000;
  11430. return 7;
  11431. }
  11432. else if (n >= 100000)
  11433. {
  11434. pow10 = 100000;
  11435. return 6;
  11436. }
  11437. else if (n >= 10000)
  11438. {
  11439. pow10 = 10000;
  11440. return 5;
  11441. }
  11442. else if (n >= 1000)
  11443. {
  11444. pow10 = 1000;
  11445. return 4;
  11446. }
  11447. else if (n >= 100)
  11448. {
  11449. pow10 = 100;
  11450. return 3;
  11451. }
  11452. else if (n >= 10)
  11453. {
  11454. pow10 = 10;
  11455. return 2;
  11456. }
  11457. else
  11458. {
  11459. pow10 = 1;
  11460. return 1;
  11461. }
  11462. }
  11463. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  11464. std::uint64_t rest, std::uint64_t ten_k)
  11465. {
  11466. assert(len >= 1);
  11467. assert(dist <= delta);
  11468. assert(rest <= delta);
  11469. assert(ten_k > 0);
  11470. // <--------------------------- delta ---->
  11471. // <---- dist --------->
  11472. // --------------[------------------+-------------------]--------------
  11473. // M- w M+
  11474. //
  11475. // ten_k
  11476. // <------>
  11477. // <---- rest ---->
  11478. // --------------[------------------+----+--------------]--------------
  11479. // w V
  11480. // = buf * 10^k
  11481. //
  11482. // ten_k represents a unit-in-the-last-place in the decimal representation
  11483. // stored in buf.
  11484. // Decrement buf by ten_k while this takes buf closer to w.
  11485. // The tests are written in this order to avoid overflow in unsigned
  11486. // integer arithmetic.
  11487. while (rest < dist
  11488. and delta - rest >= ten_k
  11489. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  11490. {
  11491. assert(buf[len - 1] != '0');
  11492. buf[len - 1]--;
  11493. rest += ten_k;
  11494. }
  11495. }
  11496. /*!
  11497. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  11498. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  11499. */
  11500. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  11501. diyfp M_minus, diyfp w, diyfp M_plus)
  11502. {
  11503. static_assert(kAlpha >= -60, "internal error");
  11504. static_assert(kGamma <= -32, "internal error");
  11505. // Generates the digits (and the exponent) of a decimal floating-point
  11506. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  11507. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  11508. //
  11509. // <--------------------------- delta ---->
  11510. // <---- dist --------->
  11511. // --------------[------------------+-------------------]--------------
  11512. // M- w M+
  11513. //
  11514. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  11515. // V is in [M-,M+].
  11516. assert(M_plus.e >= kAlpha);
  11517. assert(M_plus.e <= kGamma);
  11518. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  11519. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  11520. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  11521. //
  11522. // M+ = f * 2^e
  11523. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  11524. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  11525. // = p1 + p2 * 2^e
  11526. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  11527. auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
  11528. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  11529. // 1)
  11530. //
  11531. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  11532. assert(p1 > 0);
  11533. std::uint32_t pow10;
  11534. const int k = find_largest_pow10(p1, pow10);
  11535. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  11536. //
  11537. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  11538. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  11539. //
  11540. // M+ = p1 + p2 * 2^e
  11541. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  11542. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  11543. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  11544. //
  11545. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  11546. //
  11547. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  11548. //
  11549. // but stop as soon as
  11550. //
  11551. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  11552. int n = k;
  11553. while (n > 0)
  11554. {
  11555. // Invariants:
  11556. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  11557. // pow10 = 10^(n-1) <= p1 < 10^n
  11558. //
  11559. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  11560. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  11561. //
  11562. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  11563. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  11564. //
  11565. assert(d <= 9);
  11566. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11567. //
  11568. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  11569. //
  11570. p1 = r;
  11571. n--;
  11572. //
  11573. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  11574. // pow10 = 10^n
  11575. //
  11576. // Now check if enough digits have been generated.
  11577. // Compute
  11578. //
  11579. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  11580. //
  11581. // Note:
  11582. // Since rest and delta share the same exponent e, it suffices to
  11583. // compare the significands.
  11584. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  11585. if (rest <= delta)
  11586. {
  11587. // V = buffer * 10^n, with M- <= V <= M+.
  11588. decimal_exponent += n;
  11589. // We may now just stop. But instead look if the buffer could be
  11590. // decremented to bring V closer to w.
  11591. //
  11592. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  11593. // The rounding procedure works with diyfp's with an implicit
  11594. // exponent of e.
  11595. //
  11596. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  11597. //
  11598. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  11599. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  11600. return;
  11601. }
  11602. pow10 /= 10;
  11603. //
  11604. // pow10 = 10^(n-1) <= p1 < 10^n
  11605. // Invariants restored.
  11606. }
  11607. // 2)
  11608. //
  11609. // The digits of the integral part have been generated:
  11610. //
  11611. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  11612. // = buffer + p2 * 2^e
  11613. //
  11614. // Now generate the digits of the fractional part p2 * 2^e.
  11615. //
  11616. // Note:
  11617. // No decimal point is generated: the exponent is adjusted instead.
  11618. //
  11619. // p2 actually represents the fraction
  11620. //
  11621. // p2 * 2^e
  11622. // = p2 / 2^-e
  11623. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  11624. //
  11625. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  11626. //
  11627. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  11628. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  11629. //
  11630. // using
  11631. //
  11632. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  11633. // = ( d) * 2^-e + ( r)
  11634. //
  11635. // or
  11636. // 10^m * p2 * 2^e = d + r * 2^e
  11637. //
  11638. // i.e.
  11639. //
  11640. // M+ = buffer + p2 * 2^e
  11641. // = buffer + 10^-m * (d + r * 2^e)
  11642. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  11643. //
  11644. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  11645. assert(p2 > delta);
  11646. int m = 0;
  11647. for (;;)
  11648. {
  11649. // Invariant:
  11650. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  11651. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  11652. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  11653. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  11654. //
  11655. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  11656. p2 *= 10;
  11657. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  11658. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  11659. //
  11660. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  11661. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  11662. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11663. //
  11664. assert(d <= 9);
  11665. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  11666. //
  11667. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  11668. //
  11669. p2 = r;
  11670. m++;
  11671. //
  11672. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  11673. // Invariant restored.
  11674. // Check if enough digits have been generated.
  11675. //
  11676. // 10^-m * p2 * 2^e <= delta * 2^e
  11677. // p2 * 2^e <= 10^m * delta * 2^e
  11678. // p2 <= 10^m * delta
  11679. delta *= 10;
  11680. dist *= 10;
  11681. if (p2 <= delta)
  11682. {
  11683. break;
  11684. }
  11685. }
  11686. // V = buffer * 10^-m, with M- <= V <= M+.
  11687. decimal_exponent -= m;
  11688. // 1 ulp in the decimal representation is now 10^-m.
  11689. // Since delta and dist are now scaled by 10^m, we need to do the
  11690. // same with ulp in order to keep the units in sync.
  11691. //
  11692. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  11693. //
  11694. const std::uint64_t ten_m = one.f;
  11695. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  11696. // By construction this algorithm generates the shortest possible decimal
  11697. // number (Loitsch, Theorem 6.2) which rounds back to w.
  11698. // For an input number of precision p, at least
  11699. //
  11700. // N = 1 + ceil(p * log_10(2))
  11701. //
  11702. // decimal digits are sufficient to identify all binary floating-point
  11703. // numbers (Matula, "In-and-Out conversions").
  11704. // This implies that the algorithm does not produce more than N decimal
  11705. // digits.
  11706. //
  11707. // N = 17 for p = 53 (IEEE double precision)
  11708. // N = 9 for p = 24 (IEEE single precision)
  11709. }
  11710. /*!
  11711. v = buf * 10^decimal_exponent
  11712. len is the length of the buffer (number of decimal digits)
  11713. The buffer must be large enough, i.e. >= max_digits10.
  11714. */
  11715. JSON_HEDLEY_NON_NULL(1)
  11716. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  11717. diyfp m_minus, diyfp v, diyfp m_plus)
  11718. {
  11719. assert(m_plus.e == m_minus.e);
  11720. assert(m_plus.e == v.e);
  11721. // --------(-----------------------+-----------------------)-------- (A)
  11722. // m- v m+
  11723. //
  11724. // --------------------(-----------+-----------------------)-------- (B)
  11725. // m- v m+
  11726. //
  11727. // First scale v (and m- and m+) such that the exponent is in the range
  11728. // [alpha, gamma].
  11729. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  11730. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  11731. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  11732. const diyfp w = diyfp::mul(v, c_minus_k);
  11733. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  11734. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  11735. // ----(---+---)---------------(---+---)---------------(---+---)----
  11736. // w- w w+
  11737. // = c*m- = c*v = c*m+
  11738. //
  11739. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  11740. // w+ are now off by a small amount.
  11741. // In fact:
  11742. //
  11743. // w - v * 10^k < 1 ulp
  11744. //
  11745. // To account for this inaccuracy, add resp. subtract 1 ulp.
  11746. //
  11747. // --------+---[---------------(---+---)---------------]---+--------
  11748. // w- M- w M+ w+
  11749. //
  11750. // Now any number in [M-, M+] (bounds included) will round to w when input,
  11751. // regardless of how the input rounding algorithm breaks ties.
  11752. //
  11753. // And digit_gen generates the shortest possible such number in [M-, M+].
  11754. // Note that this does not mean that Grisu2 always generates the shortest
  11755. // possible number in the interval (m-, m+).
  11756. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  11757. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  11758. decimal_exponent = -cached.k; // = -(-k) = k
  11759. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  11760. }
  11761. /*!
  11762. v = buf * 10^decimal_exponent
  11763. len is the length of the buffer (number of decimal digits)
  11764. The buffer must be large enough, i.e. >= max_digits10.
  11765. */
  11766. template <typename FloatType>
  11767. JSON_HEDLEY_NON_NULL(1)
  11768. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  11769. {
  11770. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  11771. "internal error: not enough precision");
  11772. assert(std::isfinite(value));
  11773. assert(value > 0);
  11774. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  11775. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  11776. // decimal representations are not exactly "short".
  11777. //
  11778. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  11779. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  11780. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  11781. // does.
  11782. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  11783. // representation using the corresponding std::from_chars function recovers value exactly". That
  11784. // indicates that single precision floating-point numbers should be recovered using
  11785. // 'std::strtof'.
  11786. //
  11787. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  11788. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  11789. // value is off by 1 ulp.
  11790. #if 0
  11791. const boundaries w = compute_boundaries(static_cast<double>(value));
  11792. #else
  11793. const boundaries w = compute_boundaries(value);
  11794. #endif
  11795. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  11796. }
  11797. /*!
  11798. @brief appends a decimal representation of e to buf
  11799. @return a pointer to the element following the exponent.
  11800. @pre -1000 < e < 1000
  11801. */
  11802. JSON_HEDLEY_NON_NULL(1)
  11803. JSON_HEDLEY_RETURNS_NON_NULL
  11804. inline char* append_exponent(char* buf, int e)
  11805. {
  11806. assert(e > -1000);
  11807. assert(e < 1000);
  11808. if (e < 0)
  11809. {
  11810. e = -e;
  11811. *buf++ = '-';
  11812. }
  11813. else
  11814. {
  11815. *buf++ = '+';
  11816. }
  11817. auto k = static_cast<std::uint32_t>(e);
  11818. if (k < 10)
  11819. {
  11820. // Always print at least two digits in the exponent.
  11821. // This is for compatibility with printf("%g").
  11822. *buf++ = '0';
  11823. *buf++ = static_cast<char>('0' + k);
  11824. }
  11825. else if (k < 100)
  11826. {
  11827. *buf++ = static_cast<char>('0' + k / 10);
  11828. k %= 10;
  11829. *buf++ = static_cast<char>('0' + k);
  11830. }
  11831. else
  11832. {
  11833. *buf++ = static_cast<char>('0' + k / 100);
  11834. k %= 100;
  11835. *buf++ = static_cast<char>('0' + k / 10);
  11836. k %= 10;
  11837. *buf++ = static_cast<char>('0' + k);
  11838. }
  11839. return buf;
  11840. }
  11841. /*!
  11842. @brief prettify v = buf * 10^decimal_exponent
  11843. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  11844. notation. Otherwise it will be printed in exponential notation.
  11845. @pre min_exp < 0
  11846. @pre max_exp > 0
  11847. */
  11848. JSON_HEDLEY_NON_NULL(1)
  11849. JSON_HEDLEY_RETURNS_NON_NULL
  11850. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  11851. int min_exp, int max_exp)
  11852. {
  11853. assert(min_exp < 0);
  11854. assert(max_exp > 0);
  11855. const int k = len;
  11856. const int n = len + decimal_exponent;
  11857. // v = buf * 10^(n-k)
  11858. // k is the length of the buffer (number of decimal digits)
  11859. // n is the position of the decimal point relative to the start of the buffer.
  11860. if (k <= n and n <= max_exp)
  11861. {
  11862. // digits[000]
  11863. // len <= max_exp + 2
  11864. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  11865. // Make it look like a floating-point number (#362, #378)
  11866. buf[n + 0] = '.';
  11867. buf[n + 1] = '0';
  11868. return buf + (n + 2);
  11869. }
  11870. if (0 < n and n <= max_exp)
  11871. {
  11872. // dig.its
  11873. // len <= max_digits10 + 1
  11874. assert(k > n);
  11875. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  11876. buf[n] = '.';
  11877. return buf + (k + 1);
  11878. }
  11879. if (min_exp < n and n <= 0)
  11880. {
  11881. // 0.[000]digits
  11882. // len <= 2 + (-min_exp - 1) + max_digits10
  11883. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  11884. buf[0] = '0';
  11885. buf[1] = '.';
  11886. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  11887. return buf + (2 + (-n) + k);
  11888. }
  11889. if (k == 1)
  11890. {
  11891. // dE+123
  11892. // len <= 1 + 5
  11893. buf += 1;
  11894. }
  11895. else
  11896. {
  11897. // d.igitsE+123
  11898. // len <= max_digits10 + 1 + 5
  11899. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  11900. buf[1] = '.';
  11901. buf += 1 + k;
  11902. }
  11903. *buf++ = 'e';
  11904. return append_exponent(buf, n - 1);
  11905. }
  11906. } // namespace dtoa_impl
  11907. /*!
  11908. @brief generates a decimal representation of the floating-point number value in [first, last).
  11909. The format of the resulting decimal representation is similar to printf's %g
  11910. format. Returns an iterator pointing past-the-end of the decimal representation.
  11911. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  11912. @note The buffer must be large enough.
  11913. @note The result is NOT null-terminated.
  11914. */
  11915. template <typename FloatType>
  11916. JSON_HEDLEY_NON_NULL(1, 2)
  11917. JSON_HEDLEY_RETURNS_NON_NULL
  11918. char* to_chars(char* first, const char* last, FloatType value)
  11919. {
  11920. static_cast<void>(last); // maybe unused - fix warning
  11921. assert(std::isfinite(value));
  11922. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  11923. if (std::signbit(value))
  11924. {
  11925. value = -value;
  11926. *first++ = '-';
  11927. }
  11928. if (value == 0) // +-0
  11929. {
  11930. *first++ = '0';
  11931. // Make it look like a floating-point number (#362, #378)
  11932. *first++ = '.';
  11933. *first++ = '0';
  11934. return first;
  11935. }
  11936. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  11937. // Compute v = buffer * 10^decimal_exponent.
  11938. // The decimal digits are stored in the buffer, which needs to be interpreted
  11939. // as an unsigned decimal integer.
  11940. // len is the length of the buffer, i.e. the number of decimal digits.
  11941. int len = 0;
  11942. int decimal_exponent = 0;
  11943. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  11944. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  11945. // Format the buffer like printf("%.*g", prec, value)
  11946. constexpr int kMinExp = -4;
  11947. // Use digits10 here to increase compatibility with version 2.
  11948. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  11949. assert(last - first >= kMaxExp + 2);
  11950. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  11951. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  11952. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  11953. }
  11954. } // namespace detail
  11955. } // namespace nlohmann
  11956. // #include <nlohmann/detail/exceptions.hpp>
  11957. // #include <nlohmann/detail/macro_scope.hpp>
  11958. // #include <nlohmann/detail/meta/cpp_future.hpp>
  11959. // #include <nlohmann/detail/output/binary_writer.hpp>
  11960. // #include <nlohmann/detail/output/output_adapters.hpp>
  11961. // #include <nlohmann/detail/value_t.hpp>
  11962. namespace nlohmann
  11963. {
  11964. namespace detail
  11965. {
  11966. ///////////////////
  11967. // serialization //
  11968. ///////////////////
  11969. /// how to treat decoding errors
  11970. enum class error_handler_t
  11971. {
  11972. strict, ///< throw a type_error exception in case of invalid UTF-8
  11973. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  11974. ignore ///< ignore invalid UTF-8 sequences
  11975. };
  11976. template<typename BasicJsonType>
  11977. class serializer
  11978. {
  11979. using string_t = typename BasicJsonType::string_t;
  11980. using number_float_t = typename BasicJsonType::number_float_t;
  11981. using number_integer_t = typename BasicJsonType::number_integer_t;
  11982. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  11983. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  11984. static constexpr std::uint8_t UTF8_REJECT = 1;
  11985. public:
  11986. /*!
  11987. @param[in] s output stream to serialize to
  11988. @param[in] ichar indentation character to use
  11989. @param[in] error_handler_ how to react on decoding errors
  11990. */
  11991. serializer(output_adapter_t<char> s, const char ichar,
  11992. error_handler_t error_handler_ = error_handler_t::strict)
  11993. : o(std::move(s))
  11994. , loc(std::localeconv())
  11995. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  11996. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  11997. , indent_char(ichar)
  11998. , indent_string(512, indent_char)
  11999. , error_handler(error_handler_)
  12000. {}
  12001. // delete because of pointer members
  12002. serializer(const serializer&) = delete;
  12003. serializer& operator=(const serializer&) = delete;
  12004. serializer(serializer&&) = delete;
  12005. serializer& operator=(serializer&&) = delete;
  12006. ~serializer() = default;
  12007. /*!
  12008. @brief internal implementation of the serialization function
  12009. This function is called by the public member function dump and organizes
  12010. the serialization internally. The indentation level is propagated as
  12011. additional parameter. In case of arrays and objects, the function is
  12012. called recursively.
  12013. - strings and object keys are escaped using `escape_string()`
  12014. - integer numbers are converted implicitly via `operator<<`
  12015. - floating-point numbers are converted to a string using `"%g"` format
  12016. @param[in] val value to serialize
  12017. @param[in] pretty_print whether the output shall be pretty-printed
  12018. @param[in] indent_step the indent level
  12019. @param[in] current_indent the current indent level (only used internally)
  12020. */
  12021. void dump(const BasicJsonType& val, const bool pretty_print,
  12022. const bool ensure_ascii,
  12023. const unsigned int indent_step,
  12024. const unsigned int current_indent = 0)
  12025. {
  12026. switch (val.m_type)
  12027. {
  12028. case value_t::object:
  12029. {
  12030. if (val.m_value.object->empty())
  12031. {
  12032. o->write_characters("{}", 2);
  12033. return;
  12034. }
  12035. if (pretty_print)
  12036. {
  12037. o->write_characters("{\n", 2);
  12038. // variable to hold indentation for recursive calls
  12039. const auto new_indent = current_indent + indent_step;
  12040. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12041. {
  12042. indent_string.resize(indent_string.size() * 2, ' ');
  12043. }
  12044. // first n-1 elements
  12045. auto i = val.m_value.object->cbegin();
  12046. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12047. {
  12048. o->write_characters(indent_string.c_str(), new_indent);
  12049. o->write_character('\"');
  12050. dump_escaped(i->first, ensure_ascii);
  12051. o->write_characters("\": ", 3);
  12052. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  12053. o->write_characters(",\n", 2);
  12054. }
  12055. // last element
  12056. assert(i != val.m_value.object->cend());
  12057. assert(std::next(i) == val.m_value.object->cend());
  12058. o->write_characters(indent_string.c_str(), new_indent);
  12059. o->write_character('\"');
  12060. dump_escaped(i->first, ensure_ascii);
  12061. o->write_characters("\": ", 3);
  12062. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  12063. o->write_character('\n');
  12064. o->write_characters(indent_string.c_str(), current_indent);
  12065. o->write_character('}');
  12066. }
  12067. else
  12068. {
  12069. o->write_character('{');
  12070. // first n-1 elements
  12071. auto i = val.m_value.object->cbegin();
  12072. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  12073. {
  12074. o->write_character('\"');
  12075. dump_escaped(i->first, ensure_ascii);
  12076. o->write_characters("\":", 2);
  12077. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  12078. o->write_character(',');
  12079. }
  12080. // last element
  12081. assert(i != val.m_value.object->cend());
  12082. assert(std::next(i) == val.m_value.object->cend());
  12083. o->write_character('\"');
  12084. dump_escaped(i->first, ensure_ascii);
  12085. o->write_characters("\":", 2);
  12086. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  12087. o->write_character('}');
  12088. }
  12089. return;
  12090. }
  12091. case value_t::array:
  12092. {
  12093. if (val.m_value.array->empty())
  12094. {
  12095. o->write_characters("[]", 2);
  12096. return;
  12097. }
  12098. if (pretty_print)
  12099. {
  12100. o->write_characters("[\n", 2);
  12101. // variable to hold indentation for recursive calls
  12102. const auto new_indent = current_indent + indent_step;
  12103. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  12104. {
  12105. indent_string.resize(indent_string.size() * 2, ' ');
  12106. }
  12107. // first n-1 elements
  12108. for (auto i = val.m_value.array->cbegin();
  12109. i != val.m_value.array->cend() - 1; ++i)
  12110. {
  12111. o->write_characters(indent_string.c_str(), new_indent);
  12112. dump(*i, true, ensure_ascii, indent_step, new_indent);
  12113. o->write_characters(",\n", 2);
  12114. }
  12115. // last element
  12116. assert(not val.m_value.array->empty());
  12117. o->write_characters(indent_string.c_str(), new_indent);
  12118. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  12119. o->write_character('\n');
  12120. o->write_characters(indent_string.c_str(), current_indent);
  12121. o->write_character(']');
  12122. }
  12123. else
  12124. {
  12125. o->write_character('[');
  12126. // first n-1 elements
  12127. for (auto i = val.m_value.array->cbegin();
  12128. i != val.m_value.array->cend() - 1; ++i)
  12129. {
  12130. dump(*i, false, ensure_ascii, indent_step, current_indent);
  12131. o->write_character(',');
  12132. }
  12133. // last element
  12134. assert(not val.m_value.array->empty());
  12135. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  12136. o->write_character(']');
  12137. }
  12138. return;
  12139. }
  12140. case value_t::string:
  12141. {
  12142. o->write_character('\"');
  12143. dump_escaped(*val.m_value.string, ensure_ascii);
  12144. o->write_character('\"');
  12145. return;
  12146. }
  12147. case value_t::boolean:
  12148. {
  12149. if (val.m_value.boolean)
  12150. {
  12151. o->write_characters("true", 4);
  12152. }
  12153. else
  12154. {
  12155. o->write_characters("false", 5);
  12156. }
  12157. return;
  12158. }
  12159. case value_t::number_integer:
  12160. {
  12161. dump_integer(val.m_value.number_integer);
  12162. return;
  12163. }
  12164. case value_t::number_unsigned:
  12165. {
  12166. dump_integer(val.m_value.number_unsigned);
  12167. return;
  12168. }
  12169. case value_t::number_float:
  12170. {
  12171. dump_float(val.m_value.number_float);
  12172. return;
  12173. }
  12174. case value_t::discarded:
  12175. {
  12176. o->write_characters("<discarded>", 11);
  12177. return;
  12178. }
  12179. case value_t::null:
  12180. {
  12181. o->write_characters("null", 4);
  12182. return;
  12183. }
  12184. default: // LCOV_EXCL_LINE
  12185. assert(false); // LCOV_EXCL_LINE
  12186. }
  12187. }
  12188. private:
  12189. /*!
  12190. @brief dump escaped string
  12191. Escape a string by replacing certain special characters by a sequence of an
  12192. escape character (backslash) and another character and other control
  12193. characters by a sequence of "\u" followed by a four-digit hex
  12194. representation. The escaped string is written to output stream @a o.
  12195. @param[in] s the string to escape
  12196. @param[in] ensure_ascii whether to escape non-ASCII characters with
  12197. \uXXXX sequences
  12198. @complexity Linear in the length of string @a s.
  12199. */
  12200. void dump_escaped(const string_t& s, const bool ensure_ascii)
  12201. {
  12202. std::uint32_t codepoint;
  12203. std::uint8_t state = UTF8_ACCEPT;
  12204. std::size_t bytes = 0; // number of bytes written to string_buffer
  12205. // number of bytes written at the point of the last valid byte
  12206. std::size_t bytes_after_last_accept = 0;
  12207. std::size_t undumped_chars = 0;
  12208. for (std::size_t i = 0; i < s.size(); ++i)
  12209. {
  12210. const auto byte = static_cast<uint8_t>(s[i]);
  12211. switch (decode(state, codepoint, byte))
  12212. {
  12213. case UTF8_ACCEPT: // decode found a new code point
  12214. {
  12215. switch (codepoint)
  12216. {
  12217. case 0x08: // backspace
  12218. {
  12219. string_buffer[bytes++] = '\\';
  12220. string_buffer[bytes++] = 'b';
  12221. break;
  12222. }
  12223. case 0x09: // horizontal tab
  12224. {
  12225. string_buffer[bytes++] = '\\';
  12226. string_buffer[bytes++] = 't';
  12227. break;
  12228. }
  12229. case 0x0A: // newline
  12230. {
  12231. string_buffer[bytes++] = '\\';
  12232. string_buffer[bytes++] = 'n';
  12233. break;
  12234. }
  12235. case 0x0C: // formfeed
  12236. {
  12237. string_buffer[bytes++] = '\\';
  12238. string_buffer[bytes++] = 'f';
  12239. break;
  12240. }
  12241. case 0x0D: // carriage return
  12242. {
  12243. string_buffer[bytes++] = '\\';
  12244. string_buffer[bytes++] = 'r';
  12245. break;
  12246. }
  12247. case 0x22: // quotation mark
  12248. {
  12249. string_buffer[bytes++] = '\\';
  12250. string_buffer[bytes++] = '\"';
  12251. break;
  12252. }
  12253. case 0x5C: // reverse solidus
  12254. {
  12255. string_buffer[bytes++] = '\\';
  12256. string_buffer[bytes++] = '\\';
  12257. break;
  12258. }
  12259. default:
  12260. {
  12261. // escape control characters (0x00..0x1F) or, if
  12262. // ensure_ascii parameter is used, non-ASCII characters
  12263. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  12264. {
  12265. if (codepoint <= 0xFFFF)
  12266. {
  12267. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  12268. static_cast<std::uint16_t>(codepoint));
  12269. bytes += 6;
  12270. }
  12271. else
  12272. {
  12273. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  12274. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  12275. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  12276. bytes += 12;
  12277. }
  12278. }
  12279. else
  12280. {
  12281. // copy byte to buffer (all previous bytes
  12282. // been copied have in default case above)
  12283. string_buffer[bytes++] = s[i];
  12284. }
  12285. break;
  12286. }
  12287. }
  12288. // write buffer and reset index; there must be 13 bytes
  12289. // left, as this is the maximal number of bytes to be
  12290. // written ("\uxxxx\uxxxx\0") for one code point
  12291. if (string_buffer.size() - bytes < 13)
  12292. {
  12293. o->write_characters(string_buffer.data(), bytes);
  12294. bytes = 0;
  12295. }
  12296. // remember the byte position of this accept
  12297. bytes_after_last_accept = bytes;
  12298. undumped_chars = 0;
  12299. break;
  12300. }
  12301. case UTF8_REJECT: // decode found invalid UTF-8 byte
  12302. {
  12303. switch (error_handler)
  12304. {
  12305. case error_handler_t::strict:
  12306. {
  12307. std::string sn(3, '\0');
  12308. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  12309. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  12310. }
  12311. case error_handler_t::ignore:
  12312. case error_handler_t::replace:
  12313. {
  12314. // in case we saw this character the first time, we
  12315. // would like to read it again, because the byte
  12316. // may be OK for itself, but just not OK for the
  12317. // previous sequence
  12318. if (undumped_chars > 0)
  12319. {
  12320. --i;
  12321. }
  12322. // reset length buffer to the last accepted index;
  12323. // thus removing/ignoring the invalid characters
  12324. bytes = bytes_after_last_accept;
  12325. if (error_handler == error_handler_t::replace)
  12326. {
  12327. // add a replacement character
  12328. if (ensure_ascii)
  12329. {
  12330. string_buffer[bytes++] = '\\';
  12331. string_buffer[bytes++] = 'u';
  12332. string_buffer[bytes++] = 'f';
  12333. string_buffer[bytes++] = 'f';
  12334. string_buffer[bytes++] = 'f';
  12335. string_buffer[bytes++] = 'd';
  12336. }
  12337. else
  12338. {
  12339. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  12340. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  12341. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  12342. }
  12343. // write buffer and reset index; there must be 13 bytes
  12344. // left, as this is the maximal number of bytes to be
  12345. // written ("\uxxxx\uxxxx\0") for one code point
  12346. if (string_buffer.size() - bytes < 13)
  12347. {
  12348. o->write_characters(string_buffer.data(), bytes);
  12349. bytes = 0;
  12350. }
  12351. bytes_after_last_accept = bytes;
  12352. }
  12353. undumped_chars = 0;
  12354. // continue processing the string
  12355. state = UTF8_ACCEPT;
  12356. break;
  12357. }
  12358. default: // LCOV_EXCL_LINE
  12359. assert(false); // LCOV_EXCL_LINE
  12360. }
  12361. break;
  12362. }
  12363. default: // decode found yet incomplete multi-byte code point
  12364. {
  12365. if (not ensure_ascii)
  12366. {
  12367. // code point will not be escaped - copy byte to buffer
  12368. string_buffer[bytes++] = s[i];
  12369. }
  12370. ++undumped_chars;
  12371. break;
  12372. }
  12373. }
  12374. }
  12375. // we finished processing the string
  12376. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  12377. {
  12378. // write buffer
  12379. if (bytes > 0)
  12380. {
  12381. o->write_characters(string_buffer.data(), bytes);
  12382. }
  12383. }
  12384. else
  12385. {
  12386. // we finish reading, but do not accept: string was incomplete
  12387. switch (error_handler)
  12388. {
  12389. case error_handler_t::strict:
  12390. {
  12391. std::string sn(3, '\0');
  12392. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  12393. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  12394. }
  12395. case error_handler_t::ignore:
  12396. {
  12397. // write all accepted bytes
  12398. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12399. break;
  12400. }
  12401. case error_handler_t::replace:
  12402. {
  12403. // write all accepted bytes
  12404. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  12405. // add a replacement character
  12406. if (ensure_ascii)
  12407. {
  12408. o->write_characters("\\ufffd", 6);
  12409. }
  12410. else
  12411. {
  12412. o->write_characters("\xEF\xBF\xBD", 3);
  12413. }
  12414. break;
  12415. }
  12416. default: // LCOV_EXCL_LINE
  12417. assert(false); // LCOV_EXCL_LINE
  12418. }
  12419. }
  12420. }
  12421. /*!
  12422. @brief count digits
  12423. Count the number of decimal (base 10) digits for an input unsigned integer.
  12424. @param[in] x unsigned integer number to count its digits
  12425. @return number of decimal digits
  12426. */
  12427. inline unsigned int count_digits(number_unsigned_t x) noexcept
  12428. {
  12429. unsigned int n_digits = 1;
  12430. for (;;)
  12431. {
  12432. if (x < 10)
  12433. {
  12434. return n_digits;
  12435. }
  12436. if (x < 100)
  12437. {
  12438. return n_digits + 1;
  12439. }
  12440. if (x < 1000)
  12441. {
  12442. return n_digits + 2;
  12443. }
  12444. if (x < 10000)
  12445. {
  12446. return n_digits + 3;
  12447. }
  12448. x = x / 10000u;
  12449. n_digits += 4;
  12450. }
  12451. }
  12452. /*!
  12453. @brief dump an integer
  12454. Dump a given integer to output stream @a o. Works internally with
  12455. @a number_buffer.
  12456. @param[in] x integer number (signed or unsigned) to dump
  12457. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  12458. */
  12459. template<typename NumberType, detail::enable_if_t<
  12460. std::is_same<NumberType, number_unsigned_t>::value or
  12461. std::is_same<NumberType, number_integer_t>::value,
  12462. int> = 0>
  12463. void dump_integer(NumberType x)
  12464. {
  12465. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  12466. {
  12467. {
  12468. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  12469. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  12470. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  12471. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  12472. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  12473. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  12474. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  12475. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  12476. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  12477. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  12478. }
  12479. };
  12480. // special case for "0"
  12481. if (x == 0)
  12482. {
  12483. o->write_character('0');
  12484. return;
  12485. }
  12486. // use a pointer to fill the buffer
  12487. auto buffer_ptr = number_buffer.begin();
  12488. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  12489. number_unsigned_t abs_value;
  12490. unsigned int n_chars;
  12491. if (is_negative)
  12492. {
  12493. *buffer_ptr = '-';
  12494. abs_value = remove_sign(x);
  12495. // account one more byte for the minus sign
  12496. n_chars = 1 + count_digits(abs_value);
  12497. }
  12498. else
  12499. {
  12500. abs_value = static_cast<number_unsigned_t>(x);
  12501. n_chars = count_digits(abs_value);
  12502. }
  12503. // spare 1 byte for '\0'
  12504. assert(n_chars < number_buffer.size() - 1);
  12505. // jump to the end to generate the string from backward
  12506. // so we later avoid reversing the result
  12507. buffer_ptr += n_chars;
  12508. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  12509. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  12510. while (abs_value >= 100)
  12511. {
  12512. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  12513. abs_value /= 100;
  12514. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12515. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12516. }
  12517. if (abs_value >= 10)
  12518. {
  12519. const auto digits_index = static_cast<unsigned>(abs_value);
  12520. *(--buffer_ptr) = digits_to_99[digits_index][1];
  12521. *(--buffer_ptr) = digits_to_99[digits_index][0];
  12522. }
  12523. else
  12524. {
  12525. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  12526. }
  12527. o->write_characters(number_buffer.data(), n_chars);
  12528. }
  12529. /*!
  12530. @brief dump a floating-point number
  12531. Dump a given floating-point number to output stream @a o. Works internally
  12532. with @a number_buffer.
  12533. @param[in] x floating-point number to dump
  12534. */
  12535. void dump_float(number_float_t x)
  12536. {
  12537. // NaN / inf
  12538. if (not std::isfinite(x))
  12539. {
  12540. o->write_characters("null", 4);
  12541. return;
  12542. }
  12543. // If number_float_t is an IEEE-754 single or double precision number,
  12544. // use the Grisu2 algorithm to produce short numbers which are
  12545. // guaranteed to round-trip, using strtof and strtod, resp.
  12546. //
  12547. // NB: The test below works if <long double> == <double>.
  12548. static constexpr bool is_ieee_single_or_double
  12549. = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
  12550. (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
  12551. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  12552. }
  12553. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  12554. {
  12555. char* begin = number_buffer.data();
  12556. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  12557. o->write_characters(begin, static_cast<size_t>(end - begin));
  12558. }
  12559. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  12560. {
  12561. // get number of digits for a float -> text -> float round-trip
  12562. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  12563. // the actual conversion
  12564. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  12565. // negative value indicates an error
  12566. assert(len > 0);
  12567. // check if buffer was large enough
  12568. assert(static_cast<std::size_t>(len) < number_buffer.size());
  12569. // erase thousands separator
  12570. if (thousands_sep != '\0')
  12571. {
  12572. const auto end = std::remove(number_buffer.begin(),
  12573. number_buffer.begin() + len, thousands_sep);
  12574. std::fill(end, number_buffer.end(), '\0');
  12575. assert((end - number_buffer.begin()) <= len);
  12576. len = (end - number_buffer.begin());
  12577. }
  12578. // convert decimal point to '.'
  12579. if (decimal_point != '\0' and decimal_point != '.')
  12580. {
  12581. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  12582. if (dec_pos != number_buffer.end())
  12583. {
  12584. *dec_pos = '.';
  12585. }
  12586. }
  12587. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  12588. // determine if need to append ".0"
  12589. const bool value_is_int_like =
  12590. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  12591. [](char c)
  12592. {
  12593. return c == '.' or c == 'e';
  12594. });
  12595. if (value_is_int_like)
  12596. {
  12597. o->write_characters(".0", 2);
  12598. }
  12599. }
  12600. /*!
  12601. @brief check whether a string is UTF-8 encoded
  12602. The function checks each byte of a string whether it is UTF-8 encoded. The
  12603. result of the check is stored in the @a state parameter. The function must
  12604. be called initially with state 0 (accept). State 1 means the string must
  12605. be rejected, because the current byte is not allowed. If the string is
  12606. completely processed, but the state is non-zero, the string ended
  12607. prematurely; that is, the last byte indicated more bytes should have
  12608. followed.
  12609. @param[in,out] state the state of the decoding
  12610. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  12611. @param[in] byte next byte to decode
  12612. @return new state
  12613. @note The function has been edited: a std::array is used.
  12614. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  12615. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  12616. */
  12617. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  12618. {
  12619. static const std::array<std::uint8_t, 400> utf8d =
  12620. {
  12621. {
  12622. 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
  12623. 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
  12624. 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
  12625. 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
  12626. 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
  12627. 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
  12628. 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
  12629. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  12630. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  12631. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  12632. 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
  12633. 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
  12634. 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
  12635. 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
  12636. }
  12637. };
  12638. const std::uint8_t type = utf8d[byte];
  12639. codep = (state != UTF8_ACCEPT)
  12640. ? (byte & 0x3fu) | (codep << 6u)
  12641. : (0xFFu >> type) & (byte);
  12642. state = utf8d[256u + state * 16u + type];
  12643. return state;
  12644. }
  12645. /*
  12646. * Overload to make the compiler happy while it is instantiating
  12647. * dump_integer for number_unsigned_t.
  12648. * Must never be called.
  12649. */
  12650. number_unsigned_t remove_sign(number_unsigned_t x)
  12651. {
  12652. assert(false); // LCOV_EXCL_LINE
  12653. return x; // LCOV_EXCL_LINE
  12654. }
  12655. /*
  12656. * Helper function for dump_integer
  12657. *
  12658. * This function takes a negative signed integer and returns its absolute
  12659. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  12660. * not directly remove the sign of an arbitrary signed integer as the
  12661. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  12662. * #1708 for details.
  12663. */
  12664. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  12665. {
  12666. assert(x < 0 and x < (std::numeric_limits<number_integer_t>::max)());
  12667. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  12668. }
  12669. private:
  12670. /// the output of the serializer
  12671. output_adapter_t<char> o = nullptr;
  12672. /// a (hopefully) large enough character buffer
  12673. std::array<char, 64> number_buffer{{}};
  12674. /// the locale
  12675. const std::lconv* loc = nullptr;
  12676. /// the locale's thousand separator character
  12677. const char thousands_sep = '\0';
  12678. /// the locale's decimal point character
  12679. const char decimal_point = '\0';
  12680. /// string buffer
  12681. std::array<char, 512> string_buffer{{}};
  12682. /// the indentation character
  12683. const char indent_char;
  12684. /// the indentation string
  12685. string_t indent_string;
  12686. /// error_handler how to react on decoding errors
  12687. const error_handler_t error_handler;
  12688. };
  12689. } // namespace detail
  12690. } // namespace nlohmann
  12691. // #include <nlohmann/detail/value_t.hpp>
  12692. // #include <nlohmann/json_fwd.hpp>
  12693. /*!
  12694. @brief namespace for Niels Lohmann
  12695. @see https://github.com/nlohmann
  12696. @since version 1.0.0
  12697. */
  12698. namespace nlohmann
  12699. {
  12700. /*!
  12701. @brief a class to store JSON values
  12702. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  12703. in @ref object_t)
  12704. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  12705. in @ref array_t)
  12706. @tparam StringType type for JSON strings and object keys (`std::string` by
  12707. default; will be used in @ref string_t)
  12708. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  12709. in @ref boolean_t)
  12710. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  12711. default; will be used in @ref number_integer_t)
  12712. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  12713. `uint64_t` by default; will be used in @ref number_unsigned_t)
  12714. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  12715. default; will be used in @ref number_float_t)
  12716. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  12717. default)
  12718. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  12719. and `from_json()` (@ref adl_serializer by default)
  12720. @requirement The class satisfies the following concept requirements:
  12721. - Basic
  12722. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  12723. JSON values can be default constructed. The result will be a JSON null
  12724. value.
  12725. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  12726. A JSON value can be constructed from an rvalue argument.
  12727. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  12728. A JSON value can be copy-constructed from an lvalue expression.
  12729. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  12730. A JSON value van be assigned from an rvalue argument.
  12731. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  12732. A JSON value can be copy-assigned from an lvalue expression.
  12733. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  12734. JSON values can be destructed.
  12735. - Layout
  12736. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  12737. JSON values have
  12738. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  12739. All non-static data members are private and standard layout types, the
  12740. class has no virtual functions or (virtual) base classes.
  12741. - Library-wide
  12742. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  12743. JSON values can be compared with `==`, see @ref
  12744. operator==(const_reference,const_reference).
  12745. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  12746. JSON values can be compared with `<`, see @ref
  12747. operator<(const_reference,const_reference).
  12748. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  12749. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  12750. other compatible types, using unqualified function call @ref swap().
  12751. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  12752. JSON values can be compared against `std::nullptr_t` objects which are used
  12753. to model the `null` value.
  12754. - Container
  12755. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  12756. JSON values can be used like STL containers and provide iterator access.
  12757. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  12758. JSON values can be used like STL containers and provide reverse iterator
  12759. access.
  12760. @invariant The member variables @a m_value and @a m_type have the following
  12761. relationship:
  12762. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  12763. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  12764. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  12765. The invariants are checked by member function assert_invariant().
  12766. @internal
  12767. @note ObjectType trick from http://stackoverflow.com/a/9860911
  12768. @endinternal
  12769. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  12770. Format](http://rfc7159.net/rfc7159)
  12771. @since version 1.0.0
  12772. @nosubgrouping
  12773. */
  12774. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12775. class basic_json
  12776. {
  12777. private:
  12778. template<detail::value_t> friend struct detail::external_constructor;
  12779. friend ::nlohmann::json_pointer<basic_json>;
  12780. friend ::nlohmann::detail::parser<basic_json>;
  12781. friend ::nlohmann::detail::serializer<basic_json>;
  12782. template<typename BasicJsonType>
  12783. friend class ::nlohmann::detail::iter_impl;
  12784. template<typename BasicJsonType, typename CharType>
  12785. friend class ::nlohmann::detail::binary_writer;
  12786. template<typename BasicJsonType, typename SAX>
  12787. friend class ::nlohmann::detail::binary_reader;
  12788. template<typename BasicJsonType>
  12789. friend class ::nlohmann::detail::json_sax_dom_parser;
  12790. template<typename BasicJsonType>
  12791. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  12792. /// workaround type for MSVC
  12793. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  12794. // convenience aliases for types residing in namespace detail;
  12795. using lexer = ::nlohmann::detail::lexer<basic_json>;
  12796. using parser = ::nlohmann::detail::parser<basic_json>;
  12797. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  12798. template<typename BasicJsonType>
  12799. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  12800. template<typename BasicJsonType>
  12801. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  12802. template<typename Iterator>
  12803. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  12804. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  12805. template<typename CharType>
  12806. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  12807. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  12808. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  12809. using serializer = ::nlohmann::detail::serializer<basic_json>;
  12810. public:
  12811. using value_t = detail::value_t;
  12812. /// JSON Pointer, see @ref nlohmann::json_pointer
  12813. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  12814. template<typename T, typename SFINAE>
  12815. using json_serializer = JSONSerializer<T, SFINAE>;
  12816. /// how to treat decoding errors
  12817. using error_handler_t = detail::error_handler_t;
  12818. /// helper type for initializer lists of basic_json values
  12819. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  12820. using input_format_t = detail::input_format_t;
  12821. /// SAX interface type, see @ref nlohmann::json_sax
  12822. using json_sax_t = json_sax<basic_json>;
  12823. ////////////////
  12824. // exceptions //
  12825. ////////////////
  12826. /// @name exceptions
  12827. /// Classes to implement user-defined exceptions.
  12828. /// @{
  12829. /// @copydoc detail::exception
  12830. using exception = detail::exception;
  12831. /// @copydoc detail::parse_error
  12832. using parse_error = detail::parse_error;
  12833. /// @copydoc detail::invalid_iterator
  12834. using invalid_iterator = detail::invalid_iterator;
  12835. /// @copydoc detail::type_error
  12836. using type_error = detail::type_error;
  12837. /// @copydoc detail::out_of_range
  12838. using out_of_range = detail::out_of_range;
  12839. /// @copydoc detail::other_error
  12840. using other_error = detail::other_error;
  12841. /// @}
  12842. /////////////////////
  12843. // container types //
  12844. /////////////////////
  12845. /// @name container types
  12846. /// The canonic container types to use @ref basic_json like any other STL
  12847. /// container.
  12848. /// @{
  12849. /// the type of elements in a basic_json container
  12850. using value_type = basic_json;
  12851. /// the type of an element reference
  12852. using reference = value_type&;
  12853. /// the type of an element const reference
  12854. using const_reference = const value_type&;
  12855. /// a type to represent differences between iterators
  12856. using difference_type = std::ptrdiff_t;
  12857. /// a type to represent container sizes
  12858. using size_type = std::size_t;
  12859. /// the allocator type
  12860. using allocator_type = AllocatorType<basic_json>;
  12861. /// the type of an element pointer
  12862. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  12863. /// the type of an element const pointer
  12864. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  12865. /// an iterator for a basic_json container
  12866. using iterator = iter_impl<basic_json>;
  12867. /// a const iterator for a basic_json container
  12868. using const_iterator = iter_impl<const basic_json>;
  12869. /// a reverse iterator for a basic_json container
  12870. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  12871. /// a const reverse iterator for a basic_json container
  12872. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  12873. /// @}
  12874. /*!
  12875. @brief returns the allocator associated with the container
  12876. */
  12877. static allocator_type get_allocator()
  12878. {
  12879. return allocator_type();
  12880. }
  12881. /*!
  12882. @brief returns version information on the library
  12883. This function returns a JSON object with information about the library,
  12884. including the version number and information on the platform and compiler.
  12885. @return JSON object holding version information
  12886. key | description
  12887. ----------- | ---------------
  12888. `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).
  12889. `copyright` | The copyright line for the library as string.
  12890. `name` | The name of the library as string.
  12891. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  12892. `url` | The URL of the project as string.
  12893. `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).
  12894. @liveexample{The following code shows an example output of the `meta()`
  12895. function.,meta}
  12896. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12897. changes to any JSON value.
  12898. @complexity Constant.
  12899. @since 2.1.0
  12900. */
  12901. JSON_HEDLEY_WARN_UNUSED_RESULT
  12902. static basic_json meta()
  12903. {
  12904. basic_json result;
  12905. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  12906. result["name"] = "JSON for Modern C++";
  12907. result["url"] = "https://github.com/nlohmann/json";
  12908. result["version"]["string"] =
  12909. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  12910. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  12911. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  12912. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  12913. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  12914. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  12915. #ifdef _WIN32
  12916. result["platform"] = "win32";
  12917. #elif defined __linux__
  12918. result["platform"] = "linux";
  12919. #elif defined __APPLE__
  12920. result["platform"] = "apple";
  12921. #elif defined __unix__
  12922. result["platform"] = "unix";
  12923. #else
  12924. result["platform"] = "unknown";
  12925. #endif
  12926. #if defined(__ICC) || defined(__INTEL_COMPILER)
  12927. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  12928. #elif defined(__clang__)
  12929. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  12930. #elif defined(__GNUC__) || defined(__GNUG__)
  12931. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  12932. #elif defined(__HP_cc) || defined(__HP_aCC)
  12933. result["compiler"] = "hp"
  12934. #elif defined(__IBMCPP__)
  12935. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  12936. #elif defined(_MSC_VER)
  12937. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  12938. #elif defined(__PGI)
  12939. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  12940. #elif defined(__SUNPRO_CC)
  12941. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  12942. #else
  12943. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  12944. #endif
  12945. #ifdef __cplusplus
  12946. result["compiler"]["c++"] = std::to_string(__cplusplus);
  12947. #else
  12948. result["compiler"]["c++"] = "unknown";
  12949. #endif
  12950. return result;
  12951. }
  12952. ///////////////////////////
  12953. // JSON value data types //
  12954. ///////////////////////////
  12955. /// @name JSON value data types
  12956. /// The data types to store a JSON value. These types are derived from
  12957. /// the template arguments passed to class @ref basic_json.
  12958. /// @{
  12959. #if defined(JSON_HAS_CPP_14)
  12960. // Use transparent comparator if possible, combined with perfect forwarding
  12961. // on find() and count() calls prevents unnecessary string construction.
  12962. using object_comparator_t = std::less<>;
  12963. #else
  12964. using object_comparator_t = std::less<StringType>;
  12965. #endif
  12966. /*!
  12967. @brief a type for an object
  12968. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  12969. > An object is an unordered collection of zero or more name/value pairs,
  12970. > where a name is a string and a value is a string, number, boolean, null,
  12971. > object, or array.
  12972. To store objects in C++, a type is defined by the template parameters
  12973. described below.
  12974. @tparam ObjectType the container to store objects (e.g., `std::map` or
  12975. `std::unordered_map`)
  12976. @tparam StringType the type of the keys or names (e.g., `std::string`).
  12977. The comparison function `std::less<StringType>` is used to order elements
  12978. inside the container.
  12979. @tparam AllocatorType the allocator to use for objects (e.g.,
  12980. `std::allocator`)
  12981. #### Default type
  12982. With the default values for @a ObjectType (`std::map`), @a StringType
  12983. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  12984. value for @a object_t is:
  12985. @code {.cpp}
  12986. std::map<
  12987. std::string, // key_type
  12988. basic_json, // value_type
  12989. std::less<std::string>, // key_compare
  12990. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  12991. >
  12992. @endcode
  12993. #### Behavior
  12994. The choice of @a object_t influences the behavior of the JSON class. With
  12995. the default type, objects have the following behavior:
  12996. - When all names are unique, objects will be interoperable in the sense
  12997. that all software implementations receiving that object will agree on
  12998. the name-value mappings.
  12999. - When the names within an object are not unique, it is unspecified which
  13000. one of the values for a given key will be chosen. For instance,
  13001. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  13002. `{"key": 2}`.
  13003. - Internally, name/value pairs are stored in lexicographical order of the
  13004. names. Objects will also be serialized (see @ref dump) in this order.
  13005. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  13006. and serialized as `{"a": 2, "b": 1}`.
  13007. - When comparing objects, the order of the name/value pairs is irrelevant.
  13008. This makes objects interoperable in the sense that they will not be
  13009. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  13010. `{"a": 2, "b": 1}` will be treated as equal.
  13011. #### Limits
  13012. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13013. > An implementation may set limits on the maximum depth of nesting.
  13014. In this class, the object's limit of nesting is not explicitly constrained.
  13015. However, a maximum depth of nesting may be introduced by the compiler or
  13016. runtime environment. A theoretical limit can be queried by calling the
  13017. @ref max_size function of a JSON object.
  13018. #### Storage
  13019. Objects are stored as pointers in a @ref basic_json type. That is, for any
  13020. access to object values, a pointer of type `object_t*` must be
  13021. dereferenced.
  13022. @sa @ref array_t -- type for an array value
  13023. @since version 1.0.0
  13024. @note The order name/value pairs are added to the object is *not*
  13025. preserved by the library. Therefore, iterating an object may return
  13026. name/value pairs in a different order than they were originally stored. In
  13027. fact, keys will be traversed in alphabetical order as `std::map` with
  13028. `std::less` is used by default. Please note this behavior conforms to [RFC
  13029. 7159](http://rfc7159.net/rfc7159), because any order implements the
  13030. specified "unordered" nature of JSON objects.
  13031. */
  13032. using object_t = ObjectType<StringType,
  13033. basic_json,
  13034. object_comparator_t,
  13035. AllocatorType<std::pair<const StringType,
  13036. basic_json>>>;
  13037. /*!
  13038. @brief a type for an array
  13039. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  13040. > An array is an ordered sequence of zero or more values.
  13041. To store objects in C++, a type is defined by the template parameters
  13042. explained below.
  13043. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  13044. `std::list`)
  13045. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  13046. #### Default type
  13047. With the default values for @a ArrayType (`std::vector`) and @a
  13048. AllocatorType (`std::allocator`), the default value for @a array_t is:
  13049. @code {.cpp}
  13050. std::vector<
  13051. basic_json, // value_type
  13052. std::allocator<basic_json> // allocator_type
  13053. >
  13054. @endcode
  13055. #### Limits
  13056. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13057. > An implementation may set limits on the maximum depth of nesting.
  13058. In this class, the array's limit of nesting is not explicitly constrained.
  13059. However, a maximum depth of nesting may be introduced by the compiler or
  13060. runtime environment. A theoretical limit can be queried by calling the
  13061. @ref max_size function of a JSON array.
  13062. #### Storage
  13063. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  13064. access to array values, a pointer of type `array_t*` must be dereferenced.
  13065. @sa @ref object_t -- type for an object value
  13066. @since version 1.0.0
  13067. */
  13068. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  13069. /*!
  13070. @brief a type for a string
  13071. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  13072. > A string is a sequence of zero or more Unicode characters.
  13073. To store objects in C++, a type is defined by the template parameter
  13074. described below. Unicode values are split by the JSON class into
  13075. byte-sized characters during deserialization.
  13076. @tparam StringType the container to store strings (e.g., `std::string`).
  13077. Note this container is used for keys/names in objects, see @ref object_t.
  13078. #### Default type
  13079. With the default values for @a StringType (`std::string`), the default
  13080. value for @a string_t is:
  13081. @code {.cpp}
  13082. std::string
  13083. @endcode
  13084. #### Encoding
  13085. Strings are stored in UTF-8 encoding. Therefore, functions like
  13086. `std::string::size()` or `std::string::length()` return the number of
  13087. bytes in the string rather than the number of characters or glyphs.
  13088. #### String comparison
  13089. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13090. > Software implementations are typically required to test names of object
  13091. > members for equality. Implementations that transform the textual
  13092. > representation into sequences of Unicode code units and then perform the
  13093. > comparison numerically, code unit by code unit, are interoperable in the
  13094. > sense that implementations will agree in all cases on equality or
  13095. > inequality of two strings. For example, implementations that compare
  13096. > strings with escaped characters unconverted may incorrectly find that
  13097. > `"a\\b"` and `"a\u005Cb"` are not equal.
  13098. This implementation is interoperable as it does compare strings code unit
  13099. by code unit.
  13100. #### Storage
  13101. String values are stored as pointers in a @ref basic_json type. That is,
  13102. for any access to string values, a pointer of type `string_t*` must be
  13103. dereferenced.
  13104. @since version 1.0.0
  13105. */
  13106. using string_t = StringType;
  13107. /*!
  13108. @brief a type for a boolean
  13109. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  13110. type which differentiates the two literals `true` and `false`.
  13111. To store objects in C++, a type is defined by the template parameter @a
  13112. BooleanType which chooses the type to use.
  13113. #### Default type
  13114. With the default values for @a BooleanType (`bool`), the default value for
  13115. @a boolean_t is:
  13116. @code {.cpp}
  13117. bool
  13118. @endcode
  13119. #### Storage
  13120. Boolean values are stored directly inside a @ref basic_json type.
  13121. @since version 1.0.0
  13122. */
  13123. using boolean_t = BooleanType;
  13124. /*!
  13125. @brief a type for a number (integer)
  13126. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13127. > The representation of numbers is similar to that used in most
  13128. > programming languages. A number is represented in base 10 using decimal
  13129. > digits. It contains an integer component that may be prefixed with an
  13130. > optional minus sign, which may be followed by a fraction part and/or an
  13131. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13132. > cannot be represented in the grammar below (such as Infinity and NaN)
  13133. > are not permitted.
  13134. This description includes both integer and floating-point numbers.
  13135. However, C++ allows more precise storage if it is known whether the number
  13136. is a signed integer, an unsigned integer or a floating-point number.
  13137. Therefore, three different types, @ref number_integer_t, @ref
  13138. number_unsigned_t and @ref number_float_t are used.
  13139. To store integer numbers in C++, a type is defined by the template
  13140. parameter @a NumberIntegerType which chooses the type to use.
  13141. #### Default type
  13142. With the default values for @a NumberIntegerType (`int64_t`), the default
  13143. value for @a number_integer_t is:
  13144. @code {.cpp}
  13145. int64_t
  13146. @endcode
  13147. #### Default behavior
  13148. - The restrictions about leading zeros is not enforced in C++. Instead,
  13149. leading zeros in integer literals lead to an interpretation as octal
  13150. number. Internally, the value will be stored as decimal number. For
  13151. instance, the C++ integer literal `010` will be serialized to `8`.
  13152. During deserialization, leading zeros yield an error.
  13153. - Not-a-number (NaN) values will be serialized to `null`.
  13154. #### Limits
  13155. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13156. > An implementation may set limits on the range and precision of numbers.
  13157. When the default type is used, the maximal integer number that can be
  13158. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  13159. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  13160. that are out of range will yield over/underflow when used in a
  13161. constructor. During deserialization, too large or small integer numbers
  13162. will be automatically be stored as @ref number_unsigned_t or @ref
  13163. number_float_t.
  13164. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13165. > Note that when such software is used, numbers that are integers and are
  13166. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13167. > that implementations will agree exactly on their numeric values.
  13168. As this range is a subrange of the exactly supported range [INT64_MIN,
  13169. INT64_MAX], this class's integer type is interoperable.
  13170. #### Storage
  13171. Integer number values are stored directly inside a @ref basic_json type.
  13172. @sa @ref number_float_t -- type for number values (floating-point)
  13173. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13174. @since version 1.0.0
  13175. */
  13176. using number_integer_t = NumberIntegerType;
  13177. /*!
  13178. @brief a type for a number (unsigned)
  13179. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13180. > The representation of numbers is similar to that used in most
  13181. > programming languages. A number is represented in base 10 using decimal
  13182. > digits. It contains an integer component that may be prefixed with an
  13183. > optional minus sign, which may be followed by a fraction part and/or an
  13184. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13185. > cannot be represented in the grammar below (such as Infinity and NaN)
  13186. > are not permitted.
  13187. This description includes both integer and floating-point numbers.
  13188. However, C++ allows more precise storage if it is known whether the number
  13189. is a signed integer, an unsigned integer or a floating-point number.
  13190. Therefore, three different types, @ref number_integer_t, @ref
  13191. number_unsigned_t and @ref number_float_t are used.
  13192. To store unsigned integer numbers in C++, a type is defined by the
  13193. template parameter @a NumberUnsignedType which chooses the type to use.
  13194. #### Default type
  13195. With the default values for @a NumberUnsignedType (`uint64_t`), the
  13196. default value for @a number_unsigned_t is:
  13197. @code {.cpp}
  13198. uint64_t
  13199. @endcode
  13200. #### Default behavior
  13201. - The restrictions about leading zeros is not enforced in C++. Instead,
  13202. leading zeros in integer literals lead to an interpretation as octal
  13203. number. Internally, the value will be stored as decimal number. For
  13204. instance, the C++ integer literal `010` will be serialized to `8`.
  13205. During deserialization, leading zeros yield an error.
  13206. - Not-a-number (NaN) values will be serialized to `null`.
  13207. #### Limits
  13208. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  13209. > An implementation may set limits on the range and precision of numbers.
  13210. When the default type is used, the maximal integer number that can be
  13211. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  13212. number that can be stored is `0`. Integer numbers that are out of range
  13213. will yield over/underflow when used in a constructor. During
  13214. deserialization, too large or small integer numbers will be automatically
  13215. be stored as @ref number_integer_t or @ref number_float_t.
  13216. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  13217. > Note that when such software is used, numbers that are integers and are
  13218. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  13219. > that implementations will agree exactly on their numeric values.
  13220. As this range is a subrange (when considered in conjunction with the
  13221. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  13222. this class's integer type is interoperable.
  13223. #### Storage
  13224. Integer number values are stored directly inside a @ref basic_json type.
  13225. @sa @ref number_float_t -- type for number values (floating-point)
  13226. @sa @ref number_integer_t -- type for number values (integer)
  13227. @since version 2.0.0
  13228. */
  13229. using number_unsigned_t = NumberUnsignedType;
  13230. /*!
  13231. @brief a type for a number (floating-point)
  13232. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  13233. > The representation of numbers is similar to that used in most
  13234. > programming languages. A number is represented in base 10 using decimal
  13235. > digits. It contains an integer component that may be prefixed with an
  13236. > optional minus sign, which may be followed by a fraction part and/or an
  13237. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  13238. > cannot be represented in the grammar below (such as Infinity and NaN)
  13239. > are not permitted.
  13240. This description includes both integer and floating-point numbers.
  13241. However, C++ allows more precise storage if it is known whether the number
  13242. is a signed integer, an unsigned integer or a floating-point number.
  13243. Therefore, three different types, @ref number_integer_t, @ref
  13244. number_unsigned_t and @ref number_float_t are used.
  13245. To store floating-point numbers in C++, a type is defined by the template
  13246. parameter @a NumberFloatType which chooses the type to use.
  13247. #### Default type
  13248. With the default values for @a NumberFloatType (`double`), the default
  13249. value for @a number_float_t is:
  13250. @code {.cpp}
  13251. double
  13252. @endcode
  13253. #### Default behavior
  13254. - The restrictions about leading zeros is not enforced in C++. Instead,
  13255. leading zeros in floating-point literals will be ignored. Internally,
  13256. the value will be stored as decimal number. For instance, the C++
  13257. floating-point literal `01.2` will be serialized to `1.2`. During
  13258. deserialization, leading zeros yield an error.
  13259. - Not-a-number (NaN) values will be serialized to `null`.
  13260. #### Limits
  13261. [RFC 7159](http://rfc7159.net/rfc7159) states:
  13262. > This specification allows implementations to set limits on the range and
  13263. > precision of numbers accepted. Since software that implements IEEE
  13264. > 754-2008 binary64 (double precision) numbers is generally available and
  13265. > widely used, good interoperability can be achieved by implementations
  13266. > that expect no more precision or range than these provide, in the sense
  13267. > that implementations will approximate JSON numbers within the expected
  13268. > precision.
  13269. This implementation does exactly follow this approach, as it uses double
  13270. precision floating-point numbers. Note values smaller than
  13271. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  13272. will be stored as NaN internally and be serialized to `null`.
  13273. #### Storage
  13274. Floating-point number values are stored directly inside a @ref basic_json
  13275. type.
  13276. @sa @ref number_integer_t -- type for number values (integer)
  13277. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  13278. @since version 1.0.0
  13279. */
  13280. using number_float_t = NumberFloatType;
  13281. /// @}
  13282. private:
  13283. /// helper for exception-safe object creation
  13284. template<typename T, typename... Args>
  13285. JSON_HEDLEY_RETURNS_NON_NULL
  13286. static T* create(Args&& ... args)
  13287. {
  13288. AllocatorType<T> alloc;
  13289. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  13290. auto deleter = [&](T * object)
  13291. {
  13292. AllocatorTraits::deallocate(alloc, object, 1);
  13293. };
  13294. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  13295. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  13296. assert(object != nullptr);
  13297. return object.release();
  13298. }
  13299. ////////////////////////
  13300. // JSON value storage //
  13301. ////////////////////////
  13302. /*!
  13303. @brief a JSON value
  13304. The actual storage for a JSON value of the @ref basic_json class. This
  13305. union combines the different storage types for the JSON value types
  13306. defined in @ref value_t.
  13307. JSON type | value_t type | used type
  13308. --------- | --------------- | ------------------------
  13309. object | object | pointer to @ref object_t
  13310. array | array | pointer to @ref array_t
  13311. string | string | pointer to @ref string_t
  13312. boolean | boolean | @ref boolean_t
  13313. number | number_integer | @ref number_integer_t
  13314. number | number_unsigned | @ref number_unsigned_t
  13315. number | number_float | @ref number_float_t
  13316. null | null | *no value is stored*
  13317. @note Variable-length types (objects, arrays, and strings) are stored as
  13318. pointers. The size of the union should not exceed 64 bits if the default
  13319. value types are used.
  13320. @since version 1.0.0
  13321. */
  13322. union json_value
  13323. {
  13324. /// object (stored with pointer to save storage)
  13325. object_t* object;
  13326. /// array (stored with pointer to save storage)
  13327. array_t* array;
  13328. /// string (stored with pointer to save storage)
  13329. string_t* string;
  13330. /// boolean
  13331. boolean_t boolean;
  13332. /// number (integer)
  13333. number_integer_t number_integer;
  13334. /// number (unsigned integer)
  13335. number_unsigned_t number_unsigned;
  13336. /// number (floating-point)
  13337. number_float_t number_float;
  13338. /// default constructor (for null values)
  13339. json_value() = default;
  13340. /// constructor for booleans
  13341. json_value(boolean_t v) noexcept : boolean(v) {}
  13342. /// constructor for numbers (integer)
  13343. json_value(number_integer_t v) noexcept : number_integer(v) {}
  13344. /// constructor for numbers (unsigned)
  13345. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  13346. /// constructor for numbers (floating-point)
  13347. json_value(number_float_t v) noexcept : number_float(v) {}
  13348. /// constructor for empty values of a given type
  13349. json_value(value_t t)
  13350. {
  13351. switch (t)
  13352. {
  13353. case value_t::object:
  13354. {
  13355. object = create<object_t>();
  13356. break;
  13357. }
  13358. case value_t::array:
  13359. {
  13360. array = create<array_t>();
  13361. break;
  13362. }
  13363. case value_t::string:
  13364. {
  13365. string = create<string_t>("");
  13366. break;
  13367. }
  13368. case value_t::boolean:
  13369. {
  13370. boolean = boolean_t(false);
  13371. break;
  13372. }
  13373. case value_t::number_integer:
  13374. {
  13375. number_integer = number_integer_t(0);
  13376. break;
  13377. }
  13378. case value_t::number_unsigned:
  13379. {
  13380. number_unsigned = number_unsigned_t(0);
  13381. break;
  13382. }
  13383. case value_t::number_float:
  13384. {
  13385. number_float = number_float_t(0.0);
  13386. break;
  13387. }
  13388. case value_t::null:
  13389. {
  13390. object = nullptr; // silence warning, see #821
  13391. break;
  13392. }
  13393. default:
  13394. {
  13395. object = nullptr; // silence warning, see #821
  13396. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  13397. {
  13398. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.1")); // LCOV_EXCL_LINE
  13399. }
  13400. break;
  13401. }
  13402. }
  13403. }
  13404. /// constructor for strings
  13405. json_value(const string_t& value)
  13406. {
  13407. string = create<string_t>(value);
  13408. }
  13409. /// constructor for rvalue strings
  13410. json_value(string_t&& value)
  13411. {
  13412. string = create<string_t>(std::move(value));
  13413. }
  13414. /// constructor for objects
  13415. json_value(const object_t& value)
  13416. {
  13417. object = create<object_t>(value);
  13418. }
  13419. /// constructor for rvalue objects
  13420. json_value(object_t&& value)
  13421. {
  13422. object = create<object_t>(std::move(value));
  13423. }
  13424. /// constructor for arrays
  13425. json_value(const array_t& value)
  13426. {
  13427. array = create<array_t>(value);
  13428. }
  13429. /// constructor for rvalue arrays
  13430. json_value(array_t&& value)
  13431. {
  13432. array = create<array_t>(std::move(value));
  13433. }
  13434. void destroy(value_t t) noexcept
  13435. {
  13436. switch (t)
  13437. {
  13438. case value_t::object:
  13439. {
  13440. AllocatorType<object_t> alloc;
  13441. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  13442. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  13443. break;
  13444. }
  13445. case value_t::array:
  13446. {
  13447. AllocatorType<array_t> alloc;
  13448. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  13449. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  13450. break;
  13451. }
  13452. case value_t::string:
  13453. {
  13454. AllocatorType<string_t> alloc;
  13455. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  13456. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  13457. break;
  13458. }
  13459. default:
  13460. {
  13461. break;
  13462. }
  13463. }
  13464. }
  13465. };
  13466. /*!
  13467. @brief checks the class invariants
  13468. This function asserts the class invariants. It needs to be called at the
  13469. end of every constructor to make sure that created objects respect the
  13470. invariant. Furthermore, it has to be called each time the type of a JSON
  13471. value is changed, because the invariant expresses a relationship between
  13472. @a m_type and @a m_value.
  13473. */
  13474. void assert_invariant() const noexcept
  13475. {
  13476. assert(m_type != value_t::object or m_value.object != nullptr);
  13477. assert(m_type != value_t::array or m_value.array != nullptr);
  13478. assert(m_type != value_t::string or m_value.string != nullptr);
  13479. }
  13480. public:
  13481. //////////////////////////
  13482. // JSON parser callback //
  13483. //////////////////////////
  13484. /*!
  13485. @brief parser event types
  13486. The parser callback distinguishes the following events:
  13487. - `object_start`: the parser read `{` and started to process a JSON object
  13488. - `key`: the parser read a key of a value in an object
  13489. - `object_end`: the parser read `}` and finished processing a JSON object
  13490. - `array_start`: the parser read `[` and started to process a JSON array
  13491. - `array_end`: the parser read `]` and finished processing a JSON array
  13492. - `value`: the parser finished reading a JSON value
  13493. @image html callback_events.png "Example when certain parse events are triggered"
  13494. @sa @ref parser_callback_t for more information and examples
  13495. */
  13496. using parse_event_t = typename parser::parse_event_t;
  13497. /*!
  13498. @brief per-element parser callback type
  13499. With a parser callback function, the result of parsing a JSON text can be
  13500. influenced. When passed to @ref parse, it is called on certain events
  13501. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  13502. depth @a depth and context JSON value @a parsed. The return value of the
  13503. callback function is a boolean indicating whether the element that emitted
  13504. the callback shall be kept or not.
  13505. We distinguish six scenarios (determined by the event type) in which the
  13506. callback function can be called. The following table describes the values
  13507. of the parameters @a depth, @a event, and @a parsed.
  13508. parameter @a event | description | parameter @a depth | parameter @a parsed
  13509. ------------------ | ----------- | ------------------ | -------------------
  13510. 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
  13511. 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
  13512. 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
  13513. 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
  13514. 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
  13515. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  13516. @image html callback_events.png "Example when certain parse events are triggered"
  13517. Discarding a value (i.e., returning `false`) has different effects
  13518. depending on the context in which function was called:
  13519. - Discarded values in structured types are skipped. That is, the parser
  13520. will behave as if the discarded value was never read.
  13521. - In case a value outside a structured type is skipped, it is replaced
  13522. with `null`. This case happens if the top-level element is skipped.
  13523. @param[in] depth the depth of the recursion during parsing
  13524. @param[in] event an event of type parse_event_t indicating the context in
  13525. the callback function has been called
  13526. @param[in,out] parsed the current intermediate parse result; note that
  13527. writing to this value has no effect for parse_event_t::key events
  13528. @return Whether the JSON value which called the function during parsing
  13529. should be kept (`true`) or not (`false`). In the latter case, it is either
  13530. skipped completely or replaced by an empty discarded object.
  13531. @sa @ref parse for examples
  13532. @since version 1.0.0
  13533. */
  13534. using parser_callback_t = typename parser::parser_callback_t;
  13535. //////////////////
  13536. // constructors //
  13537. //////////////////
  13538. /// @name constructors and destructors
  13539. /// Constructors of class @ref basic_json, copy/move constructor, copy
  13540. /// assignment, static functions creating objects, and the destructor.
  13541. /// @{
  13542. /*!
  13543. @brief create an empty value with a given type
  13544. Create an empty JSON value with a given type. The value will be default
  13545. initialized with an empty value which depends on the type:
  13546. Value type | initial value
  13547. ----------- | -------------
  13548. null | `null`
  13549. boolean | `false`
  13550. string | `""`
  13551. number | `0`
  13552. object | `{}`
  13553. array | `[]`
  13554. @param[in] v the type of the value to create
  13555. @complexity Constant.
  13556. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13557. changes to any JSON value.
  13558. @liveexample{The following code shows the constructor for different @ref
  13559. value_t values,basic_json__value_t}
  13560. @sa @ref clear() -- restores the postcondition of this constructor
  13561. @since version 1.0.0
  13562. */
  13563. basic_json(const value_t v)
  13564. : m_type(v), m_value(v)
  13565. {
  13566. assert_invariant();
  13567. }
  13568. /*!
  13569. @brief create a null object
  13570. Create a `null` JSON value. It either takes a null pointer as parameter
  13571. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  13572. The passed null pointer itself is not read -- it is only used to choose
  13573. the right constructor.
  13574. @complexity Constant.
  13575. @exceptionsafety No-throw guarantee: this constructor never throws
  13576. exceptions.
  13577. @liveexample{The following code shows the constructor with and without a
  13578. null pointer parameter.,basic_json__nullptr_t}
  13579. @since version 1.0.0
  13580. */
  13581. basic_json(std::nullptr_t = nullptr) noexcept
  13582. : basic_json(value_t::null)
  13583. {
  13584. assert_invariant();
  13585. }
  13586. /*!
  13587. @brief create a JSON value
  13588. This is a "catch all" constructor for all compatible JSON types; that is,
  13589. types for which a `to_json()` method exists. The constructor forwards the
  13590. parameter @a val to that method (to `json_serializer<U>::to_json` method
  13591. with `U = uncvref_t<CompatibleType>`, to be exact).
  13592. Template type @a CompatibleType includes, but is not limited to, the
  13593. following types:
  13594. - **arrays**: @ref array_t and all kinds of compatible containers such as
  13595. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  13596. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  13597. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  13598. which a @ref basic_json value can be constructed.
  13599. - **objects**: @ref object_t and all kinds of compatible associative
  13600. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  13601. and `std::unordered_multimap` with a `key_type` compatible to
  13602. @ref string_t and a `value_type` from which a @ref basic_json value can
  13603. be constructed.
  13604. - **strings**: @ref string_t, string literals, and all compatible string
  13605. containers can be used.
  13606. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  13607. @ref number_float_t, and all convertible number types such as `int`,
  13608. `size_t`, `int64_t`, `float` or `double` can be used.
  13609. - **boolean**: @ref boolean_t / `bool` can be used.
  13610. See the examples below.
  13611. @tparam CompatibleType a type such that:
  13612. - @a CompatibleType is not derived from `std::istream`,
  13613. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  13614. constructors),
  13615. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  13616. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  13617. @ref json_pointer, @ref iterator, etc ...)
  13618. - @ref @ref json_serializer<U> has a
  13619. `to_json(basic_json_t&, CompatibleType&&)` method
  13620. @tparam U = `uncvref_t<CompatibleType>`
  13621. @param[in] val the value to be forwarded to the respective constructor
  13622. @complexity Usually linear in the size of the passed @a val, also
  13623. depending on the implementation of the called `to_json()`
  13624. method.
  13625. @exceptionsafety Depends on the called constructor. For types directly
  13626. supported by the library (i.e., all types for which no `to_json()` function
  13627. was provided), strong guarantee holds: if an exception is thrown, there are
  13628. no changes to any JSON value.
  13629. @liveexample{The following code shows the constructor with several
  13630. compatible types.,basic_json__CompatibleType}
  13631. @since version 2.1.0
  13632. */
  13633. template <typename CompatibleType,
  13634. typename U = detail::uncvref_t<CompatibleType>,
  13635. detail::enable_if_t<
  13636. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  13637. basic_json(CompatibleType && val) noexcept(noexcept(
  13638. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  13639. std::forward<CompatibleType>(val))))
  13640. {
  13641. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  13642. assert_invariant();
  13643. }
  13644. /*!
  13645. @brief create a JSON value from an existing one
  13646. This is a constructor for existing @ref basic_json types.
  13647. It does not hijack copy/move constructors, since the parameter has different
  13648. template arguments than the current ones.
  13649. The constructor tries to convert the internal @ref m_value of the parameter.
  13650. @tparam BasicJsonType a type such that:
  13651. - @a BasicJsonType is a @ref basic_json type.
  13652. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  13653. @param[in] val the @ref basic_json value to be converted.
  13654. @complexity Usually linear in the size of the passed @a val, also
  13655. depending on the implementation of the called `to_json()`
  13656. method.
  13657. @exceptionsafety Depends on the called constructor. For types directly
  13658. supported by the library (i.e., all types for which no `to_json()` function
  13659. was provided), strong guarantee holds: if an exception is thrown, there are
  13660. no changes to any JSON value.
  13661. @since version 3.2.0
  13662. */
  13663. template <typename BasicJsonType,
  13664. detail::enable_if_t<
  13665. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  13666. basic_json(const BasicJsonType& val)
  13667. {
  13668. using other_boolean_t = typename BasicJsonType::boolean_t;
  13669. using other_number_float_t = typename BasicJsonType::number_float_t;
  13670. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  13671. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13672. using other_string_t = typename BasicJsonType::string_t;
  13673. using other_object_t = typename BasicJsonType::object_t;
  13674. using other_array_t = typename BasicJsonType::array_t;
  13675. switch (val.type())
  13676. {
  13677. case value_t::boolean:
  13678. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  13679. break;
  13680. case value_t::number_float:
  13681. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  13682. break;
  13683. case value_t::number_integer:
  13684. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  13685. break;
  13686. case value_t::number_unsigned:
  13687. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  13688. break;
  13689. case value_t::string:
  13690. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  13691. break;
  13692. case value_t::object:
  13693. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  13694. break;
  13695. case value_t::array:
  13696. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  13697. break;
  13698. case value_t::null:
  13699. *this = nullptr;
  13700. break;
  13701. case value_t::discarded:
  13702. m_type = value_t::discarded;
  13703. break;
  13704. default: // LCOV_EXCL_LINE
  13705. assert(false); // LCOV_EXCL_LINE
  13706. }
  13707. assert_invariant();
  13708. }
  13709. /*!
  13710. @brief create a container (array or object) from an initializer list
  13711. Creates a JSON value of type array or object from the passed initializer
  13712. list @a init. In case @a type_deduction is `true` (default), the type of
  13713. the JSON value to be created is deducted from the initializer list @a init
  13714. according to the following rules:
  13715. 1. If the list is empty, an empty JSON object value `{}` is created.
  13716. 2. If the list consists of pairs whose first element is a string, a JSON
  13717. object value is created where the first elements of the pairs are
  13718. treated as keys and the second elements are as values.
  13719. 3. In all other cases, an array is created.
  13720. The rules aim to create the best fit between a C++ initializer list and
  13721. JSON values. The rationale is as follows:
  13722. 1. The empty initializer list is written as `{}` which is exactly an empty
  13723. JSON object.
  13724. 2. C++ has no way of describing mapped types other than to list a list of
  13725. pairs. As JSON requires that keys must be of type string, rule 2 is the
  13726. weakest constraint one can pose on initializer lists to interpret them
  13727. as an object.
  13728. 3. In all other cases, the initializer list could not be interpreted as
  13729. JSON object type, so interpreting it as JSON array type is safe.
  13730. With the rules described above, the following JSON values cannot be
  13731. expressed by an initializer list:
  13732. - the empty array (`[]`): use @ref array(initializer_list_t)
  13733. with an empty initializer list in this case
  13734. - arrays whose elements satisfy rule 2: use @ref
  13735. array(initializer_list_t) with the same initializer list
  13736. in this case
  13737. @note When used without parentheses around an empty initializer list, @ref
  13738. basic_json() is called instead of this function, yielding the JSON null
  13739. value.
  13740. @param[in] init initializer list with JSON values
  13741. @param[in] type_deduction internal parameter; when set to `true`, the type
  13742. of the JSON value is deducted from the initializer list @a init; when set
  13743. to `false`, the type provided via @a manual_type is forced. This mode is
  13744. used by the functions @ref array(initializer_list_t) and
  13745. @ref object(initializer_list_t).
  13746. @param[in] manual_type internal parameter; when @a type_deduction is set
  13747. to `false`, the created JSON value will use the provided type (only @ref
  13748. value_t::array and @ref value_t::object are valid); when @a type_deduction
  13749. is set to `true`, this parameter has no effect
  13750. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  13751. `value_t::object`, but @a init contains an element which is not a pair
  13752. whose first element is a string. In this case, the constructor could not
  13753. create an object. If @a type_deduction would have be `true`, an array
  13754. would have been created. See @ref object(initializer_list_t)
  13755. for an example.
  13756. @complexity Linear in the size of the initializer list @a init.
  13757. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13758. changes to any JSON value.
  13759. @liveexample{The example below shows how JSON values are created from
  13760. initializer lists.,basic_json__list_init_t}
  13761. @sa @ref array(initializer_list_t) -- create a JSON array
  13762. value from an initializer list
  13763. @sa @ref object(initializer_list_t) -- create a JSON object
  13764. value from an initializer list
  13765. @since version 1.0.0
  13766. */
  13767. basic_json(initializer_list_t init,
  13768. bool type_deduction = true,
  13769. value_t manual_type = value_t::array)
  13770. {
  13771. // check if each element is an array with two elements whose first
  13772. // element is a string
  13773. bool is_an_object = std::all_of(init.begin(), init.end(),
  13774. [](const detail::json_ref<basic_json>& element_ref)
  13775. {
  13776. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  13777. });
  13778. // adjust type if type deduction is not wanted
  13779. if (not type_deduction)
  13780. {
  13781. // if array is wanted, do not create an object though possible
  13782. if (manual_type == value_t::array)
  13783. {
  13784. is_an_object = false;
  13785. }
  13786. // if object is wanted but impossible, throw an exception
  13787. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
  13788. {
  13789. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  13790. }
  13791. }
  13792. if (is_an_object)
  13793. {
  13794. // the initializer list is a list of pairs -> create object
  13795. m_type = value_t::object;
  13796. m_value = value_t::object;
  13797. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  13798. {
  13799. auto element = element_ref.moved_or_copied();
  13800. m_value.object->emplace(
  13801. std::move(*((*element.m_value.array)[0].m_value.string)),
  13802. std::move((*element.m_value.array)[1]));
  13803. });
  13804. }
  13805. else
  13806. {
  13807. // the initializer list describes an array -> create array
  13808. m_type = value_t::array;
  13809. m_value.array = create<array_t>(init.begin(), init.end());
  13810. }
  13811. assert_invariant();
  13812. }
  13813. /*!
  13814. @brief explicitly create an array from an initializer list
  13815. Creates a JSON array value from a given initializer list. That is, given a
  13816. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  13817. initializer list is empty, the empty array `[]` is created.
  13818. @note This function is only needed to express two edge cases that cannot
  13819. be realized with the initializer list constructor (@ref
  13820. basic_json(initializer_list_t, bool, value_t)). These cases
  13821. are:
  13822. 1. creating an array whose elements are all pairs whose first element is a
  13823. string -- in this case, the initializer list constructor would create an
  13824. object, taking the first elements as keys
  13825. 2. creating an empty array -- passing the empty initializer list to the
  13826. initializer list constructor yields an empty object
  13827. @param[in] init initializer list with JSON values to create an array from
  13828. (optional)
  13829. @return JSON array value
  13830. @complexity Linear in the size of @a init.
  13831. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13832. changes to any JSON value.
  13833. @liveexample{The following code shows an example for the `array`
  13834. function.,array}
  13835. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13836. create a JSON value from an initializer list
  13837. @sa @ref object(initializer_list_t) -- create a JSON object
  13838. value from an initializer list
  13839. @since version 1.0.0
  13840. */
  13841. JSON_HEDLEY_WARN_UNUSED_RESULT
  13842. static basic_json array(initializer_list_t init = {})
  13843. {
  13844. return basic_json(init, false, value_t::array);
  13845. }
  13846. /*!
  13847. @brief explicitly create an object from an initializer list
  13848. Creates a JSON object value from a given initializer list. The initializer
  13849. lists elements must be pairs, and their first elements must be strings. If
  13850. the initializer list is empty, the empty object `{}` is created.
  13851. @note This function is only added for symmetry reasons. In contrast to the
  13852. related function @ref array(initializer_list_t), there are
  13853. no cases which can only be expressed by this function. That is, any
  13854. initializer list @a init can also be passed to the initializer list
  13855. constructor @ref basic_json(initializer_list_t, bool, value_t).
  13856. @param[in] init initializer list to create an object from (optional)
  13857. @return JSON object value
  13858. @throw type_error.301 if @a init is not a list of pairs whose first
  13859. elements are strings. In this case, no object can be created. When such a
  13860. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  13861. an array would have been created from the passed initializer list @a init.
  13862. See example below.
  13863. @complexity Linear in the size of @a init.
  13864. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13865. changes to any JSON value.
  13866. @liveexample{The following code shows an example for the `object`
  13867. function.,object}
  13868. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  13869. create a JSON value from an initializer list
  13870. @sa @ref array(initializer_list_t) -- create a JSON array
  13871. value from an initializer list
  13872. @since version 1.0.0
  13873. */
  13874. JSON_HEDLEY_WARN_UNUSED_RESULT
  13875. static basic_json object(initializer_list_t init = {})
  13876. {
  13877. return basic_json(init, false, value_t::object);
  13878. }
  13879. /*!
  13880. @brief construct an array with count copies of given value
  13881. Constructs a JSON array value by creating @a cnt copies of a passed value.
  13882. In case @a cnt is `0`, an empty array is created.
  13883. @param[in] cnt the number of JSON copies of @a val to create
  13884. @param[in] val the JSON value to copy
  13885. @post `std::distance(begin(),end()) == cnt` holds.
  13886. @complexity Linear in @a cnt.
  13887. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13888. changes to any JSON value.
  13889. @liveexample{The following code shows examples for the @ref
  13890. basic_json(size_type\, const basic_json&)
  13891. constructor.,basic_json__size_type_basic_json}
  13892. @since version 1.0.0
  13893. */
  13894. basic_json(size_type cnt, const basic_json& val)
  13895. : m_type(value_t::array)
  13896. {
  13897. m_value.array = create<array_t>(cnt, val);
  13898. assert_invariant();
  13899. }
  13900. /*!
  13901. @brief construct a JSON container given an iterator range
  13902. Constructs the JSON value with the contents of the range `[first, last)`.
  13903. The semantics depends on the different types a JSON value can have:
  13904. - In case of a null type, invalid_iterator.206 is thrown.
  13905. - In case of other primitive types (number, boolean, or string), @a first
  13906. must be `begin()` and @a last must be `end()`. In this case, the value is
  13907. copied. Otherwise, invalid_iterator.204 is thrown.
  13908. - In case of structured types (array, object), the constructor behaves as
  13909. similar versions for `std::vector` or `std::map`; that is, a JSON array
  13910. or object is constructed from the values in the range.
  13911. @tparam InputIT an input iterator type (@ref iterator or @ref
  13912. const_iterator)
  13913. @param[in] first begin of the range to copy from (included)
  13914. @param[in] last end of the range to copy from (excluded)
  13915. @pre Iterators @a first and @a last must be initialized. **This
  13916. precondition is enforced with an assertion (see warning).** If
  13917. assertions are switched off, a violation of this precondition yields
  13918. undefined behavior.
  13919. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  13920. checked efficiently. Only certain edge cases are detected; see the
  13921. description of the exceptions below. A violation of this precondition
  13922. yields undefined behavior.
  13923. @warning A precondition is enforced with a runtime assertion that will
  13924. result in calling `std::abort` if this precondition is not met.
  13925. Assertions can be disabled by defining `NDEBUG` at compile time.
  13926. See https://en.cppreference.com/w/cpp/error/assert for more
  13927. information.
  13928. @throw invalid_iterator.201 if iterators @a first and @a last are not
  13929. compatible (i.e., do not belong to the same JSON value). In this case,
  13930. the range `[first, last)` is undefined.
  13931. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  13932. primitive type (number, boolean, or string), but @a first does not point
  13933. to the first element any more. In this case, the range `[first, last)` is
  13934. undefined. See example code below.
  13935. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  13936. null value. In this case, the range `[first, last)` is undefined.
  13937. @complexity Linear in distance between @a first and @a last.
  13938. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13939. changes to any JSON value.
  13940. @liveexample{The example below shows several ways to create JSON values by
  13941. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  13942. @since version 1.0.0
  13943. */
  13944. template<class InputIT, typename std::enable_if<
  13945. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  13946. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  13947. basic_json(InputIT first, InputIT last)
  13948. {
  13949. assert(first.m_object != nullptr);
  13950. assert(last.m_object != nullptr);
  13951. // make sure iterator fits the current value
  13952. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  13953. {
  13954. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  13955. }
  13956. // copy type from first iterator
  13957. m_type = first.m_object->m_type;
  13958. // check if iterator range is complete for primitive values
  13959. switch (m_type)
  13960. {
  13961. case value_t::boolean:
  13962. case value_t::number_float:
  13963. case value_t::number_integer:
  13964. case value_t::number_unsigned:
  13965. case value_t::string:
  13966. {
  13967. if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  13968. or not last.m_it.primitive_iterator.is_end()))
  13969. {
  13970. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13971. }
  13972. break;
  13973. }
  13974. default:
  13975. break;
  13976. }
  13977. switch (m_type)
  13978. {
  13979. case value_t::number_integer:
  13980. {
  13981. m_value.number_integer = first.m_object->m_value.number_integer;
  13982. break;
  13983. }
  13984. case value_t::number_unsigned:
  13985. {
  13986. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  13987. break;
  13988. }
  13989. case value_t::number_float:
  13990. {
  13991. m_value.number_float = first.m_object->m_value.number_float;
  13992. break;
  13993. }
  13994. case value_t::boolean:
  13995. {
  13996. m_value.boolean = first.m_object->m_value.boolean;
  13997. break;
  13998. }
  13999. case value_t::string:
  14000. {
  14001. m_value = *first.m_object->m_value.string;
  14002. break;
  14003. }
  14004. case value_t::object:
  14005. {
  14006. m_value.object = create<object_t>(first.m_it.object_iterator,
  14007. last.m_it.object_iterator);
  14008. break;
  14009. }
  14010. case value_t::array:
  14011. {
  14012. m_value.array = create<array_t>(first.m_it.array_iterator,
  14013. last.m_it.array_iterator);
  14014. break;
  14015. }
  14016. default:
  14017. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  14018. std::string(first.m_object->type_name())));
  14019. }
  14020. assert_invariant();
  14021. }
  14022. ///////////////////////////////////////
  14023. // other constructors and destructor //
  14024. ///////////////////////////////////////
  14025. /// @private
  14026. basic_json(const detail::json_ref<basic_json>& ref)
  14027. : basic_json(ref.moved_or_copied())
  14028. {}
  14029. /*!
  14030. @brief copy constructor
  14031. Creates a copy of a given JSON value.
  14032. @param[in] other the JSON value to copy
  14033. @post `*this == other`
  14034. @complexity Linear in the size of @a other.
  14035. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14036. changes to any JSON value.
  14037. @requirement This function helps `basic_json` satisfying the
  14038. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14039. requirements:
  14040. - The complexity is linear.
  14041. - As postcondition, it holds: `other == basic_json(other)`.
  14042. @liveexample{The following code shows an example for the copy
  14043. constructor.,basic_json__basic_json}
  14044. @since version 1.0.0
  14045. */
  14046. basic_json(const basic_json& other)
  14047. : m_type(other.m_type)
  14048. {
  14049. // check of passed value is valid
  14050. other.assert_invariant();
  14051. switch (m_type)
  14052. {
  14053. case value_t::object:
  14054. {
  14055. m_value = *other.m_value.object;
  14056. break;
  14057. }
  14058. case value_t::array:
  14059. {
  14060. m_value = *other.m_value.array;
  14061. break;
  14062. }
  14063. case value_t::string:
  14064. {
  14065. m_value = *other.m_value.string;
  14066. break;
  14067. }
  14068. case value_t::boolean:
  14069. {
  14070. m_value = other.m_value.boolean;
  14071. break;
  14072. }
  14073. case value_t::number_integer:
  14074. {
  14075. m_value = other.m_value.number_integer;
  14076. break;
  14077. }
  14078. case value_t::number_unsigned:
  14079. {
  14080. m_value = other.m_value.number_unsigned;
  14081. break;
  14082. }
  14083. case value_t::number_float:
  14084. {
  14085. m_value = other.m_value.number_float;
  14086. break;
  14087. }
  14088. default:
  14089. break;
  14090. }
  14091. assert_invariant();
  14092. }
  14093. /*!
  14094. @brief move constructor
  14095. Move constructor. Constructs a JSON value with the contents of the given
  14096. value @a other using move semantics. It "steals" the resources from @a
  14097. other and leaves it as JSON null value.
  14098. @param[in,out] other value to move to this object
  14099. @post `*this` has the same value as @a other before the call.
  14100. @post @a other is a JSON null value.
  14101. @complexity Constant.
  14102. @exceptionsafety No-throw guarantee: this constructor never throws
  14103. exceptions.
  14104. @requirement This function helps `basic_json` satisfying the
  14105. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  14106. requirements.
  14107. @liveexample{The code below shows the move constructor explicitly called
  14108. via std::move.,basic_json__moveconstructor}
  14109. @since version 1.0.0
  14110. */
  14111. basic_json(basic_json&& other) noexcept
  14112. : m_type(std::move(other.m_type)),
  14113. m_value(std::move(other.m_value))
  14114. {
  14115. // check that passed value is valid
  14116. other.assert_invariant();
  14117. // invalidate payload
  14118. other.m_type = value_t::null;
  14119. other.m_value = {};
  14120. assert_invariant();
  14121. }
  14122. /*!
  14123. @brief copy assignment
  14124. Copy assignment operator. Copies a JSON value via the "copy and swap"
  14125. strategy: It is expressed in terms of the copy constructor, destructor,
  14126. and the `swap()` member function.
  14127. @param[in] other value to copy from
  14128. @complexity Linear.
  14129. @requirement This function helps `basic_json` satisfying the
  14130. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14131. requirements:
  14132. - The complexity is linear.
  14133. @liveexample{The code below shows and example for the copy assignment. It
  14134. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  14135. copy of `a` (which is the null value after the swap) is
  14136. destroyed.,basic_json__copyassignment}
  14137. @since version 1.0.0
  14138. */
  14139. basic_json& operator=(basic_json other) noexcept (
  14140. std::is_nothrow_move_constructible<value_t>::value and
  14141. std::is_nothrow_move_assignable<value_t>::value and
  14142. std::is_nothrow_move_constructible<json_value>::value and
  14143. std::is_nothrow_move_assignable<json_value>::value
  14144. )
  14145. {
  14146. // check that passed value is valid
  14147. other.assert_invariant();
  14148. using std::swap;
  14149. swap(m_type, other.m_type);
  14150. swap(m_value, other.m_value);
  14151. assert_invariant();
  14152. return *this;
  14153. }
  14154. /*!
  14155. @brief destructor
  14156. Destroys the JSON value and frees all allocated memory.
  14157. @complexity Linear.
  14158. @requirement This function helps `basic_json` satisfying the
  14159. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14160. requirements:
  14161. - The complexity is linear.
  14162. - All stored elements are destroyed and all memory is freed.
  14163. @since version 1.0.0
  14164. */
  14165. ~basic_json() noexcept
  14166. {
  14167. assert_invariant();
  14168. m_value.destroy(m_type);
  14169. }
  14170. /// @}
  14171. public:
  14172. ///////////////////////
  14173. // object inspection //
  14174. ///////////////////////
  14175. /// @name object inspection
  14176. /// Functions to inspect the type of a JSON value.
  14177. /// @{
  14178. /*!
  14179. @brief serialization
  14180. Serialization function for JSON values. The function tries to mimic
  14181. Python's `json.dumps()` function, and currently supports its @a indent
  14182. and @a ensure_ascii parameters.
  14183. @param[in] indent If indent is nonnegative, then array elements and object
  14184. members will be pretty-printed with that indent level. An indent level of
  14185. `0` will only insert newlines. `-1` (the default) selects the most compact
  14186. representation.
  14187. @param[in] indent_char The character to use for indentation if @a indent is
  14188. greater than `0`. The default is ` ` (space).
  14189. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  14190. in the output are escaped with `\uXXXX` sequences, and the result consists
  14191. of ASCII characters only.
  14192. @param[in] error_handler how to react on decoding errors; there are three
  14193. possible values: `strict` (throws and exception in case a decoding error
  14194. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  14195. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  14196. @return string containing the serialization of the JSON value
  14197. @throw type_error.316 if a string stored inside the JSON value is not
  14198. UTF-8 encoded
  14199. @complexity Linear.
  14200. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14201. changes in the JSON value.
  14202. @liveexample{The following example shows the effect of different @a indent\,
  14203. @a indent_char\, and @a ensure_ascii parameters to the result of the
  14204. serialization.,dump}
  14205. @see https://docs.python.org/2/library/json.html#json.dump
  14206. @since version 1.0.0; indentation character @a indent_char, option
  14207. @a ensure_ascii and exceptions added in version 3.0.0; error
  14208. handlers added in version 3.4.0.
  14209. */
  14210. string_t dump(const int indent = -1,
  14211. const char indent_char = ' ',
  14212. const bool ensure_ascii = false,
  14213. const error_handler_t error_handler = error_handler_t::strict) const
  14214. {
  14215. string_t result;
  14216. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  14217. if (indent >= 0)
  14218. {
  14219. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  14220. }
  14221. else
  14222. {
  14223. s.dump(*this, false, ensure_ascii, 0);
  14224. }
  14225. return result;
  14226. }
  14227. /*!
  14228. @brief return the type of the JSON value (explicit)
  14229. Return the type of the JSON value as a value from the @ref value_t
  14230. enumeration.
  14231. @return the type of the JSON value
  14232. Value type | return value
  14233. ------------------------- | -------------------------
  14234. null | value_t::null
  14235. boolean | value_t::boolean
  14236. string | value_t::string
  14237. number (integer) | value_t::number_integer
  14238. number (unsigned integer) | value_t::number_unsigned
  14239. number (floating-point) | value_t::number_float
  14240. object | value_t::object
  14241. array | value_t::array
  14242. discarded | value_t::discarded
  14243. @complexity Constant.
  14244. @exceptionsafety No-throw guarantee: this member function never throws
  14245. exceptions.
  14246. @liveexample{The following code exemplifies `type()` for all JSON
  14247. types.,type}
  14248. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  14249. @sa @ref type_name() -- return the type as string
  14250. @since version 1.0.0
  14251. */
  14252. constexpr value_t type() const noexcept
  14253. {
  14254. return m_type;
  14255. }
  14256. /*!
  14257. @brief return whether type is primitive
  14258. This function returns true if and only if the JSON type is primitive
  14259. (string, number, boolean, or null).
  14260. @return `true` if type is primitive (string, number, boolean, or null),
  14261. `false` otherwise.
  14262. @complexity Constant.
  14263. @exceptionsafety No-throw guarantee: this member function never throws
  14264. exceptions.
  14265. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  14266. types.,is_primitive}
  14267. @sa @ref is_structured() -- returns whether JSON value is structured
  14268. @sa @ref is_null() -- returns whether JSON value is `null`
  14269. @sa @ref is_string() -- returns whether JSON value is a string
  14270. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  14271. @sa @ref is_number() -- returns whether JSON value is a number
  14272. @since version 1.0.0
  14273. */
  14274. constexpr bool is_primitive() const noexcept
  14275. {
  14276. return is_null() or is_string() or is_boolean() or is_number();
  14277. }
  14278. /*!
  14279. @brief return whether type is structured
  14280. This function returns true if and only if the JSON type is structured
  14281. (array or object).
  14282. @return `true` if type is structured (array or object), `false` otherwise.
  14283. @complexity Constant.
  14284. @exceptionsafety No-throw guarantee: this member function never throws
  14285. exceptions.
  14286. @liveexample{The following code exemplifies `is_structured()` for all JSON
  14287. types.,is_structured}
  14288. @sa @ref is_primitive() -- returns whether value is primitive
  14289. @sa @ref is_array() -- returns whether value is an array
  14290. @sa @ref is_object() -- returns whether value is an object
  14291. @since version 1.0.0
  14292. */
  14293. constexpr bool is_structured() const noexcept
  14294. {
  14295. return is_array() or is_object();
  14296. }
  14297. /*!
  14298. @brief return whether value is null
  14299. This function returns true if and only if the JSON value is null.
  14300. @return `true` if type is null, `false` otherwise.
  14301. @complexity Constant.
  14302. @exceptionsafety No-throw guarantee: this member function never throws
  14303. exceptions.
  14304. @liveexample{The following code exemplifies `is_null()` for all JSON
  14305. types.,is_null}
  14306. @since version 1.0.0
  14307. */
  14308. constexpr bool is_null() const noexcept
  14309. {
  14310. return m_type == value_t::null;
  14311. }
  14312. /*!
  14313. @brief return whether value is a boolean
  14314. This function returns true if and only if the JSON value is a boolean.
  14315. @return `true` if type is boolean, `false` otherwise.
  14316. @complexity Constant.
  14317. @exceptionsafety No-throw guarantee: this member function never throws
  14318. exceptions.
  14319. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  14320. types.,is_boolean}
  14321. @since version 1.0.0
  14322. */
  14323. constexpr bool is_boolean() const noexcept
  14324. {
  14325. return m_type == value_t::boolean;
  14326. }
  14327. /*!
  14328. @brief return whether value is a number
  14329. This function returns true if and only if the JSON value is a number. This
  14330. includes both integer (signed and unsigned) and floating-point values.
  14331. @return `true` if type is number (regardless whether integer, unsigned
  14332. integer or floating-type), `false` otherwise.
  14333. @complexity Constant.
  14334. @exceptionsafety No-throw guarantee: this member function never throws
  14335. exceptions.
  14336. @liveexample{The following code exemplifies `is_number()` for all JSON
  14337. types.,is_number}
  14338. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14339. integer number
  14340. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14341. number
  14342. @sa @ref is_number_float() -- check if value is a floating-point number
  14343. @since version 1.0.0
  14344. */
  14345. constexpr bool is_number() const noexcept
  14346. {
  14347. return is_number_integer() or is_number_float();
  14348. }
  14349. /*!
  14350. @brief return whether value is an integer number
  14351. This function returns true if and only if the JSON value is a signed or
  14352. unsigned integer number. This excludes floating-point values.
  14353. @return `true` if type is an integer or unsigned integer number, `false`
  14354. otherwise.
  14355. @complexity Constant.
  14356. @exceptionsafety No-throw guarantee: this member function never throws
  14357. exceptions.
  14358. @liveexample{The following code exemplifies `is_number_integer()` for all
  14359. JSON types.,is_number_integer}
  14360. @sa @ref is_number() -- check if value is a number
  14361. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14362. number
  14363. @sa @ref is_number_float() -- check if value is a floating-point number
  14364. @since version 1.0.0
  14365. */
  14366. constexpr bool is_number_integer() const noexcept
  14367. {
  14368. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  14369. }
  14370. /*!
  14371. @brief return whether value is an unsigned integer number
  14372. This function returns true if and only if the JSON value is an unsigned
  14373. integer number. This excludes floating-point and signed integer values.
  14374. @return `true` if type is an unsigned integer number, `false` otherwise.
  14375. @complexity Constant.
  14376. @exceptionsafety No-throw guarantee: this member function never throws
  14377. exceptions.
  14378. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  14379. JSON types.,is_number_unsigned}
  14380. @sa @ref is_number() -- check if value is a number
  14381. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  14382. integer number
  14383. @sa @ref is_number_float() -- check if value is a floating-point number
  14384. @since version 2.0.0
  14385. */
  14386. constexpr bool is_number_unsigned() const noexcept
  14387. {
  14388. return m_type == value_t::number_unsigned;
  14389. }
  14390. /*!
  14391. @brief return whether value is a floating-point number
  14392. This function returns true if and only if the JSON value is a
  14393. floating-point number. This excludes signed and unsigned integer values.
  14394. @return `true` if type is a floating-point number, `false` otherwise.
  14395. @complexity Constant.
  14396. @exceptionsafety No-throw guarantee: this member function never throws
  14397. exceptions.
  14398. @liveexample{The following code exemplifies `is_number_float()` for all
  14399. JSON types.,is_number_float}
  14400. @sa @ref is_number() -- check if value is number
  14401. @sa @ref is_number_integer() -- check if value is an integer number
  14402. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  14403. number
  14404. @since version 1.0.0
  14405. */
  14406. constexpr bool is_number_float() const noexcept
  14407. {
  14408. return m_type == value_t::number_float;
  14409. }
  14410. /*!
  14411. @brief return whether value is an object
  14412. This function returns true if and only if the JSON value is an object.
  14413. @return `true` if type is object, `false` otherwise.
  14414. @complexity Constant.
  14415. @exceptionsafety No-throw guarantee: this member function never throws
  14416. exceptions.
  14417. @liveexample{The following code exemplifies `is_object()` for all JSON
  14418. types.,is_object}
  14419. @since version 1.0.0
  14420. */
  14421. constexpr bool is_object() const noexcept
  14422. {
  14423. return m_type == value_t::object;
  14424. }
  14425. /*!
  14426. @brief return whether value is an array
  14427. This function returns true if and only if the JSON value is an array.
  14428. @return `true` if type is array, `false` otherwise.
  14429. @complexity Constant.
  14430. @exceptionsafety No-throw guarantee: this member function never throws
  14431. exceptions.
  14432. @liveexample{The following code exemplifies `is_array()` for all JSON
  14433. types.,is_array}
  14434. @since version 1.0.0
  14435. */
  14436. constexpr bool is_array() const noexcept
  14437. {
  14438. return m_type == value_t::array;
  14439. }
  14440. /*!
  14441. @brief return whether value is a string
  14442. This function returns true if and only if the JSON value is a string.
  14443. @return `true` if type is string, `false` otherwise.
  14444. @complexity Constant.
  14445. @exceptionsafety No-throw guarantee: this member function never throws
  14446. exceptions.
  14447. @liveexample{The following code exemplifies `is_string()` for all JSON
  14448. types.,is_string}
  14449. @since version 1.0.0
  14450. */
  14451. constexpr bool is_string() const noexcept
  14452. {
  14453. return m_type == value_t::string;
  14454. }
  14455. /*!
  14456. @brief return whether value is discarded
  14457. This function returns true if and only if the JSON value was discarded
  14458. during parsing with a callback function (see @ref parser_callback_t).
  14459. @note This function will always be `false` for JSON values after parsing.
  14460. That is, discarded values can only occur during parsing, but will be
  14461. removed when inside a structured value or replaced by null in other cases.
  14462. @return `true` if type is discarded, `false` otherwise.
  14463. @complexity Constant.
  14464. @exceptionsafety No-throw guarantee: this member function never throws
  14465. exceptions.
  14466. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  14467. types.,is_discarded}
  14468. @since version 1.0.0
  14469. */
  14470. constexpr bool is_discarded() const noexcept
  14471. {
  14472. return m_type == value_t::discarded;
  14473. }
  14474. /*!
  14475. @brief return the type of the JSON value (implicit)
  14476. Implicitly return the type of the JSON value as a value from the @ref
  14477. value_t enumeration.
  14478. @return the type of the JSON value
  14479. @complexity Constant.
  14480. @exceptionsafety No-throw guarantee: this member function never throws
  14481. exceptions.
  14482. @liveexample{The following code exemplifies the @ref value_t operator for
  14483. all JSON types.,operator__value_t}
  14484. @sa @ref type() -- return the type of the JSON value (explicit)
  14485. @sa @ref type_name() -- return the type as string
  14486. @since version 1.0.0
  14487. */
  14488. constexpr operator value_t() const noexcept
  14489. {
  14490. return m_type;
  14491. }
  14492. /// @}
  14493. private:
  14494. //////////////////
  14495. // value access //
  14496. //////////////////
  14497. /// get a boolean (explicit)
  14498. boolean_t get_impl(boolean_t* /*unused*/) const
  14499. {
  14500. if (JSON_HEDLEY_LIKELY(is_boolean()))
  14501. {
  14502. return m_value.boolean;
  14503. }
  14504. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  14505. }
  14506. /// get a pointer to the value (object)
  14507. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  14508. {
  14509. return is_object() ? m_value.object : nullptr;
  14510. }
  14511. /// get a pointer to the value (object)
  14512. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  14513. {
  14514. return is_object() ? m_value.object : nullptr;
  14515. }
  14516. /// get a pointer to the value (array)
  14517. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  14518. {
  14519. return is_array() ? m_value.array : nullptr;
  14520. }
  14521. /// get a pointer to the value (array)
  14522. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  14523. {
  14524. return is_array() ? m_value.array : nullptr;
  14525. }
  14526. /// get a pointer to the value (string)
  14527. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  14528. {
  14529. return is_string() ? m_value.string : nullptr;
  14530. }
  14531. /// get a pointer to the value (string)
  14532. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  14533. {
  14534. return is_string() ? m_value.string : nullptr;
  14535. }
  14536. /// get a pointer to the value (boolean)
  14537. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  14538. {
  14539. return is_boolean() ? &m_value.boolean : nullptr;
  14540. }
  14541. /// get a pointer to the value (boolean)
  14542. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  14543. {
  14544. return is_boolean() ? &m_value.boolean : nullptr;
  14545. }
  14546. /// get a pointer to the value (integer number)
  14547. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  14548. {
  14549. return is_number_integer() ? &m_value.number_integer : nullptr;
  14550. }
  14551. /// get a pointer to the value (integer number)
  14552. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  14553. {
  14554. return is_number_integer() ? &m_value.number_integer : nullptr;
  14555. }
  14556. /// get a pointer to the value (unsigned number)
  14557. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  14558. {
  14559. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14560. }
  14561. /// get a pointer to the value (unsigned number)
  14562. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  14563. {
  14564. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  14565. }
  14566. /// get a pointer to the value (floating-point number)
  14567. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  14568. {
  14569. return is_number_float() ? &m_value.number_float : nullptr;
  14570. }
  14571. /// get a pointer to the value (floating-point number)
  14572. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  14573. {
  14574. return is_number_float() ? &m_value.number_float : nullptr;
  14575. }
  14576. /*!
  14577. @brief helper function to implement get_ref()
  14578. This function helps to implement get_ref() without code duplication for
  14579. const and non-const overloads
  14580. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  14581. @throw type_error.303 if ReferenceType does not match underlying value
  14582. type of the current JSON
  14583. */
  14584. template<typename ReferenceType, typename ThisType>
  14585. static ReferenceType get_ref_impl(ThisType& obj)
  14586. {
  14587. // delegate the call to get_ptr<>()
  14588. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  14589. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  14590. {
  14591. return *ptr;
  14592. }
  14593. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  14594. }
  14595. public:
  14596. /// @name value access
  14597. /// Direct access to the stored value of a JSON value.
  14598. /// @{
  14599. /*!
  14600. @brief get special-case overload
  14601. This overloads avoids a lot of template boilerplate, it can be seen as the
  14602. identity method
  14603. @tparam BasicJsonType == @ref basic_json
  14604. @return a copy of *this
  14605. @complexity Constant.
  14606. @since version 2.1.0
  14607. */
  14608. template<typename BasicJsonType, detail::enable_if_t<
  14609. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  14610. int> = 0>
  14611. basic_json get() const
  14612. {
  14613. return *this;
  14614. }
  14615. /*!
  14616. @brief get special-case overload
  14617. This overloads converts the current @ref basic_json in a different
  14618. @ref basic_json type
  14619. @tparam BasicJsonType == @ref basic_json
  14620. @return a copy of *this, converted into @tparam BasicJsonType
  14621. @complexity Depending on the implementation of the called `from_json()`
  14622. method.
  14623. @since version 3.2.0
  14624. */
  14625. template<typename BasicJsonType, detail::enable_if_t<
  14626. not std::is_same<BasicJsonType, basic_json>::value and
  14627. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  14628. BasicJsonType get() const
  14629. {
  14630. return *this;
  14631. }
  14632. /*!
  14633. @brief get a value (explicit)
  14634. Explicit type conversion between the JSON value and a compatible value
  14635. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14636. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14637. The value is converted by calling the @ref json_serializer<ValueType>
  14638. `from_json()` method.
  14639. The function is equivalent to executing
  14640. @code {.cpp}
  14641. ValueType ret;
  14642. JSONSerializer<ValueType>::from_json(*this, ret);
  14643. return ret;
  14644. @endcode
  14645. This overloads is chosen if:
  14646. - @a ValueType is not @ref basic_json,
  14647. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14648. `void from_json(const basic_json&, ValueType&)`, and
  14649. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  14650. the form `ValueType from_json(const basic_json&)`
  14651. @tparam ValueTypeCV the provided value type
  14652. @tparam ValueType the returned value type
  14653. @return copy of the JSON value, converted to @a ValueType
  14654. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14655. @liveexample{The example below shows several conversions from JSON values
  14656. to other types. There a few things to note: (1) Floating-point numbers can
  14657. be converted to integers\, (2) A JSON array can be converted to a standard
  14658. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14659. associative containers such as `std::unordered_map<std::string\,
  14660. json>`.,get__ValueType_const}
  14661. @since version 2.1.0
  14662. */
  14663. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14664. detail::enable_if_t <
  14665. not detail::is_basic_json<ValueType>::value and
  14666. detail::has_from_json<basic_json_t, ValueType>::value and
  14667. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14668. int> = 0>
  14669. ValueType get() const noexcept(noexcept(
  14670. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  14671. {
  14672. // we cannot static_assert on ValueTypeCV being non-const, because
  14673. // there is support for get<const basic_json_t>(), which is why we
  14674. // still need the uncvref
  14675. static_assert(not std::is_reference<ValueTypeCV>::value,
  14676. "get() cannot be used with reference types, you might want to use get_ref()");
  14677. static_assert(std::is_default_constructible<ValueType>::value,
  14678. "types must be DefaultConstructible when used with get()");
  14679. ValueType ret;
  14680. JSONSerializer<ValueType>::from_json(*this, ret);
  14681. return ret;
  14682. }
  14683. /*!
  14684. @brief get a value (explicit); special case
  14685. Explicit type conversion between the JSON value and a compatible value
  14686. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  14687. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  14688. The value is converted by calling the @ref json_serializer<ValueType>
  14689. `from_json()` method.
  14690. The function is equivalent to executing
  14691. @code {.cpp}
  14692. return JSONSerializer<ValueTypeCV>::from_json(*this);
  14693. @endcode
  14694. This overloads is chosen if:
  14695. - @a ValueType is not @ref basic_json and
  14696. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14697. `ValueType from_json(const basic_json&)`
  14698. @note If @ref json_serializer<ValueType> has both overloads of
  14699. `from_json()`, this one is chosen.
  14700. @tparam ValueTypeCV the provided value type
  14701. @tparam ValueType the returned value type
  14702. @return copy of the JSON value, converted to @a ValueType
  14703. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14704. @since version 2.1.0
  14705. */
  14706. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  14707. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  14708. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  14709. int> = 0>
  14710. ValueType get() const noexcept(noexcept(
  14711. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  14712. {
  14713. static_assert(not std::is_reference<ValueTypeCV>::value,
  14714. "get() cannot be used with reference types, you might want to use get_ref()");
  14715. return JSONSerializer<ValueType>::from_json(*this);
  14716. }
  14717. /*!
  14718. @brief get a value (explicit)
  14719. Explicit type conversion between the JSON value and a compatible value.
  14720. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  14721. `from_json()` method.
  14722. The function is equivalent to executing
  14723. @code {.cpp}
  14724. ValueType v;
  14725. JSONSerializer<ValueType>::from_json(*this, v);
  14726. @endcode
  14727. This overloads is chosen if:
  14728. - @a ValueType is not @ref basic_json,
  14729. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  14730. `void from_json(const basic_json&, ValueType&)`, and
  14731. @tparam ValueType the input parameter type.
  14732. @return the input parameter, allowing chaining calls.
  14733. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  14734. @liveexample{The example below shows several conversions from JSON values
  14735. to other types. There a few things to note: (1) Floating-point numbers can
  14736. be converted to integers\, (2) A JSON array can be converted to a standard
  14737. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14738. associative containers such as `std::unordered_map<std::string\,
  14739. json>`.,get_to}
  14740. @since version 3.3.0
  14741. */
  14742. template<typename ValueType,
  14743. detail::enable_if_t <
  14744. not detail::is_basic_json<ValueType>::value and
  14745. detail::has_from_json<basic_json_t, ValueType>::value,
  14746. int> = 0>
  14747. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  14748. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  14749. {
  14750. JSONSerializer<ValueType>::from_json(*this, v);
  14751. return v;
  14752. }
  14753. template <
  14754. typename T, std::size_t N,
  14755. typename Array = T (&)[N],
  14756. detail::enable_if_t <
  14757. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  14758. Array get_to(T (&v)[N]) const
  14759. noexcept(noexcept(JSONSerializer<Array>::from_json(
  14760. std::declval<const basic_json_t&>(), v)))
  14761. {
  14762. JSONSerializer<Array>::from_json(*this, v);
  14763. return v;
  14764. }
  14765. /*!
  14766. @brief get a pointer value (implicit)
  14767. Implicit pointer access to the internally stored JSON value. No copies are
  14768. made.
  14769. @warning Writing data to the pointee of the result yields an undefined
  14770. state.
  14771. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14772. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14773. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  14774. assertion.
  14775. @return pointer to the internally stored JSON value if the requested
  14776. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14777. @complexity Constant.
  14778. @liveexample{The example below shows how pointers to internal values of a
  14779. JSON value can be requested. Note that no type conversions are made and a
  14780. `nullptr` is returned if the value and the requested pointer type does not
  14781. match.,get_ptr}
  14782. @since version 1.0.0
  14783. */
  14784. template<typename PointerType, typename std::enable_if<
  14785. std::is_pointer<PointerType>::value, int>::type = 0>
  14786. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14787. {
  14788. // delegate the call to get_impl_ptr<>()
  14789. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14790. }
  14791. /*!
  14792. @brief get a pointer value (implicit)
  14793. @copydoc get_ptr()
  14794. */
  14795. template<typename PointerType, typename std::enable_if<
  14796. std::is_pointer<PointerType>::value and
  14797. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  14798. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  14799. {
  14800. // delegate the call to get_impl_ptr<>() const
  14801. return get_impl_ptr(static_cast<PointerType>(nullptr));
  14802. }
  14803. /*!
  14804. @brief get a pointer value (explicit)
  14805. Explicit pointer access to the internally stored JSON value. No copies are
  14806. made.
  14807. @warning The pointer becomes invalid if the underlying JSON object
  14808. changes.
  14809. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  14810. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  14811. @ref number_unsigned_t, or @ref number_float_t.
  14812. @return pointer to the internally stored JSON value if the requested
  14813. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  14814. @complexity Constant.
  14815. @liveexample{The example below shows how pointers to internal values of a
  14816. JSON value can be requested. Note that no type conversions are made and a
  14817. `nullptr` is returned if the value and the requested pointer type does not
  14818. match.,get__PointerType}
  14819. @sa @ref get_ptr() for explicit pointer-member access
  14820. @since version 1.0.0
  14821. */
  14822. template<typename PointerType, typename std::enable_if<
  14823. std::is_pointer<PointerType>::value, int>::type = 0>
  14824. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  14825. {
  14826. // delegate the call to get_ptr
  14827. return get_ptr<PointerType>();
  14828. }
  14829. /*!
  14830. @brief get a pointer value (explicit)
  14831. @copydoc get()
  14832. */
  14833. template<typename PointerType, typename std::enable_if<
  14834. std::is_pointer<PointerType>::value, int>::type = 0>
  14835. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  14836. {
  14837. // delegate the call to get_ptr
  14838. return get_ptr<PointerType>();
  14839. }
  14840. /*!
  14841. @brief get a reference value (implicit)
  14842. Implicit reference access to the internally stored JSON value. No copies
  14843. are made.
  14844. @warning Writing data to the referee of the result yields an undefined
  14845. state.
  14846. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  14847. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  14848. @ref number_float_t. Enforced by static assertion.
  14849. @return reference to the internally stored JSON value if the requested
  14850. reference type @a ReferenceType fits to the JSON value; throws
  14851. type_error.303 otherwise
  14852. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  14853. with the stored JSON value; see example below
  14854. @complexity Constant.
  14855. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  14856. @since version 1.1.0
  14857. */
  14858. template<typename ReferenceType, typename std::enable_if<
  14859. std::is_reference<ReferenceType>::value, int>::type = 0>
  14860. ReferenceType get_ref()
  14861. {
  14862. // delegate call to get_ref_impl
  14863. return get_ref_impl<ReferenceType>(*this);
  14864. }
  14865. /*!
  14866. @brief get a reference value (implicit)
  14867. @copydoc get_ref()
  14868. */
  14869. template<typename ReferenceType, typename std::enable_if<
  14870. std::is_reference<ReferenceType>::value and
  14871. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  14872. ReferenceType get_ref() const
  14873. {
  14874. // delegate call to get_ref_impl
  14875. return get_ref_impl<ReferenceType>(*this);
  14876. }
  14877. /*!
  14878. @brief get a value (implicit)
  14879. Implicit type conversion between the JSON value and a compatible value.
  14880. The call is realized by calling @ref get() const.
  14881. @tparam ValueType non-pointer type compatible to the JSON value, for
  14882. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  14883. `std::vector` types for JSON arrays. The character type of @ref string_t
  14884. as well as an initializer list of this type is excluded to avoid
  14885. ambiguities as these types implicitly convert to `std::string`.
  14886. @return copy of the JSON value, converted to type @a ValueType
  14887. @throw type_error.302 in case passed type @a ValueType is incompatible
  14888. to the JSON value type (e.g., the JSON value is of type boolean, but a
  14889. string is requested); see example below
  14890. @complexity Linear in the size of the JSON value.
  14891. @liveexample{The example below shows several conversions from JSON values
  14892. to other types. There a few things to note: (1) Floating-point numbers can
  14893. be converted to integers\, (2) A JSON array can be converted to a standard
  14894. `std::vector<short>`\, (3) A JSON object can be converted to C++
  14895. associative containers such as `std::unordered_map<std::string\,
  14896. json>`.,operator__ValueType}
  14897. @since version 1.0.0
  14898. */
  14899. template < typename ValueType, typename std::enable_if <
  14900. not std::is_pointer<ValueType>::value and
  14901. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  14902. not std::is_same<ValueType, typename string_t::value_type>::value and
  14903. not detail::is_basic_json<ValueType>::value
  14904. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  14905. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  14906. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  14907. and not std::is_same<ValueType, typename std::string_view>::value
  14908. #endif
  14909. #endif
  14910. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  14911. , int >::type = 0 >
  14912. operator ValueType() const
  14913. {
  14914. // delegate the call to get<>() const
  14915. return get<ValueType>();
  14916. }
  14917. /// @}
  14918. ////////////////////
  14919. // element access //
  14920. ////////////////////
  14921. /// @name element access
  14922. /// Access to the JSON value.
  14923. /// @{
  14924. /*!
  14925. @brief access specified array element with bounds checking
  14926. Returns a reference to the element at specified location @a idx, with
  14927. bounds checking.
  14928. @param[in] idx index of the element to access
  14929. @return reference to the element at index @a idx
  14930. @throw type_error.304 if the JSON value is not an array; in this case,
  14931. calling `at` with an index makes no sense. See example below.
  14932. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14933. that is, `idx >= size()`. See example below.
  14934. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14935. changes in the JSON value.
  14936. @complexity Constant.
  14937. @since version 1.0.0
  14938. @liveexample{The example below shows how array elements can be read and
  14939. written using `at()`. It also demonstrates the different exceptions that
  14940. can be thrown.,at__size_type}
  14941. */
  14942. reference at(size_type idx)
  14943. {
  14944. // at only works for arrays
  14945. if (JSON_HEDLEY_LIKELY(is_array()))
  14946. {
  14947. JSON_TRY
  14948. {
  14949. return m_value.array->at(idx);
  14950. }
  14951. JSON_CATCH (std::out_of_range&)
  14952. {
  14953. // create better exception explanation
  14954. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14955. }
  14956. }
  14957. else
  14958. {
  14959. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14960. }
  14961. }
  14962. /*!
  14963. @brief access specified array element with bounds checking
  14964. Returns a const reference to the element at specified location @a idx,
  14965. with bounds checking.
  14966. @param[in] idx index of the element to access
  14967. @return const reference to the element at index @a idx
  14968. @throw type_error.304 if the JSON value is not an array; in this case,
  14969. calling `at` with an index makes no sense. See example below.
  14970. @throw out_of_range.401 if the index @a idx is out of range of the array;
  14971. that is, `idx >= size()`. See example below.
  14972. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14973. changes in the JSON value.
  14974. @complexity Constant.
  14975. @since version 1.0.0
  14976. @liveexample{The example below shows how array elements can be read using
  14977. `at()`. It also demonstrates the different exceptions that can be thrown.,
  14978. at__size_type_const}
  14979. */
  14980. const_reference at(size_type idx) const
  14981. {
  14982. // at only works for arrays
  14983. if (JSON_HEDLEY_LIKELY(is_array()))
  14984. {
  14985. JSON_TRY
  14986. {
  14987. return m_value.array->at(idx);
  14988. }
  14989. JSON_CATCH (std::out_of_range&)
  14990. {
  14991. // create better exception explanation
  14992. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14993. }
  14994. }
  14995. else
  14996. {
  14997. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  14998. }
  14999. }
  15000. /*!
  15001. @brief access specified object element with bounds checking
  15002. Returns a reference to the element at with specified key @a key, with
  15003. bounds checking.
  15004. @param[in] key key of the element to access
  15005. @return reference to the element at key @a key
  15006. @throw type_error.304 if the JSON value is not an object; in this case,
  15007. calling `at` with a key makes no sense. See example below.
  15008. @throw out_of_range.403 if the key @a key is is not stored in the object;
  15009. that is, `find(key) == end()`. See example below.
  15010. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15011. changes in the JSON value.
  15012. @complexity Logarithmic in the size of the container.
  15013. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15014. access by reference
  15015. @sa @ref value() for access by value with a default value
  15016. @since version 1.0.0
  15017. @liveexample{The example below shows how object elements can be read and
  15018. written using `at()`. It also demonstrates the different exceptions that
  15019. can be thrown.,at__object_t_key_type}
  15020. */
  15021. reference at(const typename object_t::key_type& key)
  15022. {
  15023. // at only works for objects
  15024. if (JSON_HEDLEY_LIKELY(is_object()))
  15025. {
  15026. JSON_TRY
  15027. {
  15028. return m_value.object->at(key);
  15029. }
  15030. JSON_CATCH (std::out_of_range&)
  15031. {
  15032. // create better exception explanation
  15033. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  15034. }
  15035. }
  15036. else
  15037. {
  15038. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  15039. }
  15040. }
  15041. /*!
  15042. @brief access specified object element with bounds checking
  15043. Returns a const reference to the element at with specified key @a key,
  15044. with bounds checking.
  15045. @param[in] key key of the element to access
  15046. @return const reference to the element at key @a key
  15047. @throw type_error.304 if the JSON value is not an object; in this case,
  15048. calling `at` with a key makes no sense. See example below.
  15049. @throw out_of_range.403 if the key @a key is is not stored in the object;
  15050. that is, `find(key) == end()`. See example below.
  15051. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15052. changes in the JSON value.
  15053. @complexity Logarithmic in the size of the container.
  15054. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15055. access by reference
  15056. @sa @ref value() for access by value with a default value
  15057. @since version 1.0.0
  15058. @liveexample{The example below shows how object elements can be read using
  15059. `at()`. It also demonstrates the different exceptions that can be thrown.,
  15060. at__object_t_key_type_const}
  15061. */
  15062. const_reference at(const typename object_t::key_type& key) const
  15063. {
  15064. // at only works for objects
  15065. if (JSON_HEDLEY_LIKELY(is_object()))
  15066. {
  15067. JSON_TRY
  15068. {
  15069. return m_value.object->at(key);
  15070. }
  15071. JSON_CATCH (std::out_of_range&)
  15072. {
  15073. // create better exception explanation
  15074. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  15075. }
  15076. }
  15077. else
  15078. {
  15079. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  15080. }
  15081. }
  15082. /*!
  15083. @brief access specified array element
  15084. Returns a reference to the element at specified location @a idx.
  15085. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  15086. then the array is silently filled up with `null` values to make `idx` a
  15087. valid reference to the last stored element.
  15088. @param[in] idx index of the element to access
  15089. @return reference to the element at index @a idx
  15090. @throw type_error.305 if the JSON value is not an array or null; in that
  15091. cases, using the [] operator with an index makes no sense.
  15092. @complexity Constant if @a idx is in the range of the array. Otherwise
  15093. linear in `idx - size()`.
  15094. @liveexample{The example below shows how array elements can be read and
  15095. written using `[]` operator. Note the addition of `null`
  15096. values.,operatorarray__size_type}
  15097. @since version 1.0.0
  15098. */
  15099. reference operator[](size_type idx)
  15100. {
  15101. // implicitly convert null value to an empty array
  15102. if (is_null())
  15103. {
  15104. m_type = value_t::array;
  15105. m_value.array = create<array_t>();
  15106. assert_invariant();
  15107. }
  15108. // operator[] only works for arrays
  15109. if (JSON_HEDLEY_LIKELY(is_array()))
  15110. {
  15111. // fill up array with null values if given idx is outside range
  15112. if (idx >= m_value.array->size())
  15113. {
  15114. m_value.array->insert(m_value.array->end(),
  15115. idx - m_value.array->size() + 1,
  15116. basic_json());
  15117. }
  15118. return m_value.array->operator[](idx);
  15119. }
  15120. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15121. }
  15122. /*!
  15123. @brief access specified array element
  15124. Returns a const reference to the element at specified location @a idx.
  15125. @param[in] idx index of the element to access
  15126. @return const reference to the element at index @a idx
  15127. @throw type_error.305 if the JSON value is not an array; in that case,
  15128. using the [] operator with an index makes no sense.
  15129. @complexity Constant.
  15130. @liveexample{The example below shows how array elements can be read using
  15131. the `[]` operator.,operatorarray__size_type_const}
  15132. @since version 1.0.0
  15133. */
  15134. const_reference operator[](size_type idx) const
  15135. {
  15136. // const operator[] only works for arrays
  15137. if (JSON_HEDLEY_LIKELY(is_array()))
  15138. {
  15139. return m_value.array->operator[](idx);
  15140. }
  15141. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  15142. }
  15143. /*!
  15144. @brief access specified object element
  15145. Returns a reference to the element at with specified key @a key.
  15146. @note If @a key is not found in the object, then it is silently added to
  15147. the object and filled with a `null` value to make `key` a valid reference.
  15148. In case the value was `null` before, it is converted to an object.
  15149. @param[in] key key of the element to access
  15150. @return reference to the element at key @a key
  15151. @throw type_error.305 if the JSON value is not an object or null; in that
  15152. cases, using the [] operator with a key makes no sense.
  15153. @complexity Logarithmic in the size of the container.
  15154. @liveexample{The example below shows how object elements can be read and
  15155. written using the `[]` operator.,operatorarray__key_type}
  15156. @sa @ref at(const typename object_t::key_type&) for access by reference
  15157. with range checking
  15158. @sa @ref value() for access by value with a default value
  15159. @since version 1.0.0
  15160. */
  15161. reference operator[](const typename object_t::key_type& key)
  15162. {
  15163. // implicitly convert null value to an empty object
  15164. if (is_null())
  15165. {
  15166. m_type = value_t::object;
  15167. m_value.object = create<object_t>();
  15168. assert_invariant();
  15169. }
  15170. // operator[] only works for objects
  15171. if (JSON_HEDLEY_LIKELY(is_object()))
  15172. {
  15173. return m_value.object->operator[](key);
  15174. }
  15175. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15176. }
  15177. /*!
  15178. @brief read-only access specified object element
  15179. Returns a const reference to the element at with specified key @a key. No
  15180. bounds checking is performed.
  15181. @warning If the element with key @a key does not exist, the behavior is
  15182. undefined.
  15183. @param[in] key key of the element to access
  15184. @return const reference to the element at key @a key
  15185. @pre The element with key @a key must exist. **This precondition is
  15186. enforced with an assertion.**
  15187. @throw type_error.305 if the JSON value is not an object; in that case,
  15188. using the [] operator with a key makes no sense.
  15189. @complexity Logarithmic in the size of the container.
  15190. @liveexample{The example below shows how object elements can be read using
  15191. the `[]` operator.,operatorarray__key_type_const}
  15192. @sa @ref at(const typename object_t::key_type&) for access by reference
  15193. with range checking
  15194. @sa @ref value() for access by value with a default value
  15195. @since version 1.0.0
  15196. */
  15197. const_reference operator[](const typename object_t::key_type& key) const
  15198. {
  15199. // const operator[] only works for objects
  15200. if (JSON_HEDLEY_LIKELY(is_object()))
  15201. {
  15202. assert(m_value.object->find(key) != m_value.object->end());
  15203. return m_value.object->find(key)->second;
  15204. }
  15205. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15206. }
  15207. /*!
  15208. @brief access specified object element
  15209. Returns a reference to the element at with specified key @a key.
  15210. @note If @a key is not found in the object, then it is silently added to
  15211. the object and filled with a `null` value to make `key` a valid reference.
  15212. In case the value was `null` before, it is converted to an object.
  15213. @param[in] key key of the element to access
  15214. @return reference to the element at key @a key
  15215. @throw type_error.305 if the JSON value is not an object or null; in that
  15216. cases, using the [] operator with a key makes no sense.
  15217. @complexity Logarithmic in the size of the container.
  15218. @liveexample{The example below shows how object elements can be read and
  15219. written using the `[]` operator.,operatorarray__key_type}
  15220. @sa @ref at(const typename object_t::key_type&) for access by reference
  15221. with range checking
  15222. @sa @ref value() for access by value with a default value
  15223. @since version 1.1.0
  15224. */
  15225. template<typename T>
  15226. JSON_HEDLEY_NON_NULL(2)
  15227. reference operator[](T* key)
  15228. {
  15229. // implicitly convert null to object
  15230. if (is_null())
  15231. {
  15232. m_type = value_t::object;
  15233. m_value = value_t::object;
  15234. assert_invariant();
  15235. }
  15236. // at only works for objects
  15237. if (JSON_HEDLEY_LIKELY(is_object()))
  15238. {
  15239. return m_value.object->operator[](key);
  15240. }
  15241. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15242. }
  15243. /*!
  15244. @brief read-only access specified object element
  15245. Returns a const reference to the element at with specified key @a key. No
  15246. bounds checking is performed.
  15247. @warning If the element with key @a key does not exist, the behavior is
  15248. undefined.
  15249. @param[in] key key of the element to access
  15250. @return const reference to the element at key @a key
  15251. @pre The element with key @a key must exist. **This precondition is
  15252. enforced with an assertion.**
  15253. @throw type_error.305 if the JSON value is not an object; in that case,
  15254. using the [] operator with a key makes no sense.
  15255. @complexity Logarithmic in the size of the container.
  15256. @liveexample{The example below shows how object elements can be read using
  15257. the `[]` operator.,operatorarray__key_type_const}
  15258. @sa @ref at(const typename object_t::key_type&) for access by reference
  15259. with range checking
  15260. @sa @ref value() for access by value with a default value
  15261. @since version 1.1.0
  15262. */
  15263. template<typename T>
  15264. JSON_HEDLEY_NON_NULL(2)
  15265. const_reference operator[](T* key) const
  15266. {
  15267. // at only works for objects
  15268. if (JSON_HEDLEY_LIKELY(is_object()))
  15269. {
  15270. assert(m_value.object->find(key) != m_value.object->end());
  15271. return m_value.object->find(key)->second;
  15272. }
  15273. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  15274. }
  15275. /*!
  15276. @brief access specified object element with default value
  15277. Returns either a copy of an object's element at the specified key @a key
  15278. or a given default value if no element with key @a key exists.
  15279. The function is basically equivalent to executing
  15280. @code {.cpp}
  15281. try {
  15282. return at(key);
  15283. } catch(out_of_range) {
  15284. return default_value;
  15285. }
  15286. @endcode
  15287. @note Unlike @ref at(const typename object_t::key_type&), this function
  15288. does not throw if the given key @a key was not found.
  15289. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  15290. function does not implicitly add an element to the position defined by @a
  15291. key. This function is furthermore also applicable to const objects.
  15292. @param[in] key key of the element to access
  15293. @param[in] default_value the value to return if @a key is not found
  15294. @tparam ValueType type compatible to JSON values, for instance `int` for
  15295. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15296. JSON arrays. Note the type of the expected value at @a key and the default
  15297. value @a default_value must be compatible.
  15298. @return copy of the element at key @a key or @a default_value if @a key
  15299. is not found
  15300. @throw type_error.302 if @a default_value does not match the type of the
  15301. value at @a key
  15302. @throw type_error.306 if the JSON value is not an object; in that case,
  15303. using `value()` with a key makes no sense.
  15304. @complexity Logarithmic in the size of the container.
  15305. @liveexample{The example below shows how object elements can be queried
  15306. with a default value.,basic_json__value}
  15307. @sa @ref at(const typename object_t::key_type&) for access by reference
  15308. with range checking
  15309. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  15310. access by reference
  15311. @since version 1.0.0
  15312. */
  15313. template<class ValueType, typename std::enable_if<
  15314. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15315. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  15316. {
  15317. // at only works for objects
  15318. if (JSON_HEDLEY_LIKELY(is_object()))
  15319. {
  15320. // if key is found, return value and given default value otherwise
  15321. const auto it = find(key);
  15322. if (it != end())
  15323. {
  15324. return *it;
  15325. }
  15326. return default_value;
  15327. }
  15328. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15329. }
  15330. /*!
  15331. @brief overload for a default value of type const char*
  15332. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  15333. */
  15334. string_t value(const typename object_t::key_type& key, const char* default_value) const
  15335. {
  15336. return value(key, string_t(default_value));
  15337. }
  15338. /*!
  15339. @brief access specified object element via JSON Pointer with default value
  15340. Returns either a copy of an object's element at the specified key @a key
  15341. or a given default value if no element with key @a key exists.
  15342. The function is basically equivalent to executing
  15343. @code {.cpp}
  15344. try {
  15345. return at(ptr);
  15346. } catch(out_of_range) {
  15347. return default_value;
  15348. }
  15349. @endcode
  15350. @note Unlike @ref at(const json_pointer&), this function does not throw
  15351. if the given key @a key was not found.
  15352. @param[in] ptr a JSON pointer to the element to access
  15353. @param[in] default_value the value to return if @a ptr found no value
  15354. @tparam ValueType type compatible to JSON values, for instance `int` for
  15355. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  15356. JSON arrays. Note the type of the expected value at @a key and the default
  15357. value @a default_value must be compatible.
  15358. @return copy of the element at key @a key or @a default_value if @a key
  15359. is not found
  15360. @throw type_error.302 if @a default_value does not match the type of the
  15361. value at @a ptr
  15362. @throw type_error.306 if the JSON value is not an object; in that case,
  15363. using `value()` with a key makes no sense.
  15364. @complexity Logarithmic in the size of the container.
  15365. @liveexample{The example below shows how object elements can be queried
  15366. with a default value.,basic_json__value_ptr}
  15367. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  15368. @since version 2.0.2
  15369. */
  15370. template<class ValueType, typename std::enable_if<
  15371. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  15372. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  15373. {
  15374. // at only works for objects
  15375. if (JSON_HEDLEY_LIKELY(is_object()))
  15376. {
  15377. // if pointer resolves a value, return it or use default value
  15378. JSON_TRY
  15379. {
  15380. return ptr.get_checked(this);
  15381. }
  15382. JSON_INTERNAL_CATCH (out_of_range&)
  15383. {
  15384. return default_value;
  15385. }
  15386. }
  15387. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  15388. }
  15389. /*!
  15390. @brief overload for a default value of type const char*
  15391. @copydoc basic_json::value(const json_pointer&, ValueType) const
  15392. */
  15393. JSON_HEDLEY_NON_NULL(3)
  15394. string_t value(const json_pointer& ptr, const char* default_value) const
  15395. {
  15396. return value(ptr, string_t(default_value));
  15397. }
  15398. /*!
  15399. @brief access the first element
  15400. Returns a reference to the first element in the container. For a JSON
  15401. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  15402. @return In case of a structured type (array or object), a reference to the
  15403. first element is returned. In case of number, string, or boolean values, a
  15404. reference to the value is returned.
  15405. @complexity Constant.
  15406. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15407. or an empty array or object (undefined behavior, **guarded by
  15408. assertions**).
  15409. @post The JSON value remains unchanged.
  15410. @throw invalid_iterator.214 when called on `null` value
  15411. @liveexample{The following code shows an example for `front()`.,front}
  15412. @sa @ref back() -- access the last element
  15413. @since version 1.0.0
  15414. */
  15415. reference front()
  15416. {
  15417. return *begin();
  15418. }
  15419. /*!
  15420. @copydoc basic_json::front()
  15421. */
  15422. const_reference front() const
  15423. {
  15424. return *cbegin();
  15425. }
  15426. /*!
  15427. @brief access the last element
  15428. Returns a reference to the last element in the container. For a JSON
  15429. container `c`, the expression `c.back()` is equivalent to
  15430. @code {.cpp}
  15431. auto tmp = c.end();
  15432. --tmp;
  15433. return *tmp;
  15434. @endcode
  15435. @return In case of a structured type (array or object), a reference to the
  15436. last element is returned. In case of number, string, or boolean values, a
  15437. reference to the value is returned.
  15438. @complexity Constant.
  15439. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  15440. or an empty array or object (undefined behavior, **guarded by
  15441. assertions**).
  15442. @post The JSON value remains unchanged.
  15443. @throw invalid_iterator.214 when called on a `null` value. See example
  15444. below.
  15445. @liveexample{The following code shows an example for `back()`.,back}
  15446. @sa @ref front() -- access the first element
  15447. @since version 1.0.0
  15448. */
  15449. reference back()
  15450. {
  15451. auto tmp = end();
  15452. --tmp;
  15453. return *tmp;
  15454. }
  15455. /*!
  15456. @copydoc basic_json::back()
  15457. */
  15458. const_reference back() const
  15459. {
  15460. auto tmp = cend();
  15461. --tmp;
  15462. return *tmp;
  15463. }
  15464. /*!
  15465. @brief remove element given an iterator
  15466. Removes the element specified by iterator @a pos. The iterator @a pos must
  15467. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  15468. but is not dereferenceable) cannot be used as a value for @a pos.
  15469. If called on a primitive type other than `null`, the resulting JSON value
  15470. will be `null`.
  15471. @param[in] pos iterator to the element to remove
  15472. @return Iterator following the last removed element. If the iterator @a
  15473. pos refers to the last element, the `end()` iterator is returned.
  15474. @tparam IteratorType an @ref iterator or @ref const_iterator
  15475. @post Invalidates iterators and references at or after the point of the
  15476. erase, including the `end()` iterator.
  15477. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15478. erase() with null"`
  15479. @throw invalid_iterator.202 if called on an iterator which does not belong
  15480. to the current JSON value; example: `"iterator does not fit current
  15481. value"`
  15482. @throw invalid_iterator.205 if called on a primitive type with invalid
  15483. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  15484. out of range"`
  15485. @complexity The complexity depends on the type:
  15486. - objects: amortized constant
  15487. - arrays: linear in distance between @a pos and the end of the container
  15488. - strings: linear in the length of the string
  15489. - other types: constant
  15490. @liveexample{The example shows the result of `erase()` for different JSON
  15491. types.,erase__IteratorType}
  15492. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15493. the given range
  15494. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15495. from an object at the given key
  15496. @sa @ref erase(const size_type) -- removes the element from an array at
  15497. the given index
  15498. @since version 1.0.0
  15499. */
  15500. template<class IteratorType, typename std::enable_if<
  15501. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15502. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15503. = 0>
  15504. IteratorType erase(IteratorType pos)
  15505. {
  15506. // make sure iterator fits the current value
  15507. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  15508. {
  15509. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15510. }
  15511. IteratorType result = end();
  15512. switch (m_type)
  15513. {
  15514. case value_t::boolean:
  15515. case value_t::number_float:
  15516. case value_t::number_integer:
  15517. case value_t::number_unsigned:
  15518. case value_t::string:
  15519. {
  15520. if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  15521. {
  15522. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  15523. }
  15524. if (is_string())
  15525. {
  15526. AllocatorType<string_t> alloc;
  15527. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15528. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15529. m_value.string = nullptr;
  15530. }
  15531. m_type = value_t::null;
  15532. assert_invariant();
  15533. break;
  15534. }
  15535. case value_t::object:
  15536. {
  15537. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  15538. break;
  15539. }
  15540. case value_t::array:
  15541. {
  15542. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  15543. break;
  15544. }
  15545. default:
  15546. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15547. }
  15548. return result;
  15549. }
  15550. /*!
  15551. @brief remove elements given an iterator range
  15552. Removes the element specified by the range `[first; last)`. The iterator
  15553. @a first does not need to be dereferenceable if `first == last`: erasing
  15554. an empty range is a no-op.
  15555. If called on a primitive type other than `null`, the resulting JSON value
  15556. will be `null`.
  15557. @param[in] first iterator to the beginning of the range to remove
  15558. @param[in] last iterator past the end of the range to remove
  15559. @return Iterator following the last removed element. If the iterator @a
  15560. second refers to the last element, the `end()` iterator is returned.
  15561. @tparam IteratorType an @ref iterator or @ref const_iterator
  15562. @post Invalidates iterators and references at or after the point of the
  15563. erase, including the `end()` iterator.
  15564. @throw type_error.307 if called on a `null` value; example: `"cannot use
  15565. erase() with null"`
  15566. @throw invalid_iterator.203 if called on iterators which does not belong
  15567. to the current JSON value; example: `"iterators do not fit current value"`
  15568. @throw invalid_iterator.204 if called on a primitive type with invalid
  15569. iterators (i.e., if `first != begin()` and `last != end()`); example:
  15570. `"iterators out of range"`
  15571. @complexity The complexity depends on the type:
  15572. - objects: `log(size()) + std::distance(first, last)`
  15573. - arrays: linear in the distance between @a first and @a last, plus linear
  15574. in the distance between @a last and end of the container
  15575. - strings: linear in the length of the string
  15576. - other types: constant
  15577. @liveexample{The example shows the result of `erase()` for different JSON
  15578. types.,erase__IteratorType_IteratorType}
  15579. @sa @ref erase(IteratorType) -- removes the element at a given position
  15580. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15581. from an object at the given key
  15582. @sa @ref erase(const size_type) -- removes the element from an array at
  15583. the given index
  15584. @since version 1.0.0
  15585. */
  15586. template<class IteratorType, typename std::enable_if<
  15587. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  15588. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  15589. = 0>
  15590. IteratorType erase(IteratorType first, IteratorType last)
  15591. {
  15592. // make sure iterator fits the current value
  15593. if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
  15594. {
  15595. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  15596. }
  15597. IteratorType result = end();
  15598. switch (m_type)
  15599. {
  15600. case value_t::boolean:
  15601. case value_t::number_float:
  15602. case value_t::number_integer:
  15603. case value_t::number_unsigned:
  15604. case value_t::string:
  15605. {
  15606. if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
  15607. or not last.m_it.primitive_iterator.is_end()))
  15608. {
  15609. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15610. }
  15611. if (is_string())
  15612. {
  15613. AllocatorType<string_t> alloc;
  15614. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  15615. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  15616. m_value.string = nullptr;
  15617. }
  15618. m_type = value_t::null;
  15619. assert_invariant();
  15620. break;
  15621. }
  15622. case value_t::object:
  15623. {
  15624. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  15625. last.m_it.object_iterator);
  15626. break;
  15627. }
  15628. case value_t::array:
  15629. {
  15630. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  15631. last.m_it.array_iterator);
  15632. break;
  15633. }
  15634. default:
  15635. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15636. }
  15637. return result;
  15638. }
  15639. /*!
  15640. @brief remove element from a JSON object given a key
  15641. Removes elements from a JSON object with the key value @a key.
  15642. @param[in] key value of the elements to remove
  15643. @return Number of elements removed. If @a ObjectType is the default
  15644. `std::map` type, the return value will always be `0` (@a key was not
  15645. found) or `1` (@a key was found).
  15646. @post References and iterators to the erased elements are invalidated.
  15647. Other references and iterators are not affected.
  15648. @throw type_error.307 when called on a type other than JSON object;
  15649. example: `"cannot use erase() with null"`
  15650. @complexity `log(size()) + count(key)`
  15651. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  15652. @sa @ref erase(IteratorType) -- removes the element at a given position
  15653. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15654. the given range
  15655. @sa @ref erase(const size_type) -- removes the element from an array at
  15656. the given index
  15657. @since version 1.0.0
  15658. */
  15659. size_type erase(const typename object_t::key_type& key)
  15660. {
  15661. // this erase only works for objects
  15662. if (JSON_HEDLEY_LIKELY(is_object()))
  15663. {
  15664. return m_value.object->erase(key);
  15665. }
  15666. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15667. }
  15668. /*!
  15669. @brief remove element from a JSON array given an index
  15670. Removes element from a JSON array at the index @a idx.
  15671. @param[in] idx index of the element to remove
  15672. @throw type_error.307 when called on a type other than JSON object;
  15673. example: `"cannot use erase() with null"`
  15674. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  15675. is out of range"`
  15676. @complexity Linear in distance between @a idx and the end of the container.
  15677. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  15678. @sa @ref erase(IteratorType) -- removes the element at a given position
  15679. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  15680. the given range
  15681. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  15682. from an object at the given key
  15683. @since version 1.0.0
  15684. */
  15685. void erase(const size_type idx)
  15686. {
  15687. // this erase only works for arrays
  15688. if (JSON_HEDLEY_LIKELY(is_array()))
  15689. {
  15690. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  15691. {
  15692. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  15693. }
  15694. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  15695. }
  15696. else
  15697. {
  15698. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  15699. }
  15700. }
  15701. /// @}
  15702. ////////////
  15703. // lookup //
  15704. ////////////
  15705. /// @name lookup
  15706. /// @{
  15707. /*!
  15708. @brief find an element in a JSON object
  15709. Finds an element in a JSON object with key equivalent to @a key. If the
  15710. element is not found or the JSON value is not an object, end() is
  15711. returned.
  15712. @note This method always returns @ref end() when executed on a JSON type
  15713. that is not an object.
  15714. @param[in] key key value of the element to search for.
  15715. @return Iterator to an element with key equivalent to @a key. If no such
  15716. element is found or the JSON value is not an object, past-the-end (see
  15717. @ref end()) iterator is returned.
  15718. @complexity Logarithmic in the size of the JSON object.
  15719. @liveexample{The example shows how `find()` is used.,find__key_type}
  15720. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  15721. @since version 1.0.0
  15722. */
  15723. template<typename KeyT>
  15724. iterator find(KeyT&& key)
  15725. {
  15726. auto result = end();
  15727. if (is_object())
  15728. {
  15729. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15730. }
  15731. return result;
  15732. }
  15733. /*!
  15734. @brief find an element in a JSON object
  15735. @copydoc find(KeyT&&)
  15736. */
  15737. template<typename KeyT>
  15738. const_iterator find(KeyT&& key) const
  15739. {
  15740. auto result = cend();
  15741. if (is_object())
  15742. {
  15743. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  15744. }
  15745. return result;
  15746. }
  15747. /*!
  15748. @brief returns the number of occurrences of a key in a JSON object
  15749. Returns the number of elements with key @a key. If ObjectType is the
  15750. default `std::map` type, the return value will always be `0` (@a key was
  15751. not found) or `1` (@a key was found).
  15752. @note This method always returns `0` when executed on a JSON type that is
  15753. not an object.
  15754. @param[in] key key value of the element to count
  15755. @return Number of elements with key @a key. If the JSON value is not an
  15756. object, the return value will be `0`.
  15757. @complexity Logarithmic in the size of the JSON object.
  15758. @liveexample{The example shows how `count()` is used.,count}
  15759. @since version 1.0.0
  15760. */
  15761. template<typename KeyT>
  15762. size_type count(KeyT&& key) const
  15763. {
  15764. // return 0 for all nonobject types
  15765. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  15766. }
  15767. /*!
  15768. @brief check the existence of an element in a JSON object
  15769. Check whether an element exists in a JSON object with key equivalent to
  15770. @a key. If the element is not found or the JSON value is not an object,
  15771. false is returned.
  15772. @note This method always returns false when executed on a JSON type
  15773. that is not an object.
  15774. @param[in] key key value to check its existence.
  15775. @return true if an element with specified @a key exists. If no such
  15776. element with such key is found or the JSON value is not an object,
  15777. false is returned.
  15778. @complexity Logarithmic in the size of the JSON object.
  15779. @liveexample{The following code shows an example for `contains()`.,contains}
  15780. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  15781. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  15782. @since version 3.6.0
  15783. */
  15784. template<typename KeyT, typename std::enable_if<
  15785. not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
  15786. bool contains(KeyT && key) const
  15787. {
  15788. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  15789. }
  15790. /*!
  15791. @brief check the existence of an element in a JSON object given a JSON pointer
  15792. Check whether the given JSON pointer @a ptr can be resolved in the current
  15793. JSON value.
  15794. @note This method can be executed on any JSON value type.
  15795. @param[in] ptr JSON pointer to check its existence.
  15796. @return true if the JSON pointer can be resolved to a stored value, false
  15797. otherwise.
  15798. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  15799. @throw parse_error.106 if an array index begins with '0'
  15800. @throw parse_error.109 if an array index was not a number
  15801. @complexity Logarithmic in the size of the JSON object.
  15802. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  15803. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  15804. @since version 3.7.0
  15805. */
  15806. bool contains(const json_pointer& ptr) const
  15807. {
  15808. return ptr.contains(this);
  15809. }
  15810. /// @}
  15811. ///////////////
  15812. // iterators //
  15813. ///////////////
  15814. /// @name iterators
  15815. /// @{
  15816. /*!
  15817. @brief returns an iterator to the first element
  15818. Returns an iterator to the first element.
  15819. @image html range-begin-end.svg "Illustration from cppreference.com"
  15820. @return iterator to the first element
  15821. @complexity Constant.
  15822. @requirement This function helps `basic_json` satisfying the
  15823. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15824. requirements:
  15825. - The complexity is constant.
  15826. @liveexample{The following code shows an example for `begin()`.,begin}
  15827. @sa @ref cbegin() -- returns a const iterator to the beginning
  15828. @sa @ref end() -- returns an iterator to the end
  15829. @sa @ref cend() -- returns a const iterator to the end
  15830. @since version 1.0.0
  15831. */
  15832. iterator begin() noexcept
  15833. {
  15834. iterator result(this);
  15835. result.set_begin();
  15836. return result;
  15837. }
  15838. /*!
  15839. @copydoc basic_json::cbegin()
  15840. */
  15841. const_iterator begin() const noexcept
  15842. {
  15843. return cbegin();
  15844. }
  15845. /*!
  15846. @brief returns a const iterator to the first element
  15847. Returns a const iterator to the first element.
  15848. @image html range-begin-end.svg "Illustration from cppreference.com"
  15849. @return const iterator to the first element
  15850. @complexity Constant.
  15851. @requirement This function helps `basic_json` satisfying the
  15852. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15853. requirements:
  15854. - The complexity is constant.
  15855. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  15856. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  15857. @sa @ref begin() -- returns an iterator to the beginning
  15858. @sa @ref end() -- returns an iterator to the end
  15859. @sa @ref cend() -- returns a const iterator to the end
  15860. @since version 1.0.0
  15861. */
  15862. const_iterator cbegin() const noexcept
  15863. {
  15864. const_iterator result(this);
  15865. result.set_begin();
  15866. return result;
  15867. }
  15868. /*!
  15869. @brief returns an iterator to one past the last element
  15870. Returns an iterator to one past the last element.
  15871. @image html range-begin-end.svg "Illustration from cppreference.com"
  15872. @return iterator one past the last element
  15873. @complexity Constant.
  15874. @requirement This function helps `basic_json` satisfying the
  15875. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15876. requirements:
  15877. - The complexity is constant.
  15878. @liveexample{The following code shows an example for `end()`.,end}
  15879. @sa @ref cend() -- returns a const iterator to the end
  15880. @sa @ref begin() -- returns an iterator to the beginning
  15881. @sa @ref cbegin() -- returns a const iterator to the beginning
  15882. @since version 1.0.0
  15883. */
  15884. iterator end() noexcept
  15885. {
  15886. iterator result(this);
  15887. result.set_end();
  15888. return result;
  15889. }
  15890. /*!
  15891. @copydoc basic_json::cend()
  15892. */
  15893. const_iterator end() const noexcept
  15894. {
  15895. return cend();
  15896. }
  15897. /*!
  15898. @brief returns a const iterator to one past the last element
  15899. Returns a const iterator to one past the last element.
  15900. @image html range-begin-end.svg "Illustration from cppreference.com"
  15901. @return const iterator one past the last element
  15902. @complexity Constant.
  15903. @requirement This function helps `basic_json` satisfying the
  15904. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15905. requirements:
  15906. - The complexity is constant.
  15907. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  15908. @liveexample{The following code shows an example for `cend()`.,cend}
  15909. @sa @ref end() -- returns an iterator to the end
  15910. @sa @ref begin() -- returns an iterator to the beginning
  15911. @sa @ref cbegin() -- returns a const iterator to the beginning
  15912. @since version 1.0.0
  15913. */
  15914. const_iterator cend() const noexcept
  15915. {
  15916. const_iterator result(this);
  15917. result.set_end();
  15918. return result;
  15919. }
  15920. /*!
  15921. @brief returns an iterator to the reverse-beginning
  15922. Returns an iterator to the reverse-beginning; that is, the last element.
  15923. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15924. @complexity Constant.
  15925. @requirement This function helps `basic_json` satisfying the
  15926. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15927. requirements:
  15928. - The complexity is constant.
  15929. - Has the semantics of `reverse_iterator(end())`.
  15930. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  15931. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15932. @sa @ref rend() -- returns a reverse iterator to the end
  15933. @sa @ref crend() -- returns a const reverse iterator to the end
  15934. @since version 1.0.0
  15935. */
  15936. reverse_iterator rbegin() noexcept
  15937. {
  15938. return reverse_iterator(end());
  15939. }
  15940. /*!
  15941. @copydoc basic_json::crbegin()
  15942. */
  15943. const_reverse_iterator rbegin() const noexcept
  15944. {
  15945. return crbegin();
  15946. }
  15947. /*!
  15948. @brief returns an iterator to the reverse-end
  15949. Returns an iterator to the reverse-end; that is, one before the first
  15950. element.
  15951. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15952. @complexity Constant.
  15953. @requirement This function helps `basic_json` satisfying the
  15954. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15955. requirements:
  15956. - The complexity is constant.
  15957. - Has the semantics of `reverse_iterator(begin())`.
  15958. @liveexample{The following code shows an example for `rend()`.,rend}
  15959. @sa @ref crend() -- returns a const reverse iterator to the end
  15960. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15961. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  15962. @since version 1.0.0
  15963. */
  15964. reverse_iterator rend() noexcept
  15965. {
  15966. return reverse_iterator(begin());
  15967. }
  15968. /*!
  15969. @copydoc basic_json::crend()
  15970. */
  15971. const_reverse_iterator rend() const noexcept
  15972. {
  15973. return crend();
  15974. }
  15975. /*!
  15976. @brief returns a const reverse iterator to the last element
  15977. Returns a const iterator to the reverse-beginning; that is, the last
  15978. element.
  15979. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  15980. @complexity Constant.
  15981. @requirement This function helps `basic_json` satisfying the
  15982. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  15983. requirements:
  15984. - The complexity is constant.
  15985. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  15986. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  15987. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  15988. @sa @ref rend() -- returns a reverse iterator to the end
  15989. @sa @ref crend() -- returns a const reverse iterator to the end
  15990. @since version 1.0.0
  15991. */
  15992. const_reverse_iterator crbegin() const noexcept
  15993. {
  15994. return const_reverse_iterator(cend());
  15995. }
  15996. /*!
  15997. @brief returns a const reverse iterator to one before the first
  15998. Returns a const reverse iterator to the reverse-end; that is, one before
  15999. the first element.
  16000. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  16001. @complexity Constant.
  16002. @requirement This function helps `basic_json` satisfying the
  16003. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  16004. requirements:
  16005. - The complexity is constant.
  16006. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  16007. @liveexample{The following code shows an example for `crend()`.,crend}
  16008. @sa @ref rend() -- returns a reverse iterator to the end
  16009. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  16010. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  16011. @since version 1.0.0
  16012. */
  16013. const_reverse_iterator crend() const noexcept
  16014. {
  16015. return const_reverse_iterator(cbegin());
  16016. }
  16017. public:
  16018. /*!
  16019. @brief wrapper to access iterator member functions in range-based for
  16020. This function allows to access @ref iterator::key() and @ref
  16021. iterator::value() during range-based for loops. In these loops, a
  16022. reference to the JSON values is returned, so there is no access to the
  16023. underlying iterator.
  16024. For loop without iterator_wrapper:
  16025. @code{cpp}
  16026. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  16027. {
  16028. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16029. }
  16030. @endcode
  16031. Range-based for loop without iterator proxy:
  16032. @code{cpp}
  16033. for (auto it : j_object)
  16034. {
  16035. // "it" is of type json::reference and has no key() member
  16036. std::cout << "value: " << it << '\n';
  16037. }
  16038. @endcode
  16039. Range-based for loop with iterator proxy:
  16040. @code{cpp}
  16041. for (auto it : json::iterator_wrapper(j_object))
  16042. {
  16043. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16044. }
  16045. @endcode
  16046. @note When iterating over an array, `key()` will return the index of the
  16047. element as string (see example).
  16048. @param[in] ref reference to a JSON value
  16049. @return iteration proxy object wrapping @a ref with an interface to use in
  16050. range-based for loops
  16051. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  16052. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16053. changes in the JSON value.
  16054. @complexity Constant.
  16055. @note The name of this function is not yet final and may change in the
  16056. future.
  16057. @deprecated This stream operator is deprecated and will be removed in
  16058. future 4.0.0 of the library. Please use @ref items() instead;
  16059. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  16060. */
  16061. JSON_HEDLEY_DEPRECATED(3.1.0)
  16062. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  16063. {
  16064. return ref.items();
  16065. }
  16066. /*!
  16067. @copydoc iterator_wrapper(reference)
  16068. */
  16069. JSON_HEDLEY_DEPRECATED(3.1.0)
  16070. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  16071. {
  16072. return ref.items();
  16073. }
  16074. /*!
  16075. @brief helper to access iterator member functions in range-based for
  16076. This function allows to access @ref iterator::key() and @ref
  16077. iterator::value() during range-based for loops. In these loops, a
  16078. reference to the JSON values is returned, so there is no access to the
  16079. underlying iterator.
  16080. For loop without `items()` function:
  16081. @code{cpp}
  16082. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  16083. {
  16084. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  16085. }
  16086. @endcode
  16087. Range-based for loop without `items()` function:
  16088. @code{cpp}
  16089. for (auto it : j_object)
  16090. {
  16091. // "it" is of type json::reference and has no key() member
  16092. std::cout << "value: " << it << '\n';
  16093. }
  16094. @endcode
  16095. Range-based for loop with `items()` function:
  16096. @code{cpp}
  16097. for (auto& el : j_object.items())
  16098. {
  16099. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  16100. }
  16101. @endcode
  16102. The `items()` function also allows to use
  16103. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  16104. (C++17):
  16105. @code{cpp}
  16106. for (auto& [key, val] : j_object.items())
  16107. {
  16108. std::cout << "key: " << key << ", value:" << val << '\n';
  16109. }
  16110. @endcode
  16111. @note When iterating over an array, `key()` will return the index of the
  16112. element as string (see example). For primitive types (e.g., numbers),
  16113. `key()` returns an empty string.
  16114. @return iteration proxy object wrapping @a ref with an interface to use in
  16115. range-based for loops
  16116. @liveexample{The following code shows how the function is used.,items}
  16117. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16118. changes in the JSON value.
  16119. @complexity Constant.
  16120. @since version 3.1.0, structured bindings support since 3.5.0.
  16121. */
  16122. iteration_proxy<iterator> items() noexcept
  16123. {
  16124. return iteration_proxy<iterator>(*this);
  16125. }
  16126. /*!
  16127. @copydoc items()
  16128. */
  16129. iteration_proxy<const_iterator> items() const noexcept
  16130. {
  16131. return iteration_proxy<const_iterator>(*this);
  16132. }
  16133. /// @}
  16134. //////////////
  16135. // capacity //
  16136. //////////////
  16137. /// @name capacity
  16138. /// @{
  16139. /*!
  16140. @brief checks whether the container is empty.
  16141. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  16142. @return The return value depends on the different types and is
  16143. defined as follows:
  16144. Value type | return value
  16145. ----------- | -------------
  16146. null | `true`
  16147. boolean | `false`
  16148. string | `false`
  16149. number | `false`
  16150. object | result of function `object_t::empty()`
  16151. array | result of function `array_t::empty()`
  16152. @liveexample{The following code uses `empty()` to check if a JSON
  16153. object contains any elements.,empty}
  16154. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16155. the Container concept; that is, their `empty()` functions have constant
  16156. complexity.
  16157. @iterators No changes.
  16158. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16159. @note This function does not return whether a string stored as JSON value
  16160. is empty - it returns whether the JSON container itself is empty which is
  16161. false in the case of a string.
  16162. @requirement This function helps `basic_json` satisfying the
  16163. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16164. requirements:
  16165. - The complexity is constant.
  16166. - Has the semantics of `begin() == end()`.
  16167. @sa @ref size() -- returns the number of elements
  16168. @since version 1.0.0
  16169. */
  16170. bool empty() const noexcept
  16171. {
  16172. switch (m_type)
  16173. {
  16174. case value_t::null:
  16175. {
  16176. // null values are empty
  16177. return true;
  16178. }
  16179. case value_t::array:
  16180. {
  16181. // delegate call to array_t::empty()
  16182. return m_value.array->empty();
  16183. }
  16184. case value_t::object:
  16185. {
  16186. // delegate call to object_t::empty()
  16187. return m_value.object->empty();
  16188. }
  16189. default:
  16190. {
  16191. // all other types are nonempty
  16192. return false;
  16193. }
  16194. }
  16195. }
  16196. /*!
  16197. @brief returns the number of elements
  16198. Returns the number of elements in a JSON value.
  16199. @return The return value depends on the different types and is
  16200. defined as follows:
  16201. Value type | return value
  16202. ----------- | -------------
  16203. null | `0`
  16204. boolean | `1`
  16205. string | `1`
  16206. number | `1`
  16207. object | result of function object_t::size()
  16208. array | result of function array_t::size()
  16209. @liveexample{The following code calls `size()` on the different value
  16210. types.,size}
  16211. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16212. the Container concept; that is, their size() functions have constant
  16213. complexity.
  16214. @iterators No changes.
  16215. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16216. @note This function does not return the length of a string stored as JSON
  16217. value - it returns the number of elements in the JSON value which is 1 in
  16218. the case of a string.
  16219. @requirement This function helps `basic_json` satisfying the
  16220. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16221. requirements:
  16222. - The complexity is constant.
  16223. - Has the semantics of `std::distance(begin(), end())`.
  16224. @sa @ref empty() -- checks whether the container is empty
  16225. @sa @ref max_size() -- returns the maximal number of elements
  16226. @since version 1.0.0
  16227. */
  16228. size_type size() const noexcept
  16229. {
  16230. switch (m_type)
  16231. {
  16232. case value_t::null:
  16233. {
  16234. // null values are empty
  16235. return 0;
  16236. }
  16237. case value_t::array:
  16238. {
  16239. // delegate call to array_t::size()
  16240. return m_value.array->size();
  16241. }
  16242. case value_t::object:
  16243. {
  16244. // delegate call to object_t::size()
  16245. return m_value.object->size();
  16246. }
  16247. default:
  16248. {
  16249. // all other types have size 1
  16250. return 1;
  16251. }
  16252. }
  16253. }
  16254. /*!
  16255. @brief returns the maximum possible number of elements
  16256. Returns the maximum number of elements a JSON value is able to hold due to
  16257. system or library implementation limitations, i.e. `std::distance(begin(),
  16258. end())` for the JSON value.
  16259. @return The return value depends on the different types and is
  16260. defined as follows:
  16261. Value type | return value
  16262. ----------- | -------------
  16263. null | `0` (same as `size()`)
  16264. boolean | `1` (same as `size()`)
  16265. string | `1` (same as `size()`)
  16266. number | `1` (same as `size()`)
  16267. object | result of function `object_t::max_size()`
  16268. array | result of function `array_t::max_size()`
  16269. @liveexample{The following code calls `max_size()` on the different value
  16270. types. Note the output is implementation specific.,max_size}
  16271. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  16272. the Container concept; that is, their `max_size()` functions have constant
  16273. complexity.
  16274. @iterators No changes.
  16275. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16276. @requirement This function helps `basic_json` satisfying the
  16277. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  16278. requirements:
  16279. - The complexity is constant.
  16280. - Has the semantics of returning `b.size()` where `b` is the largest
  16281. possible JSON value.
  16282. @sa @ref size() -- returns the number of elements
  16283. @since version 1.0.0
  16284. */
  16285. size_type max_size() const noexcept
  16286. {
  16287. switch (m_type)
  16288. {
  16289. case value_t::array:
  16290. {
  16291. // delegate call to array_t::max_size()
  16292. return m_value.array->max_size();
  16293. }
  16294. case value_t::object:
  16295. {
  16296. // delegate call to object_t::max_size()
  16297. return m_value.object->max_size();
  16298. }
  16299. default:
  16300. {
  16301. // all other types have max_size() == size()
  16302. return size();
  16303. }
  16304. }
  16305. }
  16306. /// @}
  16307. ///////////////
  16308. // modifiers //
  16309. ///////////////
  16310. /// @name modifiers
  16311. /// @{
  16312. /*!
  16313. @brief clears the contents
  16314. Clears the content of a JSON value and resets it to the default value as
  16315. if @ref basic_json(value_t) would have been called with the current value
  16316. type from @ref type():
  16317. Value type | initial value
  16318. ----------- | -------------
  16319. null | `null`
  16320. boolean | `false`
  16321. string | `""`
  16322. number | `0`
  16323. object | `{}`
  16324. array | `[]`
  16325. @post Has the same effect as calling
  16326. @code {.cpp}
  16327. *this = basic_json(type());
  16328. @endcode
  16329. @liveexample{The example below shows the effect of `clear()` to different
  16330. JSON types.,clear}
  16331. @complexity Linear in the size of the JSON value.
  16332. @iterators All iterators, pointers and references related to this container
  16333. are invalidated.
  16334. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  16335. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  16336. same value than calling `clear()`
  16337. @since version 1.0.0
  16338. */
  16339. void clear() noexcept
  16340. {
  16341. switch (m_type)
  16342. {
  16343. case value_t::number_integer:
  16344. {
  16345. m_value.number_integer = 0;
  16346. break;
  16347. }
  16348. case value_t::number_unsigned:
  16349. {
  16350. m_value.number_unsigned = 0;
  16351. break;
  16352. }
  16353. case value_t::number_float:
  16354. {
  16355. m_value.number_float = 0.0;
  16356. break;
  16357. }
  16358. case value_t::boolean:
  16359. {
  16360. m_value.boolean = false;
  16361. break;
  16362. }
  16363. case value_t::string:
  16364. {
  16365. m_value.string->clear();
  16366. break;
  16367. }
  16368. case value_t::array:
  16369. {
  16370. m_value.array->clear();
  16371. break;
  16372. }
  16373. case value_t::object:
  16374. {
  16375. m_value.object->clear();
  16376. break;
  16377. }
  16378. default:
  16379. break;
  16380. }
  16381. }
  16382. /*!
  16383. @brief add an object to an array
  16384. Appends the given element @a val to the end of the JSON value. If the
  16385. function is called on a JSON null value, an empty array is created before
  16386. appending @a val.
  16387. @param[in] val the value to add to the JSON array
  16388. @throw type_error.308 when called on a type other than JSON array or
  16389. null; example: `"cannot use push_back() with number"`
  16390. @complexity Amortized constant.
  16391. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16392. add elements to a JSON array. Note how the `null` value was silently
  16393. converted to a JSON array.,push_back}
  16394. @since version 1.0.0
  16395. */
  16396. void push_back(basic_json&& val)
  16397. {
  16398. // push_back only works for null objects or arrays
  16399. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16400. {
  16401. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16402. }
  16403. // transform null object into an array
  16404. if (is_null())
  16405. {
  16406. m_type = value_t::array;
  16407. m_value = value_t::array;
  16408. assert_invariant();
  16409. }
  16410. // add element to array (move semantics)
  16411. m_value.array->push_back(std::move(val));
  16412. // invalidate object: mark it null so we do not call the destructor
  16413. // cppcheck-suppress accessMoved
  16414. val.m_type = value_t::null;
  16415. }
  16416. /*!
  16417. @brief add an object to an array
  16418. @copydoc push_back(basic_json&&)
  16419. */
  16420. reference operator+=(basic_json&& val)
  16421. {
  16422. push_back(std::move(val));
  16423. return *this;
  16424. }
  16425. /*!
  16426. @brief add an object to an array
  16427. @copydoc push_back(basic_json&&)
  16428. */
  16429. void push_back(const basic_json& val)
  16430. {
  16431. // push_back only works for null objects or arrays
  16432. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16433. {
  16434. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16435. }
  16436. // transform null object into an array
  16437. if (is_null())
  16438. {
  16439. m_type = value_t::array;
  16440. m_value = value_t::array;
  16441. assert_invariant();
  16442. }
  16443. // add element to array
  16444. m_value.array->push_back(val);
  16445. }
  16446. /*!
  16447. @brief add an object to an array
  16448. @copydoc push_back(basic_json&&)
  16449. */
  16450. reference operator+=(const basic_json& val)
  16451. {
  16452. push_back(val);
  16453. return *this;
  16454. }
  16455. /*!
  16456. @brief add an object to an object
  16457. Inserts the given element @a val to the JSON object. If the function is
  16458. called on a JSON null value, an empty object is created before inserting
  16459. @a val.
  16460. @param[in] val the value to add to the JSON object
  16461. @throw type_error.308 when called on a type other than JSON object or
  16462. null; example: `"cannot use push_back() with number"`
  16463. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16464. @liveexample{The example shows how `push_back()` and `+=` can be used to
  16465. add elements to a JSON object. Note how the `null` value was silently
  16466. converted to a JSON object.,push_back__object_t__value}
  16467. @since version 1.0.0
  16468. */
  16469. void push_back(const typename object_t::value_type& val)
  16470. {
  16471. // push_back only works for null objects or objects
  16472. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16473. {
  16474. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  16475. }
  16476. // transform null object into an object
  16477. if (is_null())
  16478. {
  16479. m_type = value_t::object;
  16480. m_value = value_t::object;
  16481. assert_invariant();
  16482. }
  16483. // add element to array
  16484. m_value.object->insert(val);
  16485. }
  16486. /*!
  16487. @brief add an object to an object
  16488. @copydoc push_back(const typename object_t::value_type&)
  16489. */
  16490. reference operator+=(const typename object_t::value_type& val)
  16491. {
  16492. push_back(val);
  16493. return *this;
  16494. }
  16495. /*!
  16496. @brief add an object to an object
  16497. This function allows to use `push_back` with an initializer list. In case
  16498. 1. the current value is an object,
  16499. 2. the initializer list @a init contains only two elements, and
  16500. 3. the first element of @a init is a string,
  16501. @a init is converted into an object element and added using
  16502. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  16503. is converted to a JSON value and added using @ref push_back(basic_json&&).
  16504. @param[in] init an initializer list
  16505. @complexity Linear in the size of the initializer list @a init.
  16506. @note This function is required to resolve an ambiguous overload error,
  16507. because pairs like `{"key", "value"}` can be both interpreted as
  16508. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  16509. https://github.com/nlohmann/json/issues/235 for more information.
  16510. @liveexample{The example shows how initializer lists are treated as
  16511. objects when possible.,push_back__initializer_list}
  16512. */
  16513. void push_back(initializer_list_t init)
  16514. {
  16515. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  16516. {
  16517. basic_json&& key = init.begin()->moved_or_copied();
  16518. push_back(typename object_t::value_type(
  16519. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  16520. }
  16521. else
  16522. {
  16523. push_back(basic_json(init));
  16524. }
  16525. }
  16526. /*!
  16527. @brief add an object to an object
  16528. @copydoc push_back(initializer_list_t)
  16529. */
  16530. reference operator+=(initializer_list_t init)
  16531. {
  16532. push_back(init);
  16533. return *this;
  16534. }
  16535. /*!
  16536. @brief add an object to an array
  16537. Creates a JSON value from the passed parameters @a args to the end of the
  16538. JSON value. If the function is called on a JSON null value, an empty array
  16539. is created before appending the value created from @a args.
  16540. @param[in] args arguments to forward to a constructor of @ref basic_json
  16541. @tparam Args compatible types to create a @ref basic_json object
  16542. @return reference to the inserted element
  16543. @throw type_error.311 when called on a type other than JSON array or
  16544. null; example: `"cannot use emplace_back() with number"`
  16545. @complexity Amortized constant.
  16546. @liveexample{The example shows how `push_back()` can be used to add
  16547. elements to a JSON array. Note how the `null` value was silently converted
  16548. to a JSON array.,emplace_back}
  16549. @since version 2.0.8, returns reference since 3.7.0
  16550. */
  16551. template<class... Args>
  16552. reference emplace_back(Args&& ... args)
  16553. {
  16554. // emplace_back only works for null objects or arrays
  16555. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
  16556. {
  16557. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  16558. }
  16559. // transform null object into an array
  16560. if (is_null())
  16561. {
  16562. m_type = value_t::array;
  16563. m_value = value_t::array;
  16564. assert_invariant();
  16565. }
  16566. // add element to array (perfect forwarding)
  16567. #ifdef JSON_HAS_CPP_17
  16568. return m_value.array->emplace_back(std::forward<Args>(args)...);
  16569. #else
  16570. m_value.array->emplace_back(std::forward<Args>(args)...);
  16571. return m_value.array->back();
  16572. #endif
  16573. }
  16574. /*!
  16575. @brief add an object to an object if key does not exist
  16576. Inserts a new element into a JSON object constructed in-place with the
  16577. given @a args if there is no element with the key in the container. If the
  16578. function is called on a JSON null value, an empty object is created before
  16579. appending the value created from @a args.
  16580. @param[in] args arguments to forward to a constructor of @ref basic_json
  16581. @tparam Args compatible types to create a @ref basic_json object
  16582. @return a pair consisting of an iterator to the inserted element, or the
  16583. already-existing element if no insertion happened, and a bool
  16584. denoting whether the insertion took place.
  16585. @throw type_error.311 when called on a type other than JSON object or
  16586. null; example: `"cannot use emplace() with number"`
  16587. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  16588. @liveexample{The example shows how `emplace()` can be used to add elements
  16589. to a JSON object. Note how the `null` value was silently converted to a
  16590. JSON object. Further note how no value is added if there was already one
  16591. value stored with the same key.,emplace}
  16592. @since version 2.0.8
  16593. */
  16594. template<class... Args>
  16595. std::pair<iterator, bool> emplace(Args&& ... args)
  16596. {
  16597. // emplace only works for null objects or arrays
  16598. if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
  16599. {
  16600. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  16601. }
  16602. // transform null object into an object
  16603. if (is_null())
  16604. {
  16605. m_type = value_t::object;
  16606. m_value = value_t::object;
  16607. assert_invariant();
  16608. }
  16609. // add element to array (perfect forwarding)
  16610. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  16611. // create result iterator and set iterator to the result of emplace
  16612. auto it = begin();
  16613. it.m_it.object_iterator = res.first;
  16614. // return pair of iterator and boolean
  16615. return {it, res.second};
  16616. }
  16617. /// Helper for insertion of an iterator
  16618. /// @note: This uses std::distance to support GCC 4.8,
  16619. /// see https://github.com/nlohmann/json/pull/1257
  16620. template<typename... Args>
  16621. iterator insert_iterator(const_iterator pos, Args&& ... args)
  16622. {
  16623. iterator result(this);
  16624. assert(m_value.array != nullptr);
  16625. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  16626. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  16627. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  16628. // This could have been written as:
  16629. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  16630. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  16631. return result;
  16632. }
  16633. /*!
  16634. @brief inserts element
  16635. Inserts element @a val before iterator @a pos.
  16636. @param[in] pos iterator before which the content will be inserted; may be
  16637. the end() iterator
  16638. @param[in] val element to insert
  16639. @return iterator pointing to the inserted @a val.
  16640. @throw type_error.309 if called on JSON values other than arrays;
  16641. example: `"cannot use insert() with string"`
  16642. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16643. example: `"iterator does not fit current value"`
  16644. @complexity Constant plus linear in the distance between @a pos and end of
  16645. the container.
  16646. @liveexample{The example shows how `insert()` is used.,insert}
  16647. @since version 1.0.0
  16648. */
  16649. iterator insert(const_iterator pos, const basic_json& val)
  16650. {
  16651. // insert only works for arrays
  16652. if (JSON_HEDLEY_LIKELY(is_array()))
  16653. {
  16654. // check if iterator pos fits to this JSON value
  16655. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16656. {
  16657. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16658. }
  16659. // insert to array and return iterator
  16660. return insert_iterator(pos, val);
  16661. }
  16662. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16663. }
  16664. /*!
  16665. @brief inserts element
  16666. @copydoc insert(const_iterator, const basic_json&)
  16667. */
  16668. iterator insert(const_iterator pos, basic_json&& val)
  16669. {
  16670. return insert(pos, val);
  16671. }
  16672. /*!
  16673. @brief inserts elements
  16674. Inserts @a cnt copies of @a val before iterator @a pos.
  16675. @param[in] pos iterator before which the content will be inserted; may be
  16676. the end() iterator
  16677. @param[in] cnt number of copies of @a val to insert
  16678. @param[in] val element to insert
  16679. @return iterator pointing to the first element inserted, or @a pos if
  16680. `cnt==0`
  16681. @throw type_error.309 if called on JSON values other than arrays; example:
  16682. `"cannot use insert() with string"`
  16683. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16684. example: `"iterator does not fit current value"`
  16685. @complexity Linear in @a cnt plus linear in the distance between @a pos
  16686. and end of the container.
  16687. @liveexample{The example shows how `insert()` is used.,insert__count}
  16688. @since version 1.0.0
  16689. */
  16690. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  16691. {
  16692. // insert only works for arrays
  16693. if (JSON_HEDLEY_LIKELY(is_array()))
  16694. {
  16695. // check if iterator pos fits to this JSON value
  16696. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16697. {
  16698. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16699. }
  16700. // insert to array and return iterator
  16701. return insert_iterator(pos, cnt, val);
  16702. }
  16703. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16704. }
  16705. /*!
  16706. @brief inserts elements
  16707. Inserts elements from range `[first, last)` before iterator @a pos.
  16708. @param[in] pos iterator before which the content will be inserted; may be
  16709. the end() iterator
  16710. @param[in] first begin of the range of elements to insert
  16711. @param[in] last end of the range of elements to insert
  16712. @throw type_error.309 if called on JSON values other than arrays; example:
  16713. `"cannot use insert() with string"`
  16714. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16715. example: `"iterator does not fit current value"`
  16716. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16717. same JSON value; example: `"iterators do not fit"`
  16718. @throw invalid_iterator.211 if @a first or @a last are iterators into
  16719. container for which insert is called; example: `"passed iterators may not
  16720. belong to container"`
  16721. @return iterator pointing to the first element inserted, or @a pos if
  16722. `first==last`
  16723. @complexity Linear in `std::distance(first, last)` plus linear in the
  16724. distance between @a pos and end of the container.
  16725. @liveexample{The example shows how `insert()` is used.,insert__range}
  16726. @since version 1.0.0
  16727. */
  16728. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  16729. {
  16730. // insert only works for arrays
  16731. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16732. {
  16733. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16734. }
  16735. // check if iterator pos fits to this JSON value
  16736. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16737. {
  16738. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16739. }
  16740. // check if range iterators belong to the same JSON object
  16741. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16742. {
  16743. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16744. }
  16745. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  16746. {
  16747. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  16748. }
  16749. // insert to array and return iterator
  16750. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  16751. }
  16752. /*!
  16753. @brief inserts elements
  16754. Inserts elements from initializer list @a ilist before iterator @a pos.
  16755. @param[in] pos iterator before which the content will be inserted; may be
  16756. the end() iterator
  16757. @param[in] ilist initializer list to insert the values from
  16758. @throw type_error.309 if called on JSON values other than arrays; example:
  16759. `"cannot use insert() with string"`
  16760. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  16761. example: `"iterator does not fit current value"`
  16762. @return iterator pointing to the first element inserted, or @a pos if
  16763. `ilist` is empty
  16764. @complexity Linear in `ilist.size()` plus linear in the distance between
  16765. @a pos and end of the container.
  16766. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  16767. @since version 1.0.0
  16768. */
  16769. iterator insert(const_iterator pos, initializer_list_t ilist)
  16770. {
  16771. // insert only works for arrays
  16772. if (JSON_HEDLEY_UNLIKELY(not is_array()))
  16773. {
  16774. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16775. }
  16776. // check if iterator pos fits to this JSON value
  16777. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  16778. {
  16779. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  16780. }
  16781. // insert to array and return iterator
  16782. return insert_iterator(pos, ilist.begin(), ilist.end());
  16783. }
  16784. /*!
  16785. @brief inserts elements
  16786. Inserts elements from range `[first, last)`.
  16787. @param[in] first begin of the range of elements to insert
  16788. @param[in] last end of the range of elements to insert
  16789. @throw type_error.309 if called on JSON values other than objects; example:
  16790. `"cannot use insert() with string"`
  16791. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16792. point to an object; example: `"iterators first and last must point to
  16793. objects"`
  16794. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16795. same JSON value; example: `"iterators do not fit"`
  16796. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  16797. of elements to insert.
  16798. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  16799. @since version 3.0.0
  16800. */
  16801. void insert(const_iterator first, const_iterator last)
  16802. {
  16803. // insert only works for objects
  16804. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16805. {
  16806. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  16807. }
  16808. // check if range iterators belong to the same JSON object
  16809. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16810. {
  16811. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16812. }
  16813. // passed iterators must belong to objects
  16814. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
  16815. {
  16816. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16817. }
  16818. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  16819. }
  16820. /*!
  16821. @brief updates a JSON object from another object, overwriting existing keys
  16822. Inserts all values from JSON object @a j and overwrites existing keys.
  16823. @param[in] j JSON object to read values from
  16824. @throw type_error.312 if called on JSON values other than objects; example:
  16825. `"cannot use update() with string"`
  16826. @complexity O(N*log(size() + N)), where N is the number of elements to
  16827. insert.
  16828. @liveexample{The example shows how `update()` is used.,update}
  16829. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16830. @since version 3.0.0
  16831. */
  16832. void update(const_reference j)
  16833. {
  16834. // implicitly convert null value to an empty object
  16835. if (is_null())
  16836. {
  16837. m_type = value_t::object;
  16838. m_value.object = create<object_t>();
  16839. assert_invariant();
  16840. }
  16841. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16842. {
  16843. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16844. }
  16845. if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
  16846. {
  16847. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  16848. }
  16849. for (auto it = j.cbegin(); it != j.cend(); ++it)
  16850. {
  16851. m_value.object->operator[](it.key()) = it.value();
  16852. }
  16853. }
  16854. /*!
  16855. @brief updates a JSON object from another object, overwriting existing keys
  16856. Inserts all values from from range `[first, last)` and overwrites existing
  16857. keys.
  16858. @param[in] first begin of the range of elements to insert
  16859. @param[in] last end of the range of elements to insert
  16860. @throw type_error.312 if called on JSON values other than objects; example:
  16861. `"cannot use update() with string"`
  16862. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  16863. point to an object; example: `"iterators first and last must point to
  16864. objects"`
  16865. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  16866. same JSON value; example: `"iterators do not fit"`
  16867. @complexity O(N*log(size() + N)), where N is the number of elements to
  16868. insert.
  16869. @liveexample{The example shows how `update()` is used__range.,update}
  16870. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  16871. @since version 3.0.0
  16872. */
  16873. void update(const_iterator first, const_iterator last)
  16874. {
  16875. // implicitly convert null value to an empty object
  16876. if (is_null())
  16877. {
  16878. m_type = value_t::object;
  16879. m_value.object = create<object_t>();
  16880. assert_invariant();
  16881. }
  16882. if (JSON_HEDLEY_UNLIKELY(not is_object()))
  16883. {
  16884. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  16885. }
  16886. // check if range iterators belong to the same JSON object
  16887. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  16888. {
  16889. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  16890. }
  16891. // passed iterators must belong to objects
  16892. if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
  16893. or not last.m_object->is_object()))
  16894. {
  16895. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  16896. }
  16897. for (auto it = first; it != last; ++it)
  16898. {
  16899. m_value.object->operator[](it.key()) = it.value();
  16900. }
  16901. }
  16902. /*!
  16903. @brief exchanges the values
  16904. Exchanges the contents of the JSON value with those of @a other. Does not
  16905. invoke any move, copy, or swap operations on individual elements. All
  16906. iterators and references remain valid. The past-the-end iterator is
  16907. invalidated.
  16908. @param[in,out] other JSON value to exchange the contents with
  16909. @complexity Constant.
  16910. @liveexample{The example below shows how JSON values can be swapped with
  16911. `swap()`.,swap__reference}
  16912. @since version 1.0.0
  16913. */
  16914. void swap(reference other) noexcept (
  16915. std::is_nothrow_move_constructible<value_t>::value and
  16916. std::is_nothrow_move_assignable<value_t>::value and
  16917. std::is_nothrow_move_constructible<json_value>::value and
  16918. std::is_nothrow_move_assignable<json_value>::value
  16919. )
  16920. {
  16921. std::swap(m_type, other.m_type);
  16922. std::swap(m_value, other.m_value);
  16923. assert_invariant();
  16924. }
  16925. /*!
  16926. @brief exchanges the values
  16927. Exchanges the contents of a JSON array with those of @a other. Does not
  16928. invoke any move, copy, or swap operations on individual elements. All
  16929. iterators and references remain valid. The past-the-end iterator is
  16930. invalidated.
  16931. @param[in,out] other array to exchange the contents with
  16932. @throw type_error.310 when JSON value is not an array; example: `"cannot
  16933. use swap() with string"`
  16934. @complexity Constant.
  16935. @liveexample{The example below shows how arrays can be swapped with
  16936. `swap()`.,swap__array_t}
  16937. @since version 1.0.0
  16938. */
  16939. void swap(array_t& other)
  16940. {
  16941. // swap only works for arrays
  16942. if (JSON_HEDLEY_LIKELY(is_array()))
  16943. {
  16944. std::swap(*(m_value.array), other);
  16945. }
  16946. else
  16947. {
  16948. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16949. }
  16950. }
  16951. /*!
  16952. @brief exchanges the values
  16953. Exchanges the contents of a JSON object with those of @a other. Does not
  16954. invoke any move, copy, or swap operations on individual elements. All
  16955. iterators and references remain valid. The past-the-end iterator is
  16956. invalidated.
  16957. @param[in,out] other object to exchange the contents with
  16958. @throw type_error.310 when JSON value is not an object; example:
  16959. `"cannot use swap() with string"`
  16960. @complexity Constant.
  16961. @liveexample{The example below shows how objects can be swapped with
  16962. `swap()`.,swap__object_t}
  16963. @since version 1.0.0
  16964. */
  16965. void swap(object_t& other)
  16966. {
  16967. // swap only works for objects
  16968. if (JSON_HEDLEY_LIKELY(is_object()))
  16969. {
  16970. std::swap(*(m_value.object), other);
  16971. }
  16972. else
  16973. {
  16974. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  16975. }
  16976. }
  16977. /*!
  16978. @brief exchanges the values
  16979. Exchanges the contents of a JSON string with those of @a other. Does not
  16980. invoke any move, copy, or swap operations on individual elements. All
  16981. iterators and references remain valid. The past-the-end iterator is
  16982. invalidated.
  16983. @param[in,out] other string to exchange the contents with
  16984. @throw type_error.310 when JSON value is not a string; example: `"cannot
  16985. use swap() with boolean"`
  16986. @complexity Constant.
  16987. @liveexample{The example below shows how strings can be swapped with
  16988. `swap()`.,swap__string_t}
  16989. @since version 1.0.0
  16990. */
  16991. void swap(string_t& other)
  16992. {
  16993. // swap only works for strings
  16994. if (JSON_HEDLEY_LIKELY(is_string()))
  16995. {
  16996. std::swap(*(m_value.string), other);
  16997. }
  16998. else
  16999. {
  17000. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  17001. }
  17002. }
  17003. /// @}
  17004. public:
  17005. //////////////////////////////////////////
  17006. // lexicographical comparison operators //
  17007. //////////////////////////////////////////
  17008. /// @name lexicographical comparison operators
  17009. /// @{
  17010. /*!
  17011. @brief comparison: equal
  17012. Compares two JSON values for equality according to the following rules:
  17013. - Two JSON values are equal if (1) they are from the same type and (2)
  17014. their stored values are the same according to their respective
  17015. `operator==`.
  17016. - Integer and floating-point numbers are automatically converted before
  17017. comparison. Note than two NaN values are always treated as unequal.
  17018. - Two JSON null values are equal.
  17019. @note Floating-point inside JSON values numbers are compared with
  17020. `json::number_float_t::operator==` which is `double::operator==` by
  17021. default. To compare floating-point while respecting an epsilon, an alternative
  17022. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  17023. could be used, for instance
  17024. @code {.cpp}
  17025. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  17026. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  17027. {
  17028. return std::abs(a - b) <= epsilon;
  17029. }
  17030. @endcode
  17031. @note NaN values never compare equal to themselves or to other NaN values.
  17032. @param[in] lhs first JSON value to consider
  17033. @param[in] rhs second JSON value to consider
  17034. @return whether the values @a lhs and @a rhs are equal
  17035. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17036. @complexity Linear.
  17037. @liveexample{The example demonstrates comparing several JSON
  17038. types.,operator__equal}
  17039. @since version 1.0.0
  17040. */
  17041. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  17042. {
  17043. const auto lhs_type = lhs.type();
  17044. const auto rhs_type = rhs.type();
  17045. if (lhs_type == rhs_type)
  17046. {
  17047. switch (lhs_type)
  17048. {
  17049. case value_t::array:
  17050. return *lhs.m_value.array == *rhs.m_value.array;
  17051. case value_t::object:
  17052. return *lhs.m_value.object == *rhs.m_value.object;
  17053. case value_t::null:
  17054. return true;
  17055. case value_t::string:
  17056. return *lhs.m_value.string == *rhs.m_value.string;
  17057. case value_t::boolean:
  17058. return lhs.m_value.boolean == rhs.m_value.boolean;
  17059. case value_t::number_integer:
  17060. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  17061. case value_t::number_unsigned:
  17062. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  17063. case value_t::number_float:
  17064. return lhs.m_value.number_float == rhs.m_value.number_float;
  17065. default:
  17066. return false;
  17067. }
  17068. }
  17069. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17070. {
  17071. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  17072. }
  17073. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17074. {
  17075. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  17076. }
  17077. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17078. {
  17079. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  17080. }
  17081. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17082. {
  17083. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17084. }
  17085. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17086. {
  17087. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  17088. }
  17089. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17090. {
  17091. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17092. }
  17093. return false;
  17094. }
  17095. /*!
  17096. @brief comparison: equal
  17097. @copydoc operator==(const_reference, const_reference)
  17098. */
  17099. template<typename ScalarType, typename std::enable_if<
  17100. std::is_scalar<ScalarType>::value, int>::type = 0>
  17101. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  17102. {
  17103. return lhs == basic_json(rhs);
  17104. }
  17105. /*!
  17106. @brief comparison: equal
  17107. @copydoc operator==(const_reference, const_reference)
  17108. */
  17109. template<typename ScalarType, typename std::enable_if<
  17110. std::is_scalar<ScalarType>::value, int>::type = 0>
  17111. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  17112. {
  17113. return basic_json(lhs) == rhs;
  17114. }
  17115. /*!
  17116. @brief comparison: not equal
  17117. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  17118. @param[in] lhs first JSON value to consider
  17119. @param[in] rhs second JSON value to consider
  17120. @return whether the values @a lhs and @a rhs are not equal
  17121. @complexity Linear.
  17122. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17123. @liveexample{The example demonstrates comparing several JSON
  17124. types.,operator__notequal}
  17125. @since version 1.0.0
  17126. */
  17127. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  17128. {
  17129. return not (lhs == rhs);
  17130. }
  17131. /*!
  17132. @brief comparison: not equal
  17133. @copydoc operator!=(const_reference, const_reference)
  17134. */
  17135. template<typename ScalarType, typename std::enable_if<
  17136. std::is_scalar<ScalarType>::value, int>::type = 0>
  17137. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  17138. {
  17139. return lhs != basic_json(rhs);
  17140. }
  17141. /*!
  17142. @brief comparison: not equal
  17143. @copydoc operator!=(const_reference, const_reference)
  17144. */
  17145. template<typename ScalarType, typename std::enable_if<
  17146. std::is_scalar<ScalarType>::value, int>::type = 0>
  17147. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  17148. {
  17149. return basic_json(lhs) != rhs;
  17150. }
  17151. /*!
  17152. @brief comparison: less than
  17153. Compares whether one JSON value @a lhs is less than another JSON value @a
  17154. rhs according to the following rules:
  17155. - If @a lhs and @a rhs have the same type, the values are compared using
  17156. the default `<` operator.
  17157. - Integer and floating-point numbers are automatically converted before
  17158. comparison
  17159. - In case @a lhs and @a rhs have different types, the values are ignored
  17160. and the order of the types is considered, see
  17161. @ref operator<(const value_t, const value_t).
  17162. @param[in] lhs first JSON value to consider
  17163. @param[in] rhs second JSON value to consider
  17164. @return whether @a lhs is less than @a rhs
  17165. @complexity Linear.
  17166. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17167. @liveexample{The example demonstrates comparing several JSON
  17168. types.,operator__less}
  17169. @since version 1.0.0
  17170. */
  17171. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  17172. {
  17173. const auto lhs_type = lhs.type();
  17174. const auto rhs_type = rhs.type();
  17175. if (lhs_type == rhs_type)
  17176. {
  17177. switch (lhs_type)
  17178. {
  17179. case value_t::array:
  17180. // note parentheses are necessary, see
  17181. // https://github.com/nlohmann/json/issues/1530
  17182. return (*lhs.m_value.array) < (*rhs.m_value.array);
  17183. case value_t::object:
  17184. return (*lhs.m_value.object) < (*rhs.m_value.object);
  17185. case value_t::null:
  17186. return false;
  17187. case value_t::string:
  17188. return (*lhs.m_value.string) < (*rhs.m_value.string);
  17189. case value_t::boolean:
  17190. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  17191. case value_t::number_integer:
  17192. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  17193. case value_t::number_unsigned:
  17194. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  17195. case value_t::number_float:
  17196. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  17197. default:
  17198. return false;
  17199. }
  17200. }
  17201. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  17202. {
  17203. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  17204. }
  17205. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  17206. {
  17207. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  17208. }
  17209. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  17210. {
  17211. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  17212. }
  17213. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  17214. {
  17215. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  17216. }
  17217. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  17218. {
  17219. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  17220. }
  17221. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  17222. {
  17223. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  17224. }
  17225. // We only reach this line if we cannot compare values. In that case,
  17226. // we compare types. Note we have to call the operator explicitly,
  17227. // because MSVC has problems otherwise.
  17228. return operator<(lhs_type, rhs_type);
  17229. }
  17230. /*!
  17231. @brief comparison: less than
  17232. @copydoc operator<(const_reference, const_reference)
  17233. */
  17234. template<typename ScalarType, typename std::enable_if<
  17235. std::is_scalar<ScalarType>::value, int>::type = 0>
  17236. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  17237. {
  17238. return lhs < basic_json(rhs);
  17239. }
  17240. /*!
  17241. @brief comparison: less than
  17242. @copydoc operator<(const_reference, const_reference)
  17243. */
  17244. template<typename ScalarType, typename std::enable_if<
  17245. std::is_scalar<ScalarType>::value, int>::type = 0>
  17246. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  17247. {
  17248. return basic_json(lhs) < rhs;
  17249. }
  17250. /*!
  17251. @brief comparison: less than or equal
  17252. Compares whether one JSON value @a lhs is less than or equal to another
  17253. JSON value by calculating `not (rhs < lhs)`.
  17254. @param[in] lhs first JSON value to consider
  17255. @param[in] rhs second JSON value to consider
  17256. @return whether @a lhs is less than or equal to @a rhs
  17257. @complexity Linear.
  17258. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17259. @liveexample{The example demonstrates comparing several JSON
  17260. types.,operator__greater}
  17261. @since version 1.0.0
  17262. */
  17263. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  17264. {
  17265. return not (rhs < lhs);
  17266. }
  17267. /*!
  17268. @brief comparison: less than or equal
  17269. @copydoc operator<=(const_reference, const_reference)
  17270. */
  17271. template<typename ScalarType, typename std::enable_if<
  17272. std::is_scalar<ScalarType>::value, int>::type = 0>
  17273. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  17274. {
  17275. return lhs <= basic_json(rhs);
  17276. }
  17277. /*!
  17278. @brief comparison: less than or equal
  17279. @copydoc operator<=(const_reference, const_reference)
  17280. */
  17281. template<typename ScalarType, typename std::enable_if<
  17282. std::is_scalar<ScalarType>::value, int>::type = 0>
  17283. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  17284. {
  17285. return basic_json(lhs) <= rhs;
  17286. }
  17287. /*!
  17288. @brief comparison: greater than
  17289. Compares whether one JSON value @a lhs is greater than another
  17290. JSON value by calculating `not (lhs <= rhs)`.
  17291. @param[in] lhs first JSON value to consider
  17292. @param[in] rhs second JSON value to consider
  17293. @return whether @a lhs is greater than to @a rhs
  17294. @complexity Linear.
  17295. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17296. @liveexample{The example demonstrates comparing several JSON
  17297. types.,operator__lessequal}
  17298. @since version 1.0.0
  17299. */
  17300. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  17301. {
  17302. return not (lhs <= rhs);
  17303. }
  17304. /*!
  17305. @brief comparison: greater than
  17306. @copydoc operator>(const_reference, const_reference)
  17307. */
  17308. template<typename ScalarType, typename std::enable_if<
  17309. std::is_scalar<ScalarType>::value, int>::type = 0>
  17310. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  17311. {
  17312. return lhs > basic_json(rhs);
  17313. }
  17314. /*!
  17315. @brief comparison: greater than
  17316. @copydoc operator>(const_reference, const_reference)
  17317. */
  17318. template<typename ScalarType, typename std::enable_if<
  17319. std::is_scalar<ScalarType>::value, int>::type = 0>
  17320. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  17321. {
  17322. return basic_json(lhs) > rhs;
  17323. }
  17324. /*!
  17325. @brief comparison: greater than or equal
  17326. Compares whether one JSON value @a lhs is greater than or equal to another
  17327. JSON value by calculating `not (lhs < rhs)`.
  17328. @param[in] lhs first JSON value to consider
  17329. @param[in] rhs second JSON value to consider
  17330. @return whether @a lhs is greater than or equal to @a rhs
  17331. @complexity Linear.
  17332. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17333. @liveexample{The example demonstrates comparing several JSON
  17334. types.,operator__greaterequal}
  17335. @since version 1.0.0
  17336. */
  17337. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  17338. {
  17339. return not (lhs < rhs);
  17340. }
  17341. /*!
  17342. @brief comparison: greater than or equal
  17343. @copydoc operator>=(const_reference, const_reference)
  17344. */
  17345. template<typename ScalarType, typename std::enable_if<
  17346. std::is_scalar<ScalarType>::value, int>::type = 0>
  17347. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  17348. {
  17349. return lhs >= basic_json(rhs);
  17350. }
  17351. /*!
  17352. @brief comparison: greater than or equal
  17353. @copydoc operator>=(const_reference, const_reference)
  17354. */
  17355. template<typename ScalarType, typename std::enable_if<
  17356. std::is_scalar<ScalarType>::value, int>::type = 0>
  17357. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  17358. {
  17359. return basic_json(lhs) >= rhs;
  17360. }
  17361. /// @}
  17362. ///////////////////
  17363. // serialization //
  17364. ///////////////////
  17365. /// @name serialization
  17366. /// @{
  17367. /*!
  17368. @brief serialize to stream
  17369. Serialize the given JSON value @a j to the output stream @a o. The JSON
  17370. value will be serialized using the @ref dump member function.
  17371. - The indentation of the output can be controlled with the member variable
  17372. `width` of the output stream @a o. For instance, using the manipulator
  17373. `std::setw(4)` on @a o sets the indentation level to `4` and the
  17374. serialization result is the same as calling `dump(4)`.
  17375. - The indentation character can be controlled with the member variable
  17376. `fill` of the output stream @a o. For instance, the manipulator
  17377. `std::setfill('\\t')` sets indentation to use a tab character rather than
  17378. the default space character.
  17379. @param[in,out] o stream to serialize to
  17380. @param[in] j JSON value to serialize
  17381. @return the stream @a o
  17382. @throw type_error.316 if a string stored inside the JSON value is not
  17383. UTF-8 encoded
  17384. @complexity Linear.
  17385. @liveexample{The example below shows the serialization with different
  17386. parameters to `width` to adjust the indentation level.,operator_serialize}
  17387. @since version 1.0.0; indentation character added in version 3.0.0
  17388. */
  17389. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  17390. {
  17391. // read width member and use it as indentation parameter if nonzero
  17392. const bool pretty_print = o.width() > 0;
  17393. const auto indentation = pretty_print ? o.width() : 0;
  17394. // reset width to 0 for subsequent calls to this stream
  17395. o.width(0);
  17396. // do the actual serialization
  17397. serializer s(detail::output_adapter<char>(o), o.fill());
  17398. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  17399. return o;
  17400. }
  17401. /*!
  17402. @brief serialize to stream
  17403. @deprecated This stream operator is deprecated and will be removed in
  17404. future 4.0.0 of the library. Please use
  17405. @ref operator<<(std::ostream&, const basic_json&)
  17406. instead; that is, replace calls like `j >> o;` with `o << j;`.
  17407. @since version 1.0.0; deprecated since version 3.0.0
  17408. */
  17409. JSON_HEDLEY_DEPRECATED(3.0.0)
  17410. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  17411. {
  17412. return o << j;
  17413. }
  17414. /// @}
  17415. /////////////////////
  17416. // deserialization //
  17417. /////////////////////
  17418. /// @name deserialization
  17419. /// @{
  17420. /*!
  17421. @brief deserialize from a compatible input
  17422. This function reads from a compatible input. Examples are:
  17423. - an array of 1-byte values
  17424. - strings with character/literal type with size of 1 byte
  17425. - input streams
  17426. - container with contiguous storage of 1-byte values. Compatible container
  17427. types include `std::vector`, `std::string`, `std::array`,
  17428. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17429. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17430. containers can be used as long as they implement random-access iterators
  17431. and a contiguous storage.
  17432. @pre Each element of the container has a size of 1 byte. Violating this
  17433. precondition yields undefined behavior. **This precondition is enforced
  17434. with a static assertion.**
  17435. @pre The container storage is contiguous. Violating this precondition
  17436. yields undefined behavior. **This precondition is enforced with an
  17437. assertion.**
  17438. @warning There is no way to enforce all preconditions at compile-time. If
  17439. the function is called with a noncompliant container and with
  17440. assertions switched off, the behavior is undefined and will most
  17441. likely yield segmentation violation.
  17442. @param[in] i input to read from
  17443. @param[in] cb a parser callback function of type @ref parser_callback_t
  17444. which is used to control the deserialization by filtering unwanted values
  17445. (optional)
  17446. @param[in] allow_exceptions whether to throw exceptions in case of a
  17447. parse error (optional, true by default)
  17448. @return deserialized JSON value; in case of a parse error and
  17449. @a allow_exceptions set to `false`, the return value will be
  17450. value_t::discarded.
  17451. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17452. of input; expected string literal""`
  17453. @throw parse_error.102 if to_unicode fails or surrogate error
  17454. @throw parse_error.103 if to_unicode fails
  17455. @complexity Linear in the length of the input. The parser is a predictive
  17456. LL(1) parser. The complexity can be higher if the parser callback function
  17457. @a cb has a super-linear complexity.
  17458. @note A UTF-8 byte order mark is silently ignored.
  17459. @liveexample{The example below demonstrates the `parse()` function reading
  17460. from an array.,parse__array__parser_callback_t}
  17461. @liveexample{The example below demonstrates the `parse()` function with
  17462. and without callback function.,parse__string__parser_callback_t}
  17463. @liveexample{The example below demonstrates the `parse()` function with
  17464. and without callback function.,parse__istream__parser_callback_t}
  17465. @liveexample{The example below demonstrates the `parse()` function reading
  17466. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  17467. @since version 2.0.3 (contiguous containers)
  17468. */
  17469. JSON_HEDLEY_WARN_UNUSED_RESULT
  17470. static basic_json parse(detail::input_adapter&& i,
  17471. const parser_callback_t cb = nullptr,
  17472. const bool allow_exceptions = true)
  17473. {
  17474. basic_json result;
  17475. parser(i, cb, allow_exceptions).parse(true, result);
  17476. return result;
  17477. }
  17478. static bool accept(detail::input_adapter&& i)
  17479. {
  17480. return parser(i).accept(true);
  17481. }
  17482. /*!
  17483. @brief generate SAX events
  17484. The SAX event lister must follow the interface of @ref json_sax.
  17485. This function reads from a compatible input. Examples are:
  17486. - an array of 1-byte values
  17487. - strings with character/literal type with size of 1 byte
  17488. - input streams
  17489. - container with contiguous storage of 1-byte values. Compatible container
  17490. types include `std::vector`, `std::string`, `std::array`,
  17491. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  17492. arrays can be used with `std::begin()`/`std::end()`. User-defined
  17493. containers can be used as long as they implement random-access iterators
  17494. and a contiguous storage.
  17495. @pre Each element of the container has a size of 1 byte. Violating this
  17496. precondition yields undefined behavior. **This precondition is enforced
  17497. with a static assertion.**
  17498. @pre The container storage is contiguous. Violating this precondition
  17499. yields undefined behavior. **This precondition is enforced with an
  17500. assertion.**
  17501. @warning There is no way to enforce all preconditions at compile-time. If
  17502. the function is called with a noncompliant container and with
  17503. assertions switched off, the behavior is undefined and will most
  17504. likely yield segmentation violation.
  17505. @param[in] i input to read from
  17506. @param[in,out] sax SAX event listener
  17507. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  17508. @param[in] strict whether the input has to be consumed completely
  17509. @return return value of the last processed SAX event
  17510. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  17511. of input; expected string literal""`
  17512. @throw parse_error.102 if to_unicode fails or surrogate error
  17513. @throw parse_error.103 if to_unicode fails
  17514. @complexity Linear in the length of the input. The parser is a predictive
  17515. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  17516. a super-linear complexity.
  17517. @note A UTF-8 byte order mark is silently ignored.
  17518. @liveexample{The example below demonstrates the `sax_parse()` function
  17519. reading from string and processing the events with a user-defined SAX
  17520. event consumer.,sax_parse}
  17521. @since version 3.2.0
  17522. */
  17523. template <typename SAX>
  17524. JSON_HEDLEY_NON_NULL(2)
  17525. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  17526. input_format_t format = input_format_t::json,
  17527. const bool strict = true)
  17528. {
  17529. assert(sax);
  17530. return format == input_format_t::json
  17531. ? parser(std::move(i)).sax_parse(sax, strict)
  17532. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  17533. }
  17534. /*!
  17535. @brief deserialize from an iterator range with contiguous storage
  17536. This function reads from an iterator range of a container with contiguous
  17537. storage of 1-byte values. Compatible container types include
  17538. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  17539. `std::initializer_list`. Furthermore, C-style arrays can be used with
  17540. `std::begin()`/`std::end()`. User-defined containers can be used as long
  17541. as they implement random-access iterators and a contiguous storage.
  17542. @pre The iterator range is contiguous. Violating this precondition yields
  17543. undefined behavior. **This precondition is enforced with an assertion.**
  17544. @pre Each element in the range has a size of 1 byte. Violating this
  17545. precondition yields undefined behavior. **This precondition is enforced
  17546. with a static assertion.**
  17547. @warning There is no way to enforce all preconditions at compile-time. If
  17548. the function is called with noncompliant iterators and with
  17549. assertions switched off, the behavior is undefined and will most
  17550. likely yield segmentation violation.
  17551. @tparam IteratorType iterator of container with contiguous storage
  17552. @param[in] first begin of the range to parse (included)
  17553. @param[in] last end of the range to parse (excluded)
  17554. @param[in] cb a parser callback function of type @ref parser_callback_t
  17555. which is used to control the deserialization by filtering unwanted values
  17556. (optional)
  17557. @param[in] allow_exceptions whether to throw exceptions in case of a
  17558. parse error (optional, true by default)
  17559. @return deserialized JSON value; in case of a parse error and
  17560. @a allow_exceptions set to `false`, the return value will be
  17561. value_t::discarded.
  17562. @throw parse_error.101 in case of an unexpected token
  17563. @throw parse_error.102 if to_unicode fails or surrogate error
  17564. @throw parse_error.103 if to_unicode fails
  17565. @complexity Linear in the length of the input. The parser is a predictive
  17566. LL(1) parser. The complexity can be higher if the parser callback function
  17567. @a cb has a super-linear complexity.
  17568. @note A UTF-8 byte order mark is silently ignored.
  17569. @liveexample{The example below demonstrates the `parse()` function reading
  17570. from an iterator range.,parse__iteratortype__parser_callback_t}
  17571. @since version 2.0.3
  17572. */
  17573. template<class IteratorType, typename std::enable_if<
  17574. std::is_base_of<
  17575. std::random_access_iterator_tag,
  17576. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17577. static basic_json parse(IteratorType first, IteratorType last,
  17578. const parser_callback_t cb = nullptr,
  17579. const bool allow_exceptions = true)
  17580. {
  17581. basic_json result;
  17582. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  17583. return result;
  17584. }
  17585. template<class IteratorType, typename std::enable_if<
  17586. std::is_base_of<
  17587. std::random_access_iterator_tag,
  17588. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17589. static bool accept(IteratorType first, IteratorType last)
  17590. {
  17591. return parser(detail::input_adapter(first, last)).accept(true);
  17592. }
  17593. template<class IteratorType, class SAX, typename std::enable_if<
  17594. std::is_base_of<
  17595. std::random_access_iterator_tag,
  17596. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  17597. JSON_HEDLEY_NON_NULL(3)
  17598. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  17599. {
  17600. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  17601. }
  17602. /*!
  17603. @brief deserialize from stream
  17604. @deprecated This stream operator is deprecated and will be removed in
  17605. version 4.0.0 of the library. Please use
  17606. @ref operator>>(std::istream&, basic_json&)
  17607. instead; that is, replace calls like `j << i;` with `i >> j;`.
  17608. @since version 1.0.0; deprecated since version 3.0.0
  17609. */
  17610. JSON_HEDLEY_DEPRECATED(3.0.0)
  17611. friend std::istream& operator<<(basic_json& j, std::istream& i)
  17612. {
  17613. return operator>>(i, j);
  17614. }
  17615. /*!
  17616. @brief deserialize from stream
  17617. Deserializes an input stream to a JSON value.
  17618. @param[in,out] i input stream to read a serialized JSON value from
  17619. @param[in,out] j JSON value to write the deserialized input to
  17620. @throw parse_error.101 in case of an unexpected token
  17621. @throw parse_error.102 if to_unicode fails or surrogate error
  17622. @throw parse_error.103 if to_unicode fails
  17623. @complexity Linear in the length of the input. The parser is a predictive
  17624. LL(1) parser.
  17625. @note A UTF-8 byte order mark is silently ignored.
  17626. @liveexample{The example below shows how a JSON value is constructed by
  17627. reading a serialization from a stream.,operator_deserialize}
  17628. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  17629. parser callback function to filter values while parsing
  17630. @since version 1.0.0
  17631. */
  17632. friend std::istream& operator>>(std::istream& i, basic_json& j)
  17633. {
  17634. parser(detail::input_adapter(i)).parse(false, j);
  17635. return i;
  17636. }
  17637. /// @}
  17638. ///////////////////////////
  17639. // convenience functions //
  17640. ///////////////////////////
  17641. /*!
  17642. @brief return the type as string
  17643. Returns the type name as string to be used in error messages - usually to
  17644. indicate that a function was called on a wrong JSON type.
  17645. @return a string representation of a the @a m_type member:
  17646. Value type | return value
  17647. ----------- | -------------
  17648. null | `"null"`
  17649. boolean | `"boolean"`
  17650. string | `"string"`
  17651. number | `"number"` (for all number types)
  17652. object | `"object"`
  17653. array | `"array"`
  17654. discarded | `"discarded"`
  17655. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17656. @complexity Constant.
  17657. @liveexample{The following code exemplifies `type_name()` for all JSON
  17658. types.,type_name}
  17659. @sa @ref type() -- return the type of the JSON value
  17660. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  17661. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  17662. since 3.0.0
  17663. */
  17664. JSON_HEDLEY_RETURNS_NON_NULL
  17665. const char* type_name() const noexcept
  17666. {
  17667. {
  17668. switch (m_type)
  17669. {
  17670. case value_t::null:
  17671. return "null";
  17672. case value_t::object:
  17673. return "object";
  17674. case value_t::array:
  17675. return "array";
  17676. case value_t::string:
  17677. return "string";
  17678. case value_t::boolean:
  17679. return "boolean";
  17680. case value_t::discarded:
  17681. return "discarded";
  17682. default:
  17683. return "number";
  17684. }
  17685. }
  17686. }
  17687. private:
  17688. //////////////////////
  17689. // member variables //
  17690. //////////////////////
  17691. /// the type of the current element
  17692. value_t m_type = value_t::null;
  17693. /// the value of the current element
  17694. json_value m_value = {};
  17695. //////////////////////////////////////////
  17696. // binary serialization/deserialization //
  17697. //////////////////////////////////////////
  17698. /// @name binary serialization/deserialization support
  17699. /// @{
  17700. public:
  17701. /*!
  17702. @brief create a CBOR serialization of a given JSON value
  17703. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  17704. Binary Object Representation) serialization format. CBOR is a binary
  17705. serialization format which aims to be more compact than JSON itself, yet
  17706. more efficient to parse.
  17707. The library uses the following mapping from JSON values types to
  17708. CBOR types according to the CBOR specification (RFC 7049):
  17709. JSON value type | value/range | CBOR type | first byte
  17710. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  17711. null | `null` | Null | 0xF6
  17712. boolean | `true` | True | 0xF5
  17713. boolean | `false` | False | 0xF4
  17714. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  17715. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  17716. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  17717. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  17718. number_integer | -24..-1 | Negative integer | 0x20..0x37
  17719. number_integer | 0..23 | Integer | 0x00..0x17
  17720. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17721. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17722. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17723. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17724. number_unsigned | 0..23 | Integer | 0x00..0x17
  17725. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  17726. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  17727. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  17728. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  17729. number_float | *any value* | Double-Precision Float | 0xFB
  17730. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  17731. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  17732. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  17733. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  17734. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  17735. array | *size*: 0..23 | array | 0x80..0x97
  17736. array | *size*: 23..255 | array (1 byte follow) | 0x98
  17737. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  17738. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  17739. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  17740. object | *size*: 0..23 | map | 0xA0..0xB7
  17741. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  17742. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  17743. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  17744. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  17745. @note The mapping is **complete** in the sense that any JSON value type
  17746. can be converted to a CBOR value.
  17747. @note If NaN or Infinity are stored inside a JSON number, they are
  17748. serialized properly. This behavior differs from the @ref dump()
  17749. function which serializes NaN or Infinity to `null`.
  17750. @note The following CBOR types are not used in the conversion:
  17751. - byte strings (0x40..0x5F)
  17752. - UTF-8 strings terminated by "break" (0x7F)
  17753. - arrays terminated by "break" (0x9F)
  17754. - maps terminated by "break" (0xBF)
  17755. - date/time (0xC0..0xC1)
  17756. - bignum (0xC2..0xC3)
  17757. - decimal fraction (0xC4)
  17758. - bigfloat (0xC5)
  17759. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  17760. - expected conversions (0xD5..0xD7)
  17761. - simple values (0xE0..0xF3, 0xF8)
  17762. - undefined (0xF7)
  17763. - half and single-precision floats (0xF9-0xFA)
  17764. - break (0xFF)
  17765. @param[in] j JSON value to serialize
  17766. @return MessagePack serialization as byte vector
  17767. @complexity Linear in the size of the JSON value @a j.
  17768. @liveexample{The example shows the serialization of a JSON value to a byte
  17769. vector in CBOR format.,to_cbor}
  17770. @sa http://cbor.io
  17771. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  17772. analogous deserialization
  17773. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17774. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17775. related UBJSON format
  17776. @since version 2.0.9
  17777. */
  17778. static std::vector<uint8_t> to_cbor(const basic_json& j)
  17779. {
  17780. std::vector<uint8_t> result;
  17781. to_cbor(j, result);
  17782. return result;
  17783. }
  17784. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  17785. {
  17786. binary_writer<uint8_t>(o).write_cbor(j);
  17787. }
  17788. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  17789. {
  17790. binary_writer<char>(o).write_cbor(j);
  17791. }
  17792. /*!
  17793. @brief create a MessagePack serialization of a given JSON value
  17794. Serializes a given JSON value @a j to a byte vector using the MessagePack
  17795. serialization format. MessagePack is a binary serialization format which
  17796. aims to be more compact than JSON itself, yet more efficient to parse.
  17797. The library uses the following mapping from JSON values types to
  17798. MessagePack types according to the MessagePack specification:
  17799. JSON value type | value/range | MessagePack type | first byte
  17800. --------------- | --------------------------------- | ---------------- | ----------
  17801. null | `null` | nil | 0xC0
  17802. boolean | `true` | true | 0xC3
  17803. boolean | `false` | false | 0xC2
  17804. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  17805. number_integer | -2147483648..-32769 | int32 | 0xD2
  17806. number_integer | -32768..-129 | int16 | 0xD1
  17807. number_integer | -128..-33 | int8 | 0xD0
  17808. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  17809. number_integer | 0..127 | positive fixint | 0x00..0x7F
  17810. number_integer | 128..255 | uint 8 | 0xCC
  17811. number_integer | 256..65535 | uint 16 | 0xCD
  17812. number_integer | 65536..4294967295 | uint 32 | 0xCE
  17813. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17814. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  17815. number_unsigned | 128..255 | uint 8 | 0xCC
  17816. number_unsigned | 256..65535 | uint 16 | 0xCD
  17817. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  17818. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  17819. number_float | *any value* | float 64 | 0xCB
  17820. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  17821. string | *length*: 32..255 | str 8 | 0xD9
  17822. string | *length*: 256..65535 | str 16 | 0xDA
  17823. string | *length*: 65536..4294967295 | str 32 | 0xDB
  17824. array | *size*: 0..15 | fixarray | 0x90..0x9F
  17825. array | *size*: 16..65535 | array 16 | 0xDC
  17826. array | *size*: 65536..4294967295 | array 32 | 0xDD
  17827. object | *size*: 0..15 | fix map | 0x80..0x8F
  17828. object | *size*: 16..65535 | map 16 | 0xDE
  17829. object | *size*: 65536..4294967295 | map 32 | 0xDF
  17830. @note The mapping is **complete** in the sense that any JSON value type
  17831. can be converted to a MessagePack value.
  17832. @note The following values can **not** be converted to a MessagePack value:
  17833. - strings with more than 4294967295 bytes
  17834. - arrays with more than 4294967295 elements
  17835. - objects with more than 4294967295 elements
  17836. @note The following MessagePack types are not used in the conversion:
  17837. - bin 8 - bin 32 (0xC4..0xC6)
  17838. - ext 8 - ext 32 (0xC7..0xC9)
  17839. - float 32 (0xCA)
  17840. - fixext 1 - fixext 16 (0xD4..0xD8)
  17841. @note Any MessagePack output created @ref to_msgpack can be successfully
  17842. parsed by @ref from_msgpack.
  17843. @note If NaN or Infinity are stored inside a JSON number, they are
  17844. serialized properly. This behavior differs from the @ref dump()
  17845. function which serializes NaN or Infinity to `null`.
  17846. @param[in] j JSON value to serialize
  17847. @return MessagePack serialization as byte vector
  17848. @complexity Linear in the size of the JSON value @a j.
  17849. @liveexample{The example shows the serialization of a JSON value to a byte
  17850. vector in MessagePack format.,to_msgpack}
  17851. @sa http://msgpack.org
  17852. @sa @ref from_msgpack for the analogous deserialization
  17853. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17854. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17855. related UBJSON format
  17856. @since version 2.0.9
  17857. */
  17858. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  17859. {
  17860. std::vector<uint8_t> result;
  17861. to_msgpack(j, result);
  17862. return result;
  17863. }
  17864. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  17865. {
  17866. binary_writer<uint8_t>(o).write_msgpack(j);
  17867. }
  17868. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  17869. {
  17870. binary_writer<char>(o).write_msgpack(j);
  17871. }
  17872. /*!
  17873. @brief create a UBJSON serialization of a given JSON value
  17874. Serializes a given JSON value @a j to a byte vector using the UBJSON
  17875. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  17876. than JSON itself, yet more efficient to parse.
  17877. The library uses the following mapping from JSON values types to
  17878. UBJSON types according to the UBJSON specification:
  17879. JSON value type | value/range | UBJSON type | marker
  17880. --------------- | --------------------------------- | ----------- | ------
  17881. null | `null` | null | `Z`
  17882. boolean | `true` | true | `T`
  17883. boolean | `false` | false | `F`
  17884. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  17885. number_integer | -2147483648..-32769 | int32 | `l`
  17886. number_integer | -32768..-129 | int16 | `I`
  17887. number_integer | -128..127 | int8 | `i`
  17888. number_integer | 128..255 | uint8 | `U`
  17889. number_integer | 256..32767 | int16 | `I`
  17890. number_integer | 32768..2147483647 | int32 | `l`
  17891. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  17892. number_unsigned | 0..127 | int8 | `i`
  17893. number_unsigned | 128..255 | uint8 | `U`
  17894. number_unsigned | 256..32767 | int16 | `I`
  17895. number_unsigned | 32768..2147483647 | int32 | `l`
  17896. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  17897. number_float | *any value* | float64 | `D`
  17898. string | *with shortest length indicator* | string | `S`
  17899. array | *see notes on optimized format* | array | `[`
  17900. object | *see notes on optimized format* | map | `{`
  17901. @note The mapping is **complete** in the sense that any JSON value type
  17902. can be converted to a UBJSON value.
  17903. @note The following values can **not** be converted to a UBJSON value:
  17904. - strings with more than 9223372036854775807 bytes (theoretical)
  17905. - unsigned integer numbers above 9223372036854775807
  17906. @note The following markers are not used in the conversion:
  17907. - `Z`: no-op values are not created.
  17908. - `C`: single-byte strings are serialized with `S` markers.
  17909. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  17910. by @ref from_ubjson.
  17911. @note If NaN or Infinity are stored inside a JSON number, they are
  17912. serialized properly. This behavior differs from the @ref dump()
  17913. function which serializes NaN or Infinity to `null`.
  17914. @note The optimized formats for containers are supported: Parameter
  17915. @a use_size adds size information to the beginning of a container and
  17916. removes the closing marker. Parameter @a use_type further checks
  17917. whether all elements of a container have the same type and adds the
  17918. type marker to the beginning of the container. The @a use_type
  17919. parameter must only be used together with @a use_size = true. Note
  17920. that @a use_size = true alone may result in larger representations -
  17921. the benefit of this parameter is that the receiving side is
  17922. immediately informed on the number of elements of the container.
  17923. @param[in] j JSON value to serialize
  17924. @param[in] use_size whether to add size annotations to container types
  17925. @param[in] use_type whether to add type annotations to container types
  17926. (must be combined with @a use_size = true)
  17927. @return UBJSON serialization as byte vector
  17928. @complexity Linear in the size of the JSON value @a j.
  17929. @liveexample{The example shows the serialization of a JSON value to a byte
  17930. vector in UBJSON format.,to_ubjson}
  17931. @sa http://ubjson.org
  17932. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  17933. analogous deserialization
  17934. @sa @ref to_cbor(const basic_json& for the related CBOR format
  17935. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17936. @since version 3.1.0
  17937. */
  17938. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  17939. const bool use_size = false,
  17940. const bool use_type = false)
  17941. {
  17942. std::vector<uint8_t> result;
  17943. to_ubjson(j, result, use_size, use_type);
  17944. return result;
  17945. }
  17946. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  17947. const bool use_size = false, const bool use_type = false)
  17948. {
  17949. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  17950. }
  17951. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  17952. const bool use_size = false, const bool use_type = false)
  17953. {
  17954. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  17955. }
  17956. /*!
  17957. @brief Serializes the given JSON object `j` to BSON and returns a vector
  17958. containing the corresponding BSON-representation.
  17959. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  17960. stored as a single entity (a so-called document).
  17961. The library uses the following mapping from JSON values types to BSON types:
  17962. JSON value type | value/range | BSON type | marker
  17963. --------------- | --------------------------------- | ----------- | ------
  17964. null | `null` | null | 0x0A
  17965. boolean | `true`, `false` | boolean | 0x08
  17966. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  17967. number_integer | -2147483648..2147483647 | int32 | 0x10
  17968. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  17969. number_unsigned | 0..2147483647 | int32 | 0x10
  17970. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  17971. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  17972. number_float | *any value* | double | 0x01
  17973. string | *any value* | string | 0x02
  17974. array | *any value* | document | 0x04
  17975. object | *any value* | document | 0x03
  17976. @warning The mapping is **incomplete**, since only JSON-objects (and things
  17977. contained therein) can be serialized to BSON.
  17978. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  17979. and the keys may not contain U+0000, since they are serialized a
  17980. zero-terminated c-strings.
  17981. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  17982. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  17983. @throw type_error.317 if `!j.is_object()`
  17984. @pre The input `j` is required to be an object: `j.is_object() == true`.
  17985. @note Any BSON output created via @ref to_bson can be successfully parsed
  17986. by @ref from_bson.
  17987. @param[in] j JSON value to serialize
  17988. @return BSON serialization as byte vector
  17989. @complexity Linear in the size of the JSON value @a j.
  17990. @liveexample{The example shows the serialization of a JSON value to a byte
  17991. vector in BSON format.,to_bson}
  17992. @sa http://bsonspec.org/spec.html
  17993. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  17994. analogous deserialization
  17995. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  17996. related UBJSON format
  17997. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  17998. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  17999. */
  18000. static std::vector<uint8_t> to_bson(const basic_json& j)
  18001. {
  18002. std::vector<uint8_t> result;
  18003. to_bson(j, result);
  18004. return result;
  18005. }
  18006. /*!
  18007. @brief Serializes the given JSON object `j` to BSON and forwards the
  18008. corresponding BSON-representation to the given output_adapter `o`.
  18009. @param j The JSON object to convert to BSON.
  18010. @param o The output adapter that receives the binary BSON representation.
  18011. @pre The input `j` shall be an object: `j.is_object() == true`
  18012. @sa @ref to_bson(const basic_json&)
  18013. */
  18014. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  18015. {
  18016. binary_writer<uint8_t>(o).write_bson(j);
  18017. }
  18018. /*!
  18019. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  18020. */
  18021. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  18022. {
  18023. binary_writer<char>(o).write_bson(j);
  18024. }
  18025. /*!
  18026. @brief create a JSON value from an input in CBOR format
  18027. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  18028. Binary Object Representation) serialization format.
  18029. The library maps CBOR types to JSON value types as follows:
  18030. CBOR type | JSON value type | first byte
  18031. ---------------------- | --------------- | ----------
  18032. Integer | number_unsigned | 0x00..0x17
  18033. Unsigned integer | number_unsigned | 0x18
  18034. Unsigned integer | number_unsigned | 0x19
  18035. Unsigned integer | number_unsigned | 0x1A
  18036. Unsigned integer | number_unsigned | 0x1B
  18037. Negative integer | number_integer | 0x20..0x37
  18038. Negative integer | number_integer | 0x38
  18039. Negative integer | number_integer | 0x39
  18040. Negative integer | number_integer | 0x3A
  18041. Negative integer | number_integer | 0x3B
  18042. Negative integer | number_integer | 0x40..0x57
  18043. UTF-8 string | string | 0x60..0x77
  18044. UTF-8 string | string | 0x78
  18045. UTF-8 string | string | 0x79
  18046. UTF-8 string | string | 0x7A
  18047. UTF-8 string | string | 0x7B
  18048. UTF-8 string | string | 0x7F
  18049. array | array | 0x80..0x97
  18050. array | array | 0x98
  18051. array | array | 0x99
  18052. array | array | 0x9A
  18053. array | array | 0x9B
  18054. array | array | 0x9F
  18055. map | object | 0xA0..0xB7
  18056. map | object | 0xB8
  18057. map | object | 0xB9
  18058. map | object | 0xBA
  18059. map | object | 0xBB
  18060. map | object | 0xBF
  18061. False | `false` | 0xF4
  18062. True | `true` | 0xF5
  18063. Null | `null` | 0xF6
  18064. Half-Precision Float | number_float | 0xF9
  18065. Single-Precision Float | number_float | 0xFA
  18066. Double-Precision Float | number_float | 0xFB
  18067. @warning The mapping is **incomplete** in the sense that not all CBOR
  18068. types can be converted to a JSON value. The following CBOR types
  18069. are not supported and will yield parse errors (parse_error.112):
  18070. - byte strings (0x40..0x5F)
  18071. - date/time (0xC0..0xC1)
  18072. - bignum (0xC2..0xC3)
  18073. - decimal fraction (0xC4)
  18074. - bigfloat (0xC5)
  18075. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  18076. - expected conversions (0xD5..0xD7)
  18077. - simple values (0xE0..0xF3, 0xF8)
  18078. - undefined (0xF7)
  18079. @warning CBOR allows map keys of any type, whereas JSON only allows
  18080. strings as keys in object values. Therefore, CBOR maps with keys
  18081. other than UTF-8 strings are rejected (parse_error.113).
  18082. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  18083. @ref from_cbor.
  18084. @param[in] i an input in CBOR format convertible to an input adapter
  18085. @param[in] strict whether to expect the input to be consumed until EOF
  18086. (true by default)
  18087. @param[in] allow_exceptions whether to throw exceptions in case of a
  18088. parse error (optional, true by default)
  18089. @return deserialized JSON value; in case of a parse error and
  18090. @a allow_exceptions set to `false`, the return value will be
  18091. value_t::discarded.
  18092. @throw parse_error.110 if the given input ends prematurely or the end of
  18093. file was not reached when @a strict was set to true
  18094. @throw parse_error.112 if unsupported features from CBOR were
  18095. used in the given input @a v or if the input is not valid CBOR
  18096. @throw parse_error.113 if a string was expected as map key, but not found
  18097. @complexity Linear in the size of the input @a i.
  18098. @liveexample{The example shows the deserialization of a byte vector in CBOR
  18099. format to a JSON value.,from_cbor}
  18100. @sa http://cbor.io
  18101. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  18102. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  18103. related MessagePack format
  18104. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18105. related UBJSON format
  18106. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18107. consume input adapters, removed start_index parameter, and added
  18108. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18109. since 3.2.0
  18110. */
  18111. JSON_HEDLEY_WARN_UNUSED_RESULT
  18112. static basic_json from_cbor(detail::input_adapter&& i,
  18113. const bool strict = true,
  18114. const bool allow_exceptions = true)
  18115. {
  18116. basic_json result;
  18117. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18118. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  18119. return res ? result : basic_json(value_t::discarded);
  18120. }
  18121. /*!
  18122. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  18123. */
  18124. template<typename A1, typename A2,
  18125. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18126. JSON_HEDLEY_WARN_UNUSED_RESULT
  18127. static basic_json from_cbor(A1 && a1, A2 && a2,
  18128. const bool strict = true,
  18129. const bool allow_exceptions = true)
  18130. {
  18131. basic_json result;
  18132. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18133. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  18134. return res ? result : basic_json(value_t::discarded);
  18135. }
  18136. /*!
  18137. @brief create a JSON value from an input in MessagePack format
  18138. Deserializes a given input @a i to a JSON value using the MessagePack
  18139. serialization format.
  18140. The library maps MessagePack types to JSON value types as follows:
  18141. MessagePack type | JSON value type | first byte
  18142. ---------------- | --------------- | ----------
  18143. positive fixint | number_unsigned | 0x00..0x7F
  18144. fixmap | object | 0x80..0x8F
  18145. fixarray | array | 0x90..0x9F
  18146. fixstr | string | 0xA0..0xBF
  18147. nil | `null` | 0xC0
  18148. false | `false` | 0xC2
  18149. true | `true` | 0xC3
  18150. float 32 | number_float | 0xCA
  18151. float 64 | number_float | 0xCB
  18152. uint 8 | number_unsigned | 0xCC
  18153. uint 16 | number_unsigned | 0xCD
  18154. uint 32 | number_unsigned | 0xCE
  18155. uint 64 | number_unsigned | 0xCF
  18156. int 8 | number_integer | 0xD0
  18157. int 16 | number_integer | 0xD1
  18158. int 32 | number_integer | 0xD2
  18159. int 64 | number_integer | 0xD3
  18160. str 8 | string | 0xD9
  18161. str 16 | string | 0xDA
  18162. str 32 | string | 0xDB
  18163. array 16 | array | 0xDC
  18164. array 32 | array | 0xDD
  18165. map 16 | object | 0xDE
  18166. map 32 | object | 0xDF
  18167. negative fixint | number_integer | 0xE0-0xFF
  18168. @warning The mapping is **incomplete** in the sense that not all
  18169. MessagePack types can be converted to a JSON value. The following
  18170. MessagePack types are not supported and will yield parse errors:
  18171. - bin 8 - bin 32 (0xC4..0xC6)
  18172. - ext 8 - ext 32 (0xC7..0xC9)
  18173. - fixext 1 - fixext 16 (0xD4..0xD8)
  18174. @note Any MessagePack output created @ref to_msgpack can be successfully
  18175. parsed by @ref from_msgpack.
  18176. @param[in] i an input in MessagePack format convertible to an input
  18177. adapter
  18178. @param[in] strict whether to expect the input to be consumed until EOF
  18179. (true by default)
  18180. @param[in] allow_exceptions whether to throw exceptions in case of a
  18181. parse error (optional, true by default)
  18182. @return deserialized JSON value; in case of a parse error and
  18183. @a allow_exceptions set to `false`, the return value will be
  18184. value_t::discarded.
  18185. @throw parse_error.110 if the given input ends prematurely or the end of
  18186. file was not reached when @a strict was set to true
  18187. @throw parse_error.112 if unsupported features from MessagePack were
  18188. used in the given input @a i or if the input is not valid MessagePack
  18189. @throw parse_error.113 if a string was expected as map key, but not found
  18190. @complexity Linear in the size of the input @a i.
  18191. @liveexample{The example shows the deserialization of a byte vector in
  18192. MessagePack format to a JSON value.,from_msgpack}
  18193. @sa http://msgpack.org
  18194. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  18195. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18196. related CBOR format
  18197. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  18198. the related UBJSON format
  18199. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18200. the related BSON format
  18201. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  18202. consume input adapters, removed start_index parameter, and added
  18203. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  18204. since 3.2.0
  18205. */
  18206. JSON_HEDLEY_WARN_UNUSED_RESULT
  18207. static basic_json from_msgpack(detail::input_adapter&& i,
  18208. const bool strict = true,
  18209. const bool allow_exceptions = true)
  18210. {
  18211. basic_json result;
  18212. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18213. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  18214. return res ? result : basic_json(value_t::discarded);
  18215. }
  18216. /*!
  18217. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  18218. */
  18219. template<typename A1, typename A2,
  18220. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18221. JSON_HEDLEY_WARN_UNUSED_RESULT
  18222. static basic_json from_msgpack(A1 && a1, A2 && a2,
  18223. const bool strict = true,
  18224. const bool allow_exceptions = true)
  18225. {
  18226. basic_json result;
  18227. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18228. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  18229. return res ? result : basic_json(value_t::discarded);
  18230. }
  18231. /*!
  18232. @brief create a JSON value from an input in UBJSON format
  18233. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  18234. Binary JSON) serialization format.
  18235. The library maps UBJSON types to JSON value types as follows:
  18236. UBJSON type | JSON value type | marker
  18237. ----------- | --------------------------------------- | ------
  18238. no-op | *no value, next value is read* | `N`
  18239. null | `null` | `Z`
  18240. false | `false` | `F`
  18241. true | `true` | `T`
  18242. float32 | number_float | `d`
  18243. float64 | number_float | `D`
  18244. uint8 | number_unsigned | `U`
  18245. int8 | number_integer | `i`
  18246. int16 | number_integer | `I`
  18247. int32 | number_integer | `l`
  18248. int64 | number_integer | `L`
  18249. string | string | `S`
  18250. char | string | `C`
  18251. array | array (optimized values are supported) | `[`
  18252. object | object (optimized values are supported) | `{`
  18253. @note The mapping is **complete** in the sense that any UBJSON value can
  18254. be converted to a JSON value.
  18255. @param[in] i an input in UBJSON format convertible to an input adapter
  18256. @param[in] strict whether to expect the input to be consumed until EOF
  18257. (true by default)
  18258. @param[in] allow_exceptions whether to throw exceptions in case of a
  18259. parse error (optional, true by default)
  18260. @return deserialized JSON value; in case of a parse error and
  18261. @a allow_exceptions set to `false`, the return value will be
  18262. value_t::discarded.
  18263. @throw parse_error.110 if the given input ends prematurely or the end of
  18264. file was not reached when @a strict was set to true
  18265. @throw parse_error.112 if a parse error occurs
  18266. @throw parse_error.113 if a string could not be parsed successfully
  18267. @complexity Linear in the size of the input @a i.
  18268. @liveexample{The example shows the deserialization of a byte vector in
  18269. UBJSON format to a JSON value.,from_ubjson}
  18270. @sa http://ubjson.org
  18271. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  18272. analogous serialization
  18273. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18274. related CBOR format
  18275. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18276. the related MessagePack format
  18277. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  18278. the related BSON format
  18279. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  18280. */
  18281. JSON_HEDLEY_WARN_UNUSED_RESULT
  18282. static basic_json from_ubjson(detail::input_adapter&& i,
  18283. const bool strict = true,
  18284. const bool allow_exceptions = true)
  18285. {
  18286. basic_json result;
  18287. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18288. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  18289. return res ? result : basic_json(value_t::discarded);
  18290. }
  18291. /*!
  18292. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  18293. */
  18294. template<typename A1, typename A2,
  18295. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18296. JSON_HEDLEY_WARN_UNUSED_RESULT
  18297. static basic_json from_ubjson(A1 && a1, A2 && a2,
  18298. const bool strict = true,
  18299. const bool allow_exceptions = true)
  18300. {
  18301. basic_json result;
  18302. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18303. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  18304. return res ? result : basic_json(value_t::discarded);
  18305. }
  18306. /*!
  18307. @brief Create a JSON value from an input in BSON format
  18308. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  18309. serialization format.
  18310. The library maps BSON record types to JSON value types as follows:
  18311. BSON type | BSON marker byte | JSON value type
  18312. --------------- | ---------------- | ---------------------------
  18313. double | 0x01 | number_float
  18314. string | 0x02 | string
  18315. document | 0x03 | object
  18316. array | 0x04 | array
  18317. binary | 0x05 | still unsupported
  18318. undefined | 0x06 | still unsupported
  18319. ObjectId | 0x07 | still unsupported
  18320. boolean | 0x08 | boolean
  18321. UTC Date-Time | 0x09 | still unsupported
  18322. null | 0x0A | null
  18323. Regular Expr. | 0x0B | still unsupported
  18324. DB Pointer | 0x0C | still unsupported
  18325. JavaScript Code | 0x0D | still unsupported
  18326. Symbol | 0x0E | still unsupported
  18327. JavaScript Code | 0x0F | still unsupported
  18328. int32 | 0x10 | number_integer
  18329. Timestamp | 0x11 | still unsupported
  18330. 128-bit decimal float | 0x13 | still unsupported
  18331. Max Key | 0x7F | still unsupported
  18332. Min Key | 0xFF | still unsupported
  18333. @warning The mapping is **incomplete**. The unsupported mappings
  18334. are indicated in the table above.
  18335. @param[in] i an input in BSON format convertible to an input adapter
  18336. @param[in] strict whether to expect the input to be consumed until EOF
  18337. (true by default)
  18338. @param[in] allow_exceptions whether to throw exceptions in case of a
  18339. parse error (optional, true by default)
  18340. @return deserialized JSON value; in case of a parse error and
  18341. @a allow_exceptions set to `false`, the return value will be
  18342. value_t::discarded.
  18343. @throw parse_error.114 if an unsupported BSON record type is encountered
  18344. @complexity Linear in the size of the input @a i.
  18345. @liveexample{The example shows the deserialization of a byte vector in
  18346. BSON format to a JSON value.,from_bson}
  18347. @sa http://bsonspec.org/spec.html
  18348. @sa @ref to_bson(const basic_json&) for the analogous serialization
  18349. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  18350. related CBOR format
  18351. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  18352. the related MessagePack format
  18353. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  18354. related UBJSON format
  18355. */
  18356. JSON_HEDLEY_WARN_UNUSED_RESULT
  18357. static basic_json from_bson(detail::input_adapter&& i,
  18358. const bool strict = true,
  18359. const bool allow_exceptions = true)
  18360. {
  18361. basic_json result;
  18362. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18363. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  18364. return res ? result : basic_json(value_t::discarded);
  18365. }
  18366. /*!
  18367. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  18368. */
  18369. template<typename A1, typename A2,
  18370. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  18371. JSON_HEDLEY_WARN_UNUSED_RESULT
  18372. static basic_json from_bson(A1 && a1, A2 && a2,
  18373. const bool strict = true,
  18374. const bool allow_exceptions = true)
  18375. {
  18376. basic_json result;
  18377. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  18378. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  18379. return res ? result : basic_json(value_t::discarded);
  18380. }
  18381. /// @}
  18382. //////////////////////////
  18383. // JSON Pointer support //
  18384. //////////////////////////
  18385. /// @name JSON Pointer functions
  18386. /// @{
  18387. /*!
  18388. @brief access specified element via JSON Pointer
  18389. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18390. No bound checking is performed. Similar to @ref operator[](const typename
  18391. object_t::key_type&), `null` values are created in arrays and objects if
  18392. necessary.
  18393. In particular:
  18394. - If the JSON pointer points to an object key that does not exist, it
  18395. is created an filled with a `null` value before a reference to it
  18396. is returned.
  18397. - If the JSON pointer points to an array index that does not exist, it
  18398. is created an filled with a `null` value before a reference to it
  18399. is returned. All indices between the current maximum and the given
  18400. index are also filled with `null`.
  18401. - The special value `-` is treated as a synonym for the index past the
  18402. end.
  18403. @param[in] ptr a JSON pointer
  18404. @return reference to the element pointed to by @a ptr
  18405. @complexity Constant.
  18406. @throw parse_error.106 if an array index begins with '0'
  18407. @throw parse_error.109 if an array index was not a number
  18408. @throw out_of_range.404 if the JSON pointer can not be resolved
  18409. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  18410. @since version 2.0.0
  18411. */
  18412. reference operator[](const json_pointer& ptr)
  18413. {
  18414. return ptr.get_unchecked(this);
  18415. }
  18416. /*!
  18417. @brief access specified element via JSON Pointer
  18418. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  18419. No bound checking is performed. The function does not change the JSON
  18420. value; no `null` values are created. In particular, the the special value
  18421. `-` yields an exception.
  18422. @param[in] ptr JSON pointer to the desired element
  18423. @return const reference to the element pointed to by @a ptr
  18424. @complexity Constant.
  18425. @throw parse_error.106 if an array index begins with '0'
  18426. @throw parse_error.109 if an array index was not a number
  18427. @throw out_of_range.402 if the array index '-' is used
  18428. @throw out_of_range.404 if the JSON pointer can not be resolved
  18429. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  18430. @since version 2.0.0
  18431. */
  18432. const_reference operator[](const json_pointer& ptr) const
  18433. {
  18434. return ptr.get_unchecked(this);
  18435. }
  18436. /*!
  18437. @brief access specified element via JSON Pointer
  18438. Returns a reference to the element at with specified JSON pointer @a ptr,
  18439. with bounds checking.
  18440. @param[in] ptr JSON pointer to the desired element
  18441. @return reference to the element pointed to by @a ptr
  18442. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18443. begins with '0'. See example below.
  18444. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18445. is not a number. See example below.
  18446. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18447. is out of range. See example below.
  18448. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18449. pointer @a ptr. As `at` provides checked access (and no elements are
  18450. implicitly inserted), the index '-' is always invalid. See example below.
  18451. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18452. which cannot be found. See example below.
  18453. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18454. See example below.
  18455. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18456. changes in the JSON value.
  18457. @complexity Constant.
  18458. @since version 2.0.0
  18459. @liveexample{The behavior is shown in the example.,at_json_pointer}
  18460. */
  18461. reference at(const json_pointer& ptr)
  18462. {
  18463. return ptr.get_checked(this);
  18464. }
  18465. /*!
  18466. @brief access specified element via JSON Pointer
  18467. Returns a const reference to the element at with specified JSON pointer @a
  18468. ptr, with bounds checking.
  18469. @param[in] ptr JSON pointer to the desired element
  18470. @return reference to the element pointed to by @a ptr
  18471. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  18472. begins with '0'. See example below.
  18473. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  18474. is not a number. See example below.
  18475. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  18476. is out of range. See example below.
  18477. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  18478. pointer @a ptr. As `at` provides checked access (and no elements are
  18479. implicitly inserted), the index '-' is always invalid. See example below.
  18480. @throw out_of_range.403 if the JSON pointer describes a key of an object
  18481. which cannot be found. See example below.
  18482. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  18483. See example below.
  18484. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  18485. changes in the JSON value.
  18486. @complexity Constant.
  18487. @since version 2.0.0
  18488. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  18489. */
  18490. const_reference at(const json_pointer& ptr) const
  18491. {
  18492. return ptr.get_checked(this);
  18493. }
  18494. /*!
  18495. @brief return flattened JSON value
  18496. The function creates a JSON object whose keys are JSON pointers (see [RFC
  18497. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  18498. primitive. The original JSON value can be restored using the @ref
  18499. unflatten() function.
  18500. @return an object that maps JSON pointers to primitive values
  18501. @note Empty objects and arrays are flattened to `null` and will not be
  18502. reconstructed correctly by the @ref unflatten() function.
  18503. @complexity Linear in the size the JSON value.
  18504. @liveexample{The following code shows how a JSON object is flattened to an
  18505. object whose keys consist of JSON pointers.,flatten}
  18506. @sa @ref unflatten() for the reverse function
  18507. @since version 2.0.0
  18508. */
  18509. basic_json flatten() const
  18510. {
  18511. basic_json result(value_t::object);
  18512. json_pointer::flatten("", *this, result);
  18513. return result;
  18514. }
  18515. /*!
  18516. @brief unflatten a previously flattened JSON value
  18517. The function restores the arbitrary nesting of a JSON value that has been
  18518. flattened before using the @ref flatten() function. The JSON value must
  18519. meet certain constraints:
  18520. 1. The value must be an object.
  18521. 2. The keys must be JSON pointers (see
  18522. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  18523. 3. The mapped values must be primitive JSON types.
  18524. @return the original JSON from a flattened version
  18525. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  18526. values and can not unflattened to their original type. Apart from
  18527. this example, for a JSON value `j`, the following is always true:
  18528. `j == j.flatten().unflatten()`.
  18529. @complexity Linear in the size the JSON value.
  18530. @throw type_error.314 if value is not an object
  18531. @throw type_error.315 if object values are not primitive
  18532. @liveexample{The following code shows how a flattened JSON object is
  18533. unflattened into the original nested JSON object.,unflatten}
  18534. @sa @ref flatten() for the reverse function
  18535. @since version 2.0.0
  18536. */
  18537. basic_json unflatten() const
  18538. {
  18539. return json_pointer::unflatten(*this);
  18540. }
  18541. /// @}
  18542. //////////////////////////
  18543. // JSON Patch functions //
  18544. //////////////////////////
  18545. /// @name JSON Patch functions
  18546. /// @{
  18547. /*!
  18548. @brief applies a JSON patch
  18549. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  18550. expressing a sequence of operations to apply to a JSON) document. With
  18551. this function, a JSON Patch is applied to the current JSON value by
  18552. executing all operations from the patch.
  18553. @param[in] json_patch JSON patch document
  18554. @return patched document
  18555. @note The application of a patch is atomic: Either all operations succeed
  18556. and the patched document is returned or an exception is thrown. In
  18557. any case, the original value is not changed: the patch is applied
  18558. to a copy of the value.
  18559. @throw parse_error.104 if the JSON patch does not consist of an array of
  18560. objects
  18561. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  18562. attributes are missing); example: `"operation add must have member path"`
  18563. @throw out_of_range.401 if an array index is out of range.
  18564. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  18565. resolved successfully in the current JSON value; example: `"key baz not
  18566. found"`
  18567. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  18568. "move")
  18569. @throw other_error.501 if "test" operation was unsuccessful
  18570. @complexity Linear in the size of the JSON value and the length of the
  18571. JSON patch. As usually only a fraction of the JSON value is affected by
  18572. the patch, the complexity can usually be neglected.
  18573. @liveexample{The following code shows how a JSON patch is applied to a
  18574. value.,patch}
  18575. @sa @ref diff -- create a JSON patch by comparing two JSON values
  18576. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18577. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  18578. @since version 2.0.0
  18579. */
  18580. basic_json patch(const basic_json& json_patch) const
  18581. {
  18582. // make a working copy to apply the patch to
  18583. basic_json result = *this;
  18584. // the valid JSON Patch operations
  18585. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  18586. const auto get_op = [](const std::string & op)
  18587. {
  18588. if (op == "add")
  18589. {
  18590. return patch_operations::add;
  18591. }
  18592. if (op == "remove")
  18593. {
  18594. return patch_operations::remove;
  18595. }
  18596. if (op == "replace")
  18597. {
  18598. return patch_operations::replace;
  18599. }
  18600. if (op == "move")
  18601. {
  18602. return patch_operations::move;
  18603. }
  18604. if (op == "copy")
  18605. {
  18606. return patch_operations::copy;
  18607. }
  18608. if (op == "test")
  18609. {
  18610. return patch_operations::test;
  18611. }
  18612. return patch_operations::invalid;
  18613. };
  18614. // wrapper for "add" operation; add value at ptr
  18615. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  18616. {
  18617. // adding to the root of the target document means replacing it
  18618. if (ptr.empty())
  18619. {
  18620. result = val;
  18621. return;
  18622. }
  18623. // make sure the top element of the pointer exists
  18624. json_pointer top_pointer = ptr.top();
  18625. if (top_pointer != ptr)
  18626. {
  18627. result.at(top_pointer);
  18628. }
  18629. // get reference to parent of JSON pointer ptr
  18630. const auto last_path = ptr.back();
  18631. ptr.pop_back();
  18632. basic_json& parent = result[ptr];
  18633. switch (parent.m_type)
  18634. {
  18635. case value_t::null:
  18636. case value_t::object:
  18637. {
  18638. // use operator[] to add value
  18639. parent[last_path] = val;
  18640. break;
  18641. }
  18642. case value_t::array:
  18643. {
  18644. if (last_path == "-")
  18645. {
  18646. // special case: append to back
  18647. parent.push_back(val);
  18648. }
  18649. else
  18650. {
  18651. const auto idx = json_pointer::array_index(last_path);
  18652. if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  18653. {
  18654. // avoid undefined behavior
  18655. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  18656. }
  18657. // default case: insert add offset
  18658. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  18659. }
  18660. break;
  18661. }
  18662. // if there exists a parent it cannot be primitive
  18663. default: // LCOV_EXCL_LINE
  18664. assert(false); // LCOV_EXCL_LINE
  18665. }
  18666. };
  18667. // wrapper for "remove" operation; remove value at ptr
  18668. const auto operation_remove = [&result](json_pointer & ptr)
  18669. {
  18670. // get reference to parent of JSON pointer ptr
  18671. const auto last_path = ptr.back();
  18672. ptr.pop_back();
  18673. basic_json& parent = result.at(ptr);
  18674. // remove child
  18675. if (parent.is_object())
  18676. {
  18677. // perform range check
  18678. auto it = parent.find(last_path);
  18679. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  18680. {
  18681. parent.erase(it);
  18682. }
  18683. else
  18684. {
  18685. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  18686. }
  18687. }
  18688. else if (parent.is_array())
  18689. {
  18690. // note erase performs range check
  18691. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  18692. }
  18693. };
  18694. // type check: top level value must be an array
  18695. if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
  18696. {
  18697. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18698. }
  18699. // iterate and apply the operations
  18700. for (const auto& val : json_patch)
  18701. {
  18702. // wrapper to get a value for an operation
  18703. const auto get_value = [&val](const std::string & op,
  18704. const std::string & member,
  18705. bool string_type) -> basic_json &
  18706. {
  18707. // find value
  18708. auto it = val.m_value.object->find(member);
  18709. // context-sensitive error message
  18710. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  18711. // check if desired value is present
  18712. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  18713. {
  18714. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  18715. }
  18716. // check if result is of type string
  18717. if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
  18718. {
  18719. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  18720. }
  18721. // no error: return value
  18722. return it->second;
  18723. };
  18724. // type check: every element of the array must be an object
  18725. if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
  18726. {
  18727. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  18728. }
  18729. // collect mandatory members
  18730. const std::string op = get_value("op", "op", true);
  18731. const std::string path = get_value(op, "path", true);
  18732. json_pointer ptr(path);
  18733. switch (get_op(op))
  18734. {
  18735. case patch_operations::add:
  18736. {
  18737. operation_add(ptr, get_value("add", "value", false));
  18738. break;
  18739. }
  18740. case patch_operations::remove:
  18741. {
  18742. operation_remove(ptr);
  18743. break;
  18744. }
  18745. case patch_operations::replace:
  18746. {
  18747. // the "path" location must exist - use at()
  18748. result.at(ptr) = get_value("replace", "value", false);
  18749. break;
  18750. }
  18751. case patch_operations::move:
  18752. {
  18753. const std::string from_path = get_value("move", "from", true);
  18754. json_pointer from_ptr(from_path);
  18755. // the "from" location must exist - use at()
  18756. basic_json v = result.at(from_ptr);
  18757. // The move operation is functionally identical to a
  18758. // "remove" operation on the "from" location, followed
  18759. // immediately by an "add" operation at the target
  18760. // location with the value that was just removed.
  18761. operation_remove(from_ptr);
  18762. operation_add(ptr, v);
  18763. break;
  18764. }
  18765. case patch_operations::copy:
  18766. {
  18767. const std::string from_path = get_value("copy", "from", true);
  18768. const json_pointer from_ptr(from_path);
  18769. // the "from" location must exist - use at()
  18770. basic_json v = result.at(from_ptr);
  18771. // The copy is functionally identical to an "add"
  18772. // operation at the target location using the value
  18773. // specified in the "from" member.
  18774. operation_add(ptr, v);
  18775. break;
  18776. }
  18777. case patch_operations::test:
  18778. {
  18779. bool success = false;
  18780. JSON_TRY
  18781. {
  18782. // check if "value" matches the one at "path"
  18783. // the "path" location must exist - use at()
  18784. success = (result.at(ptr) == get_value("test", "value", false));
  18785. }
  18786. JSON_INTERNAL_CATCH (out_of_range&)
  18787. {
  18788. // ignore out of range errors: success remains false
  18789. }
  18790. // throw an exception if test fails
  18791. if (JSON_HEDLEY_UNLIKELY(not success))
  18792. {
  18793. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  18794. }
  18795. break;
  18796. }
  18797. default:
  18798. {
  18799. // op must be "add", "remove", "replace", "move", "copy", or
  18800. // "test"
  18801. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  18802. }
  18803. }
  18804. }
  18805. return result;
  18806. }
  18807. /*!
  18808. @brief creates a diff as a JSON patch
  18809. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  18810. be changed into the value @a target by calling @ref patch function.
  18811. @invariant For two JSON values @a source and @a target, the following code
  18812. yields always `true`:
  18813. @code {.cpp}
  18814. source.patch(diff(source, target)) == target;
  18815. @endcode
  18816. @note Currently, only `remove`, `add`, and `replace` operations are
  18817. generated.
  18818. @param[in] source JSON value to compare from
  18819. @param[in] target JSON value to compare against
  18820. @param[in] path helper value to create JSON pointers
  18821. @return a JSON patch to convert the @a source to @a target
  18822. @complexity Linear in the lengths of @a source and @a target.
  18823. @liveexample{The following code shows how a JSON patch is created as a
  18824. diff for two JSON values.,diff}
  18825. @sa @ref patch -- apply a JSON patch
  18826. @sa @ref merge_patch -- apply a JSON Merge Patch
  18827. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  18828. @since version 2.0.0
  18829. */
  18830. JSON_HEDLEY_WARN_UNUSED_RESULT
  18831. static basic_json diff(const basic_json& source, const basic_json& target,
  18832. const std::string& path = "")
  18833. {
  18834. // the patch
  18835. basic_json result(value_t::array);
  18836. // if the values are the same, return empty patch
  18837. if (source == target)
  18838. {
  18839. return result;
  18840. }
  18841. if (source.type() != target.type())
  18842. {
  18843. // different types: replace value
  18844. result.push_back(
  18845. {
  18846. {"op", "replace"}, {"path", path}, {"value", target}
  18847. });
  18848. return result;
  18849. }
  18850. switch (source.type())
  18851. {
  18852. case value_t::array:
  18853. {
  18854. // first pass: traverse common elements
  18855. std::size_t i = 0;
  18856. while (i < source.size() and i < target.size())
  18857. {
  18858. // recursive call to compare array values at index i
  18859. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  18860. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18861. ++i;
  18862. }
  18863. // i now reached the end of at least one array
  18864. // in a second pass, traverse the remaining elements
  18865. // remove my remaining elements
  18866. const auto end_index = static_cast<difference_type>(result.size());
  18867. while (i < source.size())
  18868. {
  18869. // add operations in reverse order to avoid invalid
  18870. // indices
  18871. result.insert(result.begin() + end_index, object(
  18872. {
  18873. {"op", "remove"},
  18874. {"path", path + "/" + std::to_string(i)}
  18875. }));
  18876. ++i;
  18877. }
  18878. // add other remaining elements
  18879. while (i < target.size())
  18880. {
  18881. result.push_back(
  18882. {
  18883. {"op", "add"},
  18884. {"path", path + "/" + std::to_string(i)},
  18885. {"value", target[i]}
  18886. });
  18887. ++i;
  18888. }
  18889. break;
  18890. }
  18891. case value_t::object:
  18892. {
  18893. // first pass: traverse this object's elements
  18894. for (auto it = source.cbegin(); it != source.cend(); ++it)
  18895. {
  18896. // escape the key name to be used in a JSON patch
  18897. const auto key = json_pointer::escape(it.key());
  18898. if (target.find(it.key()) != target.end())
  18899. {
  18900. // recursive call to compare object values at key it
  18901. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  18902. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  18903. }
  18904. else
  18905. {
  18906. // found a key that is not in o -> remove it
  18907. result.push_back(object(
  18908. {
  18909. {"op", "remove"}, {"path", path + "/" + key}
  18910. }));
  18911. }
  18912. }
  18913. // second pass: traverse other object's elements
  18914. for (auto it = target.cbegin(); it != target.cend(); ++it)
  18915. {
  18916. if (source.find(it.key()) == source.end())
  18917. {
  18918. // found a key that is not in this -> add it
  18919. const auto key = json_pointer::escape(it.key());
  18920. result.push_back(
  18921. {
  18922. {"op", "add"}, {"path", path + "/" + key},
  18923. {"value", it.value()}
  18924. });
  18925. }
  18926. }
  18927. break;
  18928. }
  18929. default:
  18930. {
  18931. // both primitive type: replace value
  18932. result.push_back(
  18933. {
  18934. {"op", "replace"}, {"path", path}, {"value", target}
  18935. });
  18936. break;
  18937. }
  18938. }
  18939. return result;
  18940. }
  18941. /// @}
  18942. ////////////////////////////////
  18943. // JSON Merge Patch functions //
  18944. ////////////////////////////////
  18945. /// @name JSON Merge Patch functions
  18946. /// @{
  18947. /*!
  18948. @brief applies a JSON Merge Patch
  18949. The merge patch format is primarily intended for use with the HTTP PATCH
  18950. method as a means of describing a set of modifications to a target
  18951. resource's content. This function applies a merge patch to the current
  18952. JSON value.
  18953. The function implements the following algorithm from Section 2 of
  18954. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  18955. ```
  18956. define MergePatch(Target, Patch):
  18957. if Patch is an Object:
  18958. if Target is not an Object:
  18959. Target = {} // Ignore the contents and set it to an empty Object
  18960. for each Name/Value pair in Patch:
  18961. if Value is null:
  18962. if Name exists in Target:
  18963. remove the Name/Value pair from Target
  18964. else:
  18965. Target[Name] = MergePatch(Target[Name], Value)
  18966. return Target
  18967. else:
  18968. return Patch
  18969. ```
  18970. Thereby, `Target` is the current object; that is, the patch is applied to
  18971. the current value.
  18972. @param[in] apply_patch the patch to apply
  18973. @complexity Linear in the lengths of @a patch.
  18974. @liveexample{The following code shows how a JSON Merge Patch is applied to
  18975. a JSON document.,merge_patch}
  18976. @sa @ref patch -- apply a JSON patch
  18977. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  18978. @since version 3.0.0
  18979. */
  18980. void merge_patch(const basic_json& apply_patch)
  18981. {
  18982. if (apply_patch.is_object())
  18983. {
  18984. if (not is_object())
  18985. {
  18986. *this = object();
  18987. }
  18988. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  18989. {
  18990. if (it.value().is_null())
  18991. {
  18992. erase(it.key());
  18993. }
  18994. else
  18995. {
  18996. operator[](it.key()).merge_patch(it.value());
  18997. }
  18998. }
  18999. }
  19000. else
  19001. {
  19002. *this = apply_patch;
  19003. }
  19004. }
  19005. /// @}
  19006. };
  19007. /*!
  19008. @brief user-defined to_string function for JSON values
  19009. This function implements a user-defined to_string for JSON objects.
  19010. @param[in] j a JSON object
  19011. @return a std::string object
  19012. */
  19013. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19014. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  19015. {
  19016. return j.dump();
  19017. }
  19018. } // namespace nlohmann
  19019. ///////////////////////
  19020. // nonmember support //
  19021. ///////////////////////
  19022. // specialization of std::swap, and std::hash
  19023. namespace std
  19024. {
  19025. /// hash value for JSON objects
  19026. template<>
  19027. struct hash<nlohmann::json>
  19028. {
  19029. /*!
  19030. @brief return a hash value for a JSON object
  19031. @since version 1.0.0
  19032. */
  19033. std::size_t operator()(const nlohmann::json& j) const
  19034. {
  19035. // a naive hashing via the string representation
  19036. const auto& h = hash<nlohmann::json::string_t>();
  19037. return h(j.dump());
  19038. }
  19039. };
  19040. /// specialization for std::less<value_t>
  19041. /// @note: do not remove the space after '<',
  19042. /// see https://github.com/nlohmann/json/pull/679
  19043. template<>
  19044. struct less<::nlohmann::detail::value_t>
  19045. {
  19046. /*!
  19047. @brief compare two value_t enum values
  19048. @since version 3.0.0
  19049. */
  19050. bool operator()(nlohmann::detail::value_t lhs,
  19051. nlohmann::detail::value_t rhs) const noexcept
  19052. {
  19053. return nlohmann::detail::operator<(lhs, rhs);
  19054. }
  19055. };
  19056. /*!
  19057. @brief exchanges the values of two JSON objects
  19058. @since version 1.0.0
  19059. */
  19060. template<>
  19061. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  19062. is_nothrow_move_constructible<nlohmann::json>::value and
  19063. is_nothrow_move_assignable<nlohmann::json>::value
  19064. )
  19065. {
  19066. j1.swap(j2);
  19067. }
  19068. } // namespace std
  19069. /*!
  19070. @brief user-defined string literal for JSON values
  19071. This operator implements a user-defined string literal for JSON objects. It
  19072. can be used by adding `"_json"` to a string literal and returns a JSON object
  19073. if no parse error occurred.
  19074. @param[in] s a string representation of a JSON object
  19075. @param[in] n the length of string @a s
  19076. @return a JSON object
  19077. @since version 1.0.0
  19078. */
  19079. JSON_HEDLEY_NON_NULL(1)
  19080. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  19081. {
  19082. return nlohmann::json::parse(s, s + n);
  19083. }
  19084. /*!
  19085. @brief user-defined string literal for JSON pointer
  19086. This operator implements a user-defined string literal for JSON Pointers. It
  19087. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  19088. object if no parse error occurred.
  19089. @param[in] s a string representation of a JSON Pointer
  19090. @param[in] n the length of string @a s
  19091. @return a JSON pointer object
  19092. @since version 2.0.0
  19093. */
  19094. JSON_HEDLEY_NON_NULL(1)
  19095. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  19096. {
  19097. return nlohmann::json::json_pointer(std::string(s, n));
  19098. }
  19099. // #include <nlohmann/detail/macro_unscope.hpp>
  19100. // restore GCC/clang diagnostic settings
  19101. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  19102. #pragma GCC diagnostic pop
  19103. #endif
  19104. #if defined(__clang__)
  19105. #pragma GCC diagnostic pop
  19106. #endif
  19107. // clean up
  19108. #undef JSON_INTERNAL_CATCH
  19109. #undef JSON_CATCH
  19110. #undef JSON_THROW
  19111. #undef JSON_TRY
  19112. #undef JSON_HAS_CPP_14
  19113. #undef JSON_HAS_CPP_17
  19114. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  19115. #undef NLOHMANN_BASIC_JSON_TPL
  19116. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  19117. #undef JSON_HEDLEY_ALWAYS_INLINE
  19118. #undef JSON_HEDLEY_ARM_VERSION
  19119. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  19120. #undef JSON_HEDLEY_ARRAY_PARAM
  19121. #undef JSON_HEDLEY_ASSUME
  19122. #undef JSON_HEDLEY_BEGIN_C_DECLS
  19123. #undef JSON_HEDLEY_C_DECL
  19124. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  19125. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  19126. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  19127. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  19128. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  19129. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  19130. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  19131. #undef JSON_HEDLEY_COMPCERT_VERSION
  19132. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  19133. #undef JSON_HEDLEY_CONCAT
  19134. #undef JSON_HEDLEY_CONCAT_EX
  19135. #undef JSON_HEDLEY_CONST
  19136. #undef JSON_HEDLEY_CONST_CAST
  19137. #undef JSON_HEDLEY_CONSTEXPR
  19138. #undef JSON_HEDLEY_CPP_CAST
  19139. #undef JSON_HEDLEY_CRAY_VERSION
  19140. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  19141. #undef JSON_HEDLEY_DEPRECATED
  19142. #undef JSON_HEDLEY_DEPRECATED_FOR
  19143. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  19144. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  19145. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  19146. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  19147. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  19148. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  19149. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  19150. #undef JSON_HEDLEY_DMC_VERSION
  19151. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  19152. #undef JSON_HEDLEY_EMPTY_BASES
  19153. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  19154. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  19155. #undef JSON_HEDLEY_END_C_DECLS
  19156. #undef JSON_HEDLEY_FALL_THROUGH
  19157. #undef JSON_HEDLEY_FLAGS
  19158. #undef JSON_HEDLEY_FLAGS_CAST
  19159. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  19160. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  19161. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  19162. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  19163. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  19164. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  19165. #undef JSON_HEDLEY_GCC_HAS_WARNING
  19166. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  19167. #undef JSON_HEDLEY_GCC_VERSION
  19168. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  19169. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  19170. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  19171. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  19172. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  19173. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  19174. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  19175. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  19176. #undef JSON_HEDLEY_GNUC_VERSION
  19177. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  19178. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  19179. #undef JSON_HEDLEY_HAS_BUILTIN
  19180. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  19181. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  19182. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  19183. #undef JSON_HEDLEY_HAS_EXTENSION
  19184. #undef JSON_HEDLEY_HAS_FEATURE
  19185. #undef JSON_HEDLEY_HAS_WARNING
  19186. #undef JSON_HEDLEY_IAR_VERSION
  19187. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  19188. #undef JSON_HEDLEY_IBM_VERSION
  19189. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  19190. #undef JSON_HEDLEY_IMPORT
  19191. #undef JSON_HEDLEY_INLINE
  19192. #undef JSON_HEDLEY_INTEL_VERSION
  19193. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  19194. #undef JSON_HEDLEY_IS_CONSTANT
  19195. #undef JSON_HEDLEY_IS_CONSTEXPR_
  19196. #undef JSON_HEDLEY_LIKELY
  19197. #undef JSON_HEDLEY_MALLOC
  19198. #undef JSON_HEDLEY_MESSAGE
  19199. #undef JSON_HEDLEY_MSVC_VERSION
  19200. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  19201. #undef JSON_HEDLEY_NEVER_INLINE
  19202. #undef JSON_HEDLEY_NO_ESCAPE
  19203. #undef JSON_HEDLEY_NON_NULL
  19204. #undef JSON_HEDLEY_NO_RETURN
  19205. #undef JSON_HEDLEY_NO_THROW
  19206. #undef JSON_HEDLEY_NULL
  19207. #undef JSON_HEDLEY_PELLES_VERSION
  19208. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  19209. #undef JSON_HEDLEY_PGI_VERSION
  19210. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  19211. #undef JSON_HEDLEY_PREDICT
  19212. #undef JSON_HEDLEY_PRINTF_FORMAT
  19213. #undef JSON_HEDLEY_PRIVATE
  19214. #undef JSON_HEDLEY_PUBLIC
  19215. #undef JSON_HEDLEY_PURE
  19216. #undef JSON_HEDLEY_REINTERPRET_CAST
  19217. #undef JSON_HEDLEY_REQUIRE
  19218. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  19219. #undef JSON_HEDLEY_REQUIRE_MSG
  19220. #undef JSON_HEDLEY_RESTRICT
  19221. #undef JSON_HEDLEY_RETURNS_NON_NULL
  19222. #undef JSON_HEDLEY_SENTINEL
  19223. #undef JSON_HEDLEY_STATIC_ASSERT
  19224. #undef JSON_HEDLEY_STATIC_CAST
  19225. #undef JSON_HEDLEY_STRINGIFY
  19226. #undef JSON_HEDLEY_STRINGIFY_EX
  19227. #undef JSON_HEDLEY_SUNPRO_VERSION
  19228. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  19229. #undef JSON_HEDLEY_TINYC_VERSION
  19230. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  19231. #undef JSON_HEDLEY_TI_VERSION
  19232. #undef JSON_HEDLEY_TI_VERSION_CHECK
  19233. #undef JSON_HEDLEY_UNAVAILABLE
  19234. #undef JSON_HEDLEY_UNLIKELY
  19235. #undef JSON_HEDLEY_UNPREDICTABLE
  19236. #undef JSON_HEDLEY_UNREACHABLE
  19237. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  19238. #undef JSON_HEDLEY_VERSION
  19239. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  19240. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  19241. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  19242. #undef JSON_HEDLEY_VERSION_ENCODE
  19243. #undef JSON_HEDLEY_WARNING
  19244. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  19245. #endif // INCLUDE_NLOHMANN_JSON_HPP_