1
0

json.hpp 867 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.8.0
  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 8
  29. #define NLOHMANN_JSON_VERSION_PATCH 0
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  32. #include <functional> // hash, less
  33. #include <initializer_list> // initializer_list
  34. #include <iosfwd> // istream, ostream
  35. #include <iterator> // random_access_iterator_tag
  36. #include <memory> // unique_ptr
  37. #include <numeric> // accumulate
  38. #include <string> // string, stoi, to_string
  39. #include <utility> // declval, forward, move, pair, swap
  40. #include <vector> // vector
  41. // #include <nlohmann/adl_serializer.hpp>
  42. #include <utility>
  43. // #include <nlohmann/detail/conversions/from_json.hpp>
  44. #include <algorithm> // transform
  45. #include <array> // array
  46. #include <forward_list> // forward_list
  47. #include <iterator> // inserter, front_inserter, end
  48. #include <map> // map
  49. #include <string> // string
  50. #include <tuple> // tuple, make_tuple
  51. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  52. #include <unordered_map> // unordered_map
  53. #include <utility> // pair, declval
  54. #include <valarray> // valarray
  55. // #include <nlohmann/detail/exceptions.hpp>
  56. #include <exception> // exception
  57. #include <stdexcept> // runtime_error
  58. #include <string> // to_string
  59. // #include <nlohmann/detail/input/position_t.hpp>
  60. #include <cstddef> // size_t
  61. namespace nlohmann
  62. {
  63. namespace detail
  64. {
  65. /// struct to capture the start position of the current token
  66. struct position_t
  67. {
  68. /// the total number of characters read
  69. std::size_t chars_read_total = 0;
  70. /// the number of characters read in the current line
  71. std::size_t chars_read_current_line = 0;
  72. /// the number of lines read
  73. std::size_t lines_read = 0;
  74. /// conversion to size_t to preserve SAX interface
  75. constexpr operator size_t() const
  76. {
  77. return chars_read_total;
  78. }
  79. };
  80. } // namespace detail
  81. } // namespace nlohmann
  82. // #include <nlohmann/detail/macro_scope.hpp>
  83. #include <utility> // pair
  84. // #include <nlohmann/thirdparty/hedley/hedley.hpp>
  85. /* Hedley - https://nemequ.github.io/hedley
  86. * Created by Evan Nemerson <evan@nemerson.com>
  87. *
  88. * To the extent possible under law, the author(s) have dedicated all
  89. * copyright and related and neighboring rights to this software to
  90. * the public domain worldwide. This software is distributed without
  91. * any warranty.
  92. *
  93. * For details, see <http://creativecommons.org/publicdomain/zero/1.0/>.
  94. * SPDX-License-Identifier: CC0-1.0
  95. */
  96. #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 13)
  97. #if defined(JSON_HEDLEY_VERSION)
  98. #undef JSON_HEDLEY_VERSION
  99. #endif
  100. #define JSON_HEDLEY_VERSION 13
  101. #if defined(JSON_HEDLEY_STRINGIFY_EX)
  102. #undef JSON_HEDLEY_STRINGIFY_EX
  103. #endif
  104. #define JSON_HEDLEY_STRINGIFY_EX(x) #x
  105. #if defined(JSON_HEDLEY_STRINGIFY)
  106. #undef JSON_HEDLEY_STRINGIFY
  107. #endif
  108. #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x)
  109. #if defined(JSON_HEDLEY_CONCAT_EX)
  110. #undef JSON_HEDLEY_CONCAT_EX
  111. #endif
  112. #define JSON_HEDLEY_CONCAT_EX(a,b) a##b
  113. #if defined(JSON_HEDLEY_CONCAT)
  114. #undef JSON_HEDLEY_CONCAT
  115. #endif
  116. #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b)
  117. #if defined(JSON_HEDLEY_CONCAT3_EX)
  118. #undef JSON_HEDLEY_CONCAT3_EX
  119. #endif
  120. #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c
  121. #if defined(JSON_HEDLEY_CONCAT3)
  122. #undef JSON_HEDLEY_CONCAT3
  123. #endif
  124. #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c)
  125. #if defined(JSON_HEDLEY_VERSION_ENCODE)
  126. #undef JSON_HEDLEY_VERSION_ENCODE
  127. #endif
  128. #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision))
  129. #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR)
  130. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  131. #endif
  132. #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000)
  133. #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR)
  134. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  135. #endif
  136. #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000)
  137. #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION)
  138. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  139. #endif
  140. #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000)
  141. #if defined(JSON_HEDLEY_GNUC_VERSION)
  142. #undef JSON_HEDLEY_GNUC_VERSION
  143. #endif
  144. #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__)
  145. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
  146. #elif defined(__GNUC__)
  147. #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0)
  148. #endif
  149. #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK)
  150. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  151. #endif
  152. #if defined(JSON_HEDLEY_GNUC_VERSION)
  153. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  154. #else
  155. #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0)
  156. #endif
  157. #if defined(JSON_HEDLEY_MSVC_VERSION)
  158. #undef JSON_HEDLEY_MSVC_VERSION
  159. #endif
  160. #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000)
  161. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100)
  162. #elif defined(_MSC_FULL_VER)
  163. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10)
  164. #elif defined(_MSC_VER)
  165. #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0)
  166. #endif
  167. #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK)
  168. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  169. #endif
  170. #if !defined(_MSC_VER)
  171. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0)
  172. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  173. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch)))
  174. #elif defined(_MSC_VER) && (_MSC_VER >= 1200)
  175. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch)))
  176. #else
  177. #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor)))
  178. #endif
  179. #if defined(JSON_HEDLEY_INTEL_VERSION)
  180. #undef JSON_HEDLEY_INTEL_VERSION
  181. #endif
  182. #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE)
  183. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE)
  184. #elif defined(__INTEL_COMPILER)
  185. #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0)
  186. #endif
  187. #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK)
  188. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  189. #endif
  190. #if defined(JSON_HEDLEY_INTEL_VERSION)
  191. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  192. #else
  193. #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0)
  194. #endif
  195. #if defined(JSON_HEDLEY_PGI_VERSION)
  196. #undef JSON_HEDLEY_PGI_VERSION
  197. #endif
  198. #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__)
  199. #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__)
  200. #endif
  201. #if defined(JSON_HEDLEY_PGI_VERSION_CHECK)
  202. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  203. #endif
  204. #if defined(JSON_HEDLEY_PGI_VERSION)
  205. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  206. #else
  207. #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0)
  208. #endif
  209. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  210. #undef JSON_HEDLEY_SUNPRO_VERSION
  211. #endif
  212. #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000)
  213. #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)
  214. #elif defined(__SUNPRO_C)
  215. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf)
  216. #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000)
  217. #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)
  218. #elif defined(__SUNPRO_CC)
  219. #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf)
  220. #endif
  221. #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK)
  222. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  223. #endif
  224. #if defined(JSON_HEDLEY_SUNPRO_VERSION)
  225. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  226. #else
  227. #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0)
  228. #endif
  229. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  230. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  231. #endif
  232. #if defined(__EMSCRIPTEN__)
  233. #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__)
  234. #endif
  235. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK)
  236. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  237. #endif
  238. #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION)
  239. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  240. #else
  241. #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0)
  242. #endif
  243. #if defined(JSON_HEDLEY_ARM_VERSION)
  244. #undef JSON_HEDLEY_ARM_VERSION
  245. #endif
  246. #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION)
  247. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100)
  248. #elif defined(__CC_ARM) && defined(__ARMCC_VERSION)
  249. #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100)
  250. #endif
  251. #if defined(JSON_HEDLEY_ARM_VERSION_CHECK)
  252. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  253. #endif
  254. #if defined(JSON_HEDLEY_ARM_VERSION)
  255. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  256. #else
  257. #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0)
  258. #endif
  259. #if defined(JSON_HEDLEY_IBM_VERSION)
  260. #undef JSON_HEDLEY_IBM_VERSION
  261. #endif
  262. #if defined(__ibmxl__)
  263. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__)
  264. #elif defined(__xlC__) && defined(__xlC_ver__)
  265. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff)
  266. #elif defined(__xlC__)
  267. #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0)
  268. #endif
  269. #if defined(JSON_HEDLEY_IBM_VERSION_CHECK)
  270. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  271. #endif
  272. #if defined(JSON_HEDLEY_IBM_VERSION)
  273. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  274. #else
  275. #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0)
  276. #endif
  277. #if defined(JSON_HEDLEY_TI_VERSION)
  278. #undef JSON_HEDLEY_TI_VERSION
  279. #endif
  280. #if \
  281. defined(__TI_COMPILER_VERSION__) && \
  282. ( \
  283. defined(__TMS470__) || defined(__TI_ARM__) || \
  284. defined(__MSP430__) || \
  285. defined(__TMS320C2000__) \
  286. )
  287. #if (__TI_COMPILER_VERSION__ >= 16000000)
  288. #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  289. #endif
  290. #endif
  291. #if defined(JSON_HEDLEY_TI_VERSION_CHECK)
  292. #undef JSON_HEDLEY_TI_VERSION_CHECK
  293. #endif
  294. #if defined(JSON_HEDLEY_TI_VERSION)
  295. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  296. #else
  297. #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0)
  298. #endif
  299. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  300. #undef JSON_HEDLEY_TI_CL2000_VERSION
  301. #endif
  302. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__)
  303. #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  304. #endif
  305. #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK)
  306. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  307. #endif
  308. #if defined(JSON_HEDLEY_TI_CL2000_VERSION)
  309. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  310. #else
  311. #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0)
  312. #endif
  313. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  314. #undef JSON_HEDLEY_TI_CL430_VERSION
  315. #endif
  316. #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__)
  317. #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  318. #endif
  319. #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK)
  320. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  321. #endif
  322. #if defined(JSON_HEDLEY_TI_CL430_VERSION)
  323. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  324. #else
  325. #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0)
  326. #endif
  327. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  328. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  329. #endif
  330. #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__))
  331. #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  332. #endif
  333. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK)
  334. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  335. #endif
  336. #if defined(JSON_HEDLEY_TI_ARMCL_VERSION)
  337. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  338. #else
  339. #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0)
  340. #endif
  341. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  342. #undef JSON_HEDLEY_TI_CL6X_VERSION
  343. #endif
  344. #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__)
  345. #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  346. #endif
  347. #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK)
  348. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  349. #endif
  350. #if defined(JSON_HEDLEY_TI_CL6X_VERSION)
  351. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  352. #else
  353. #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0)
  354. #endif
  355. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  356. #undef JSON_HEDLEY_TI_CL7X_VERSION
  357. #endif
  358. #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__)
  359. #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  360. #endif
  361. #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK)
  362. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  363. #endif
  364. #if defined(JSON_HEDLEY_TI_CL7X_VERSION)
  365. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  366. #else
  367. #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0)
  368. #endif
  369. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  370. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  371. #endif
  372. #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__)
  373. #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000))
  374. #endif
  375. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK)
  376. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  377. #endif
  378. #if defined(JSON_HEDLEY_TI_CLPRU_VERSION)
  379. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  380. #else
  381. #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0)
  382. #endif
  383. #if defined(JSON_HEDLEY_CRAY_VERSION)
  384. #undef JSON_HEDLEY_CRAY_VERSION
  385. #endif
  386. #if defined(_CRAYC)
  387. #if defined(_RELEASE_PATCHLEVEL)
  388. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL)
  389. #else
  390. #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0)
  391. #endif
  392. #endif
  393. #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK)
  394. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  395. #endif
  396. #if defined(JSON_HEDLEY_CRAY_VERSION)
  397. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  398. #else
  399. #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0)
  400. #endif
  401. #if defined(JSON_HEDLEY_IAR_VERSION)
  402. #undef JSON_HEDLEY_IAR_VERSION
  403. #endif
  404. #if defined(__IAR_SYSTEMS_ICC__)
  405. #if __VER__ > 1000
  406. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000))
  407. #else
  408. #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0)
  409. #endif
  410. #endif
  411. #if defined(JSON_HEDLEY_IAR_VERSION_CHECK)
  412. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  413. #endif
  414. #if defined(JSON_HEDLEY_IAR_VERSION)
  415. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  416. #else
  417. #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0)
  418. #endif
  419. #if defined(JSON_HEDLEY_TINYC_VERSION)
  420. #undef JSON_HEDLEY_TINYC_VERSION
  421. #endif
  422. #if defined(__TINYC__)
  423. #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100)
  424. #endif
  425. #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK)
  426. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  427. #endif
  428. #if defined(JSON_HEDLEY_TINYC_VERSION)
  429. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  430. #else
  431. #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0)
  432. #endif
  433. #if defined(JSON_HEDLEY_DMC_VERSION)
  434. #undef JSON_HEDLEY_DMC_VERSION
  435. #endif
  436. #if defined(__DMC__)
  437. #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf)
  438. #endif
  439. #if defined(JSON_HEDLEY_DMC_VERSION_CHECK)
  440. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  441. #endif
  442. #if defined(JSON_HEDLEY_DMC_VERSION)
  443. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  444. #else
  445. #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0)
  446. #endif
  447. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  448. #undef JSON_HEDLEY_COMPCERT_VERSION
  449. #endif
  450. #if defined(__COMPCERT_VERSION__)
  451. #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100)
  452. #endif
  453. #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK)
  454. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  455. #endif
  456. #if defined(JSON_HEDLEY_COMPCERT_VERSION)
  457. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  458. #else
  459. #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0)
  460. #endif
  461. #if defined(JSON_HEDLEY_PELLES_VERSION)
  462. #undef JSON_HEDLEY_PELLES_VERSION
  463. #endif
  464. #if defined(__POCC__)
  465. #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0)
  466. #endif
  467. #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK)
  468. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  469. #endif
  470. #if defined(JSON_HEDLEY_PELLES_VERSION)
  471. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  472. #else
  473. #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0)
  474. #endif
  475. #if defined(JSON_HEDLEY_GCC_VERSION)
  476. #undef JSON_HEDLEY_GCC_VERSION
  477. #endif
  478. #if \
  479. defined(JSON_HEDLEY_GNUC_VERSION) && \
  480. !defined(__clang__) && \
  481. !defined(JSON_HEDLEY_INTEL_VERSION) && \
  482. !defined(JSON_HEDLEY_PGI_VERSION) && \
  483. !defined(JSON_HEDLEY_ARM_VERSION) && \
  484. !defined(JSON_HEDLEY_TI_VERSION) && \
  485. !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \
  486. !defined(JSON_HEDLEY_TI_CL430_VERSION) && \
  487. !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \
  488. !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \
  489. !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \
  490. !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \
  491. !defined(__COMPCERT__)
  492. #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION
  493. #endif
  494. #if defined(JSON_HEDLEY_GCC_VERSION_CHECK)
  495. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  496. #endif
  497. #if defined(JSON_HEDLEY_GCC_VERSION)
  498. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch))
  499. #else
  500. #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0)
  501. #endif
  502. #if defined(JSON_HEDLEY_HAS_ATTRIBUTE)
  503. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  504. #endif
  505. #if defined(__has_attribute)
  506. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute)
  507. #else
  508. #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0)
  509. #endif
  510. #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE)
  511. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  512. #endif
  513. #if defined(__has_attribute)
  514. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  515. #else
  516. #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  517. #endif
  518. #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE)
  519. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  520. #endif
  521. #if defined(__has_attribute)
  522. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute)
  523. #else
  524. #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  525. #endif
  526. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE)
  527. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  528. #endif
  529. #if \
  530. defined(__has_cpp_attribute) && \
  531. defined(__cplusplus) && \
  532. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0))
  533. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute)
  534. #else
  535. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0)
  536. #endif
  537. #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS)
  538. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  539. #endif
  540. #if !defined(__cplusplus) || !defined(__has_cpp_attribute)
  541. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  542. #elif \
  543. !defined(JSON_HEDLEY_PGI_VERSION) && \
  544. !defined(JSON_HEDLEY_IAR_VERSION) && \
  545. (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \
  546. (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0))
  547. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute)
  548. #else
  549. #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0)
  550. #endif
  551. #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE)
  552. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  553. #endif
  554. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  555. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  556. #else
  557. #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  558. #endif
  559. #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE)
  560. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  561. #endif
  562. #if defined(__has_cpp_attribute) && defined(__cplusplus)
  563. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute)
  564. #else
  565. #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  566. #endif
  567. #if defined(JSON_HEDLEY_HAS_BUILTIN)
  568. #undef JSON_HEDLEY_HAS_BUILTIN
  569. #endif
  570. #if defined(__has_builtin)
  571. #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin)
  572. #else
  573. #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0)
  574. #endif
  575. #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN)
  576. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  577. #endif
  578. #if defined(__has_builtin)
  579. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  580. #else
  581. #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  582. #endif
  583. #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN)
  584. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  585. #endif
  586. #if defined(__has_builtin)
  587. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin)
  588. #else
  589. #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  590. #endif
  591. #if defined(JSON_HEDLEY_HAS_FEATURE)
  592. #undef JSON_HEDLEY_HAS_FEATURE
  593. #endif
  594. #if defined(__has_feature)
  595. #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature)
  596. #else
  597. #define JSON_HEDLEY_HAS_FEATURE(feature) (0)
  598. #endif
  599. #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE)
  600. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  601. #endif
  602. #if defined(__has_feature)
  603. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  604. #else
  605. #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  606. #endif
  607. #if defined(JSON_HEDLEY_GCC_HAS_FEATURE)
  608. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  609. #endif
  610. #if defined(__has_feature)
  611. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature)
  612. #else
  613. #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  614. #endif
  615. #if defined(JSON_HEDLEY_HAS_EXTENSION)
  616. #undef JSON_HEDLEY_HAS_EXTENSION
  617. #endif
  618. #if defined(__has_extension)
  619. #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension)
  620. #else
  621. #define JSON_HEDLEY_HAS_EXTENSION(extension) (0)
  622. #endif
  623. #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION)
  624. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  625. #endif
  626. #if defined(__has_extension)
  627. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  628. #else
  629. #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  630. #endif
  631. #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION)
  632. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  633. #endif
  634. #if defined(__has_extension)
  635. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension)
  636. #else
  637. #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  638. #endif
  639. #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE)
  640. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  641. #endif
  642. #if defined(__has_declspec_attribute)
  643. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute)
  644. #else
  645. #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0)
  646. #endif
  647. #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE)
  648. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  649. #endif
  650. #if defined(__has_declspec_attribute)
  651. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  652. #else
  653. #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  654. #endif
  655. #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE)
  656. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  657. #endif
  658. #if defined(__has_declspec_attribute)
  659. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute)
  660. #else
  661. #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  662. #endif
  663. #if defined(JSON_HEDLEY_HAS_WARNING)
  664. #undef JSON_HEDLEY_HAS_WARNING
  665. #endif
  666. #if defined(__has_warning)
  667. #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning)
  668. #else
  669. #define JSON_HEDLEY_HAS_WARNING(warning) (0)
  670. #endif
  671. #if defined(JSON_HEDLEY_GNUC_HAS_WARNING)
  672. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  673. #endif
  674. #if defined(__has_warning)
  675. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  676. #else
  677. #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch)
  678. #endif
  679. #if defined(JSON_HEDLEY_GCC_HAS_WARNING)
  680. #undef JSON_HEDLEY_GCC_HAS_WARNING
  681. #endif
  682. #if defined(__has_warning)
  683. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning)
  684. #else
  685. #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  686. #endif
  687. /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for
  688. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  689. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  690. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  691. #endif
  692. #if defined(__cplusplus)
  693. # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat")
  694. # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions")
  695. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  696. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  697. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  698. _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \
  699. xpr \
  700. JSON_HEDLEY_DIAGNOSTIC_POP
  701. # else
  702. # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \
  703. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  704. _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \
  705. xpr \
  706. JSON_HEDLEY_DIAGNOSTIC_POP
  707. # endif
  708. # endif
  709. #endif
  710. #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_)
  711. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x
  712. #endif
  713. #if defined(JSON_HEDLEY_CONST_CAST)
  714. #undef JSON_HEDLEY_CONST_CAST
  715. #endif
  716. #if defined(__cplusplus)
  717. # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast<T>(expr))
  718. #elif \
  719. JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \
  720. JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \
  721. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  722. # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \
  723. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  724. JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \
  725. ((T) (expr)); \
  726. JSON_HEDLEY_DIAGNOSTIC_POP \
  727. }))
  728. #else
  729. # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr))
  730. #endif
  731. #if defined(JSON_HEDLEY_REINTERPRET_CAST)
  732. #undef JSON_HEDLEY_REINTERPRET_CAST
  733. #endif
  734. #if defined(__cplusplus)
  735. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast<T>(expr))
  736. #else
  737. #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr))
  738. #endif
  739. #if defined(JSON_HEDLEY_STATIC_CAST)
  740. #undef JSON_HEDLEY_STATIC_CAST
  741. #endif
  742. #if defined(__cplusplus)
  743. #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast<T>(expr))
  744. #else
  745. #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr))
  746. #endif
  747. #if defined(JSON_HEDLEY_CPP_CAST)
  748. #undef JSON_HEDLEY_CPP_CAST
  749. #endif
  750. #if defined(__cplusplus)
  751. # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast")
  752. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  753. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  754. _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \
  755. ((T) (expr)) \
  756. JSON_HEDLEY_DIAGNOSTIC_POP
  757. # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0)
  758. # define JSON_HEDLEY_CPP_CAST(T, expr) \
  759. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  760. _Pragma("diag_suppress=Pe137") \
  761. JSON_HEDLEY_DIAGNOSTIC_POP \
  762. # else
  763. # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr))
  764. # endif
  765. #else
  766. # define JSON_HEDLEY_CPP_CAST(T, expr) (expr)
  767. #endif
  768. #if \
  769. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  770. defined(__clang__) || \
  771. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  772. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  773. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  774. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  775. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  776. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  777. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  778. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  779. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  780. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \
  781. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  782. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  783. JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \
  784. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \
  785. JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \
  786. (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR))
  787. #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value)
  788. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  789. #define JSON_HEDLEY_PRAGMA(value) __pragma(value)
  790. #else
  791. #define JSON_HEDLEY_PRAGMA(value)
  792. #endif
  793. #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH)
  794. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  795. #endif
  796. #if defined(JSON_HEDLEY_DIAGNOSTIC_POP)
  797. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  798. #endif
  799. #if defined(__clang__)
  800. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push")
  801. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop")
  802. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  803. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  804. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  805. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  806. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push")
  807. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop")
  808. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  809. #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push))
  810. #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop))
  811. #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0)
  812. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push")
  813. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop")
  814. #elif \
  815. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  816. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  817. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \
  818. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  819. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  820. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  821. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push")
  822. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop")
  823. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  824. #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)")
  825. #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)")
  826. #else
  827. #define JSON_HEDLEY_DIAGNOSTIC_PUSH
  828. #define JSON_HEDLEY_DIAGNOSTIC_POP
  829. #endif
  830. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED)
  831. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  832. #endif
  833. #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations")
  834. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"")
  835. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  836. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)")
  837. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  838. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444")
  839. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  840. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  841. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  842. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996))
  843. #elif \
  844. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  845. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  846. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  847. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  848. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  849. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  850. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  851. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  852. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  853. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  854. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  855. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718")
  856. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus)
  857. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)")
  858. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus)
  859. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)")
  860. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  861. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215")
  862. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0)
  863. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)")
  864. #else
  865. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  866. #endif
  867. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS)
  868. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  869. #endif
  870. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  871. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"")
  872. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  873. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)")
  874. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  875. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675")
  876. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0)
  877. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"")
  878. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  879. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068))
  880. #elif \
  881. JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \
  882. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  883. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  884. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  885. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  886. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0)
  887. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163")
  888. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  889. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161")
  890. #else
  891. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  892. #endif
  893. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES)
  894. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  895. #endif
  896. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes")
  897. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"")
  898. #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0)
  899. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
  900. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0)
  901. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)")
  902. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0)
  903. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030))
  904. #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  905. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097")
  906. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)
  907. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)")
  908. #elif \
  909. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  910. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  911. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0)
  912. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173")
  913. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  914. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097")
  915. #else
  916. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  917. #endif
  918. #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL)
  919. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  920. #endif
  921. #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual")
  922. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"")
  923. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  924. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)")
  925. #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0)
  926. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"")
  927. #else
  928. #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  929. #endif
  930. #if defined(JSON_HEDLEY_DEPRECATED)
  931. #undef JSON_HEDLEY_DEPRECATED
  932. #endif
  933. #if defined(JSON_HEDLEY_DEPRECATED_FOR)
  934. #undef JSON_HEDLEY_DEPRECATED_FOR
  935. #endif
  936. #if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0)
  937. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since))
  938. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement))
  939. #elif defined(__cplusplus) && (__cplusplus >= 201402L)
  940. #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]])
  941. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]])
  942. #elif \
  943. JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \
  944. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  945. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  946. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  947. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \
  948. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  949. JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \
  950. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \
  951. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \
  952. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  953. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0)
  954. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since)))
  955. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement)))
  956. #elif \
  957. JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \
  958. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  959. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  960. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  961. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  962. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  963. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  964. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  965. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  966. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  967. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  968. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  969. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  970. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  971. #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__))
  972. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__))
  973. #elif \
  974. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  975. JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0)
  976. #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated)
  977. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated)
  978. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  979. #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated")
  980. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated")
  981. #else
  982. #define JSON_HEDLEY_DEPRECATED(since)
  983. #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement)
  984. #endif
  985. #if defined(JSON_HEDLEY_UNAVAILABLE)
  986. #undef JSON_HEDLEY_UNAVAILABLE
  987. #endif
  988. #if \
  989. JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \
  990. JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \
  991. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  992. #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since)))
  993. #else
  994. #define JSON_HEDLEY_UNAVAILABLE(available_since)
  995. #endif
  996. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT)
  997. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  998. #endif
  999. #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG)
  1000. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  1001. #endif
  1002. #if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L)
  1003. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1004. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]])
  1005. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard)
  1006. #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1007. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]])
  1008. #elif \
  1009. JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \
  1010. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1011. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1012. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1013. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1014. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1015. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1016. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1017. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1018. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1019. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1020. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1021. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1022. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1023. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1024. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1025. #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
  1026. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__))
  1027. #elif defined(_Check_return_) /* SAL */
  1028. #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_
  1029. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_
  1030. #else
  1031. #define JSON_HEDLEY_WARN_UNUSED_RESULT
  1032. #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg)
  1033. #endif
  1034. #if defined(JSON_HEDLEY_SENTINEL)
  1035. #undef JSON_HEDLEY_SENTINEL
  1036. #endif
  1037. #if \
  1038. JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \
  1039. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1040. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1041. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0)
  1042. #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position)))
  1043. #else
  1044. #define JSON_HEDLEY_SENTINEL(position)
  1045. #endif
  1046. #if defined(JSON_HEDLEY_NO_RETURN)
  1047. #undef JSON_HEDLEY_NO_RETURN
  1048. #endif
  1049. #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1050. #define JSON_HEDLEY_NO_RETURN __noreturn
  1051. #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1052. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1053. #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
  1054. #define JSON_HEDLEY_NO_RETURN _Noreturn
  1055. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  1056. #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]])
  1057. #elif \
  1058. JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \
  1059. JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \
  1060. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1061. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1062. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1063. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1064. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1065. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1066. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1067. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1068. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1069. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1070. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1071. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1072. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1073. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1074. #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__))
  1075. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1076. #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return")
  1077. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1078. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1079. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1080. #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;")
  1081. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1082. #define JSON_HEDLEY_NO_RETURN __attribute((noreturn))
  1083. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1084. #define JSON_HEDLEY_NO_RETURN __declspec(noreturn)
  1085. #else
  1086. #define JSON_HEDLEY_NO_RETURN
  1087. #endif
  1088. #if defined(JSON_HEDLEY_NO_ESCAPE)
  1089. #undef JSON_HEDLEY_NO_ESCAPE
  1090. #endif
  1091. #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape)
  1092. #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__))
  1093. #else
  1094. #define JSON_HEDLEY_NO_ESCAPE
  1095. #endif
  1096. #if defined(JSON_HEDLEY_UNREACHABLE)
  1097. #undef JSON_HEDLEY_UNREACHABLE
  1098. #endif
  1099. #if defined(JSON_HEDLEY_UNREACHABLE_RETURN)
  1100. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  1101. #endif
  1102. #if defined(JSON_HEDLEY_ASSUME)
  1103. #undef JSON_HEDLEY_ASSUME
  1104. #endif
  1105. #if \
  1106. JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \
  1107. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1108. #define JSON_HEDLEY_ASSUME(expr) __assume(expr)
  1109. #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume)
  1110. #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr)
  1111. #elif \
  1112. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1113. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1114. #if defined(__cplusplus)
  1115. #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr)
  1116. #else
  1117. #define JSON_HEDLEY_ASSUME(expr) _nassert(expr)
  1118. #endif
  1119. #endif
  1120. #if \
  1121. (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \
  1122. JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \
  1123. JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \
  1124. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1125. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5)
  1126. #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable()
  1127. #elif defined(JSON_HEDLEY_ASSUME)
  1128. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1129. #endif
  1130. #if !defined(JSON_HEDLEY_ASSUME)
  1131. #if defined(JSON_HEDLEY_UNREACHABLE)
  1132. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1)))
  1133. #else
  1134. #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr)
  1135. #endif
  1136. #endif
  1137. #if defined(JSON_HEDLEY_UNREACHABLE)
  1138. #if \
  1139. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1140. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0)
  1141. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value))
  1142. #else
  1143. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE()
  1144. #endif
  1145. #else
  1146. #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value)
  1147. #endif
  1148. #if !defined(JSON_HEDLEY_UNREACHABLE)
  1149. #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0)
  1150. #endif
  1151. JSON_HEDLEY_DIAGNOSTIC_PUSH
  1152. #if JSON_HEDLEY_HAS_WARNING("-Wpedantic")
  1153. #pragma clang diagnostic ignored "-Wpedantic"
  1154. #endif
  1155. #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus)
  1156. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1157. #endif
  1158. #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0)
  1159. #if defined(__clang__)
  1160. #pragma clang diagnostic ignored "-Wvariadic-macros"
  1161. #elif defined(JSON_HEDLEY_GCC_VERSION)
  1162. #pragma GCC diagnostic ignored "-Wvariadic-macros"
  1163. #endif
  1164. #endif
  1165. #if defined(JSON_HEDLEY_NON_NULL)
  1166. #undef JSON_HEDLEY_NON_NULL
  1167. #endif
  1168. #if \
  1169. JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \
  1170. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1171. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1172. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1173. #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__)))
  1174. #else
  1175. #define JSON_HEDLEY_NON_NULL(...)
  1176. #endif
  1177. JSON_HEDLEY_DIAGNOSTIC_POP
  1178. #if defined(JSON_HEDLEY_PRINTF_FORMAT)
  1179. #undef JSON_HEDLEY_PRINTF_FORMAT
  1180. #endif
  1181. #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO)
  1182. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check)))
  1183. #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO)
  1184. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check)))
  1185. #elif \
  1186. JSON_HEDLEY_HAS_ATTRIBUTE(format) || \
  1187. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1188. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1189. JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \
  1190. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1191. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1192. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1193. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1194. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1195. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1196. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1197. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1198. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1199. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1200. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1201. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1202. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check)))
  1203. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0)
  1204. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check))
  1205. #else
  1206. #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check)
  1207. #endif
  1208. #if defined(JSON_HEDLEY_CONSTEXPR)
  1209. #undef JSON_HEDLEY_CONSTEXPR
  1210. #endif
  1211. #if defined(__cplusplus)
  1212. #if __cplusplus >= 201103L
  1213. #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr)
  1214. #endif
  1215. #endif
  1216. #if !defined(JSON_HEDLEY_CONSTEXPR)
  1217. #define JSON_HEDLEY_CONSTEXPR
  1218. #endif
  1219. #if defined(JSON_HEDLEY_PREDICT)
  1220. #undef JSON_HEDLEY_PREDICT
  1221. #endif
  1222. #if defined(JSON_HEDLEY_LIKELY)
  1223. #undef JSON_HEDLEY_LIKELY
  1224. #endif
  1225. #if defined(JSON_HEDLEY_UNLIKELY)
  1226. #undef JSON_HEDLEY_UNLIKELY
  1227. #endif
  1228. #if defined(JSON_HEDLEY_UNPREDICTABLE)
  1229. #undef JSON_HEDLEY_UNPREDICTABLE
  1230. #endif
  1231. #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable)
  1232. #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr))
  1233. #endif
  1234. #if \
  1235. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \
  1236. JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0)
  1237. # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability))
  1238. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability))
  1239. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability))
  1240. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 )
  1241. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 )
  1242. #elif \
  1243. JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \
  1244. JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \
  1245. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1246. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \
  1247. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1248. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1249. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1250. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \
  1251. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1252. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \
  1253. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1254. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1255. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1256. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \
  1257. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1258. # define JSON_HEDLEY_PREDICT(expr, expected, probability) \
  1259. (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)))
  1260. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \
  1261. (__extension__ ({ \
  1262. double hedley_probability_ = (probability); \
  1263. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \
  1264. }))
  1265. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \
  1266. (__extension__ ({ \
  1267. double hedley_probability_ = (probability); \
  1268. ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \
  1269. }))
  1270. # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1)
  1271. # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0)
  1272. #else
  1273. # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))
  1274. # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr))
  1275. # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr))
  1276. # define JSON_HEDLEY_LIKELY(expr) (!!(expr))
  1277. # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr))
  1278. #endif
  1279. #if !defined(JSON_HEDLEY_UNPREDICTABLE)
  1280. #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5)
  1281. #endif
  1282. #if defined(JSON_HEDLEY_MALLOC)
  1283. #undef JSON_HEDLEY_MALLOC
  1284. #endif
  1285. #if \
  1286. JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \
  1287. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1288. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1289. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1290. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1291. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1292. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1293. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1294. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1295. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1296. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1297. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1298. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1299. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1300. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1301. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1302. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1303. #define JSON_HEDLEY_MALLOC __attribute__((__malloc__))
  1304. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1305. #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory")
  1306. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0)
  1307. #define JSON_HEDLEY_MALLOC __declspec(restrict)
  1308. #else
  1309. #define JSON_HEDLEY_MALLOC
  1310. #endif
  1311. #if defined(JSON_HEDLEY_PURE)
  1312. #undef JSON_HEDLEY_PURE
  1313. #endif
  1314. #if \
  1315. JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \
  1316. JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \
  1317. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1318. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1319. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1320. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1321. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1322. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1323. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1324. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1325. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1326. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1327. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1328. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1329. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1330. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1331. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1332. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1333. # define JSON_HEDLEY_PURE __attribute__((__pure__))
  1334. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1335. # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data")
  1336. #elif defined(__cplusplus) && \
  1337. ( \
  1338. JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \
  1339. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \
  1340. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \
  1341. )
  1342. # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;")
  1343. #else
  1344. # define JSON_HEDLEY_PURE
  1345. #endif
  1346. #if defined(JSON_HEDLEY_CONST)
  1347. #undef JSON_HEDLEY_CONST
  1348. #endif
  1349. #if \
  1350. JSON_HEDLEY_HAS_ATTRIBUTE(const) || \
  1351. JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \
  1352. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1353. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1354. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1355. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1356. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1357. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1358. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1359. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1360. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1361. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1362. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1363. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1364. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1365. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1366. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \
  1367. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0)
  1368. #define JSON_HEDLEY_CONST __attribute__((__const__))
  1369. #elif \
  1370. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0)
  1371. #define JSON_HEDLEY_CONST _Pragma("no_side_effect")
  1372. #else
  1373. #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE
  1374. #endif
  1375. #if defined(JSON_HEDLEY_RESTRICT)
  1376. #undef JSON_HEDLEY_RESTRICT
  1377. #endif
  1378. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus)
  1379. #define JSON_HEDLEY_RESTRICT restrict
  1380. #elif \
  1381. JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \
  1382. JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \
  1383. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1384. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1385. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1386. JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \
  1387. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1388. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \
  1389. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \
  1390. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1391. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \
  1392. JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \
  1393. defined(__clang__)
  1394. #define JSON_HEDLEY_RESTRICT __restrict
  1395. #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus)
  1396. #define JSON_HEDLEY_RESTRICT _Restrict
  1397. #else
  1398. #define JSON_HEDLEY_RESTRICT
  1399. #endif
  1400. #if defined(JSON_HEDLEY_INLINE)
  1401. #undef JSON_HEDLEY_INLINE
  1402. #endif
  1403. #if \
  1404. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \
  1405. (defined(__cplusplus) && (__cplusplus >= 199711L))
  1406. #define JSON_HEDLEY_INLINE inline
  1407. #elif \
  1408. defined(JSON_HEDLEY_GCC_VERSION) || \
  1409. JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0)
  1410. #define JSON_HEDLEY_INLINE __inline__
  1411. #elif \
  1412. JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \
  1413. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1414. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \
  1415. JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \
  1416. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \
  1417. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \
  1418. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1419. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1420. #define JSON_HEDLEY_INLINE __inline
  1421. #else
  1422. #define JSON_HEDLEY_INLINE
  1423. #endif
  1424. #if defined(JSON_HEDLEY_ALWAYS_INLINE)
  1425. #undef JSON_HEDLEY_ALWAYS_INLINE
  1426. #endif
  1427. #if \
  1428. JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \
  1429. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1430. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1431. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1432. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1433. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1434. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1435. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1436. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1437. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1438. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1439. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1440. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1441. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1442. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1443. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1444. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1445. # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE
  1446. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0)
  1447. # define JSON_HEDLEY_ALWAYS_INLINE __forceinline
  1448. #elif defined(__cplusplus) && \
  1449. ( \
  1450. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1451. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1452. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1453. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1454. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1455. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \
  1456. )
  1457. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;")
  1458. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1459. # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced")
  1460. #else
  1461. # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE
  1462. #endif
  1463. #if defined(JSON_HEDLEY_NEVER_INLINE)
  1464. #undef JSON_HEDLEY_NEVER_INLINE
  1465. #endif
  1466. #if \
  1467. JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \
  1468. JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \
  1469. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1470. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1471. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1472. JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \
  1473. JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \
  1474. (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1475. JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \
  1476. (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1477. JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \
  1478. (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1479. JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \
  1480. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1481. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \
  1482. JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \
  1483. JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0)
  1484. #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__))
  1485. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0)
  1486. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1487. #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0)
  1488. #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline")
  1489. #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus)
  1490. #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;")
  1491. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1492. #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never")
  1493. #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0)
  1494. #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline))
  1495. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0)
  1496. #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline)
  1497. #else
  1498. #define JSON_HEDLEY_NEVER_INLINE
  1499. #endif
  1500. #if defined(JSON_HEDLEY_PRIVATE)
  1501. #undef JSON_HEDLEY_PRIVATE
  1502. #endif
  1503. #if defined(JSON_HEDLEY_PUBLIC)
  1504. #undef JSON_HEDLEY_PUBLIC
  1505. #endif
  1506. #if defined(JSON_HEDLEY_IMPORT)
  1507. #undef JSON_HEDLEY_IMPORT
  1508. #endif
  1509. #if defined(_WIN32) || defined(__CYGWIN__)
  1510. # define JSON_HEDLEY_PRIVATE
  1511. # define JSON_HEDLEY_PUBLIC __declspec(dllexport)
  1512. # define JSON_HEDLEY_IMPORT __declspec(dllimport)
  1513. #else
  1514. # if \
  1515. JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \
  1516. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1517. JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \
  1518. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1519. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1520. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1521. ( \
  1522. defined(__TI_EABI__) && \
  1523. ( \
  1524. (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \
  1525. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \
  1526. ) \
  1527. )
  1528. # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden")))
  1529. # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default")))
  1530. # else
  1531. # define JSON_HEDLEY_PRIVATE
  1532. # define JSON_HEDLEY_PUBLIC
  1533. # endif
  1534. # define JSON_HEDLEY_IMPORT extern
  1535. #endif
  1536. #if defined(JSON_HEDLEY_NO_THROW)
  1537. #undef JSON_HEDLEY_NO_THROW
  1538. #endif
  1539. #if \
  1540. JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \
  1541. JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \
  1542. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1543. #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__))
  1544. #elif \
  1545. JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \
  1546. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0)
  1547. #define JSON_HEDLEY_NO_THROW __declspec(nothrow)
  1548. #else
  1549. #define JSON_HEDLEY_NO_THROW
  1550. #endif
  1551. #if defined(JSON_HEDLEY_FALL_THROUGH)
  1552. #undef JSON_HEDLEY_FALL_THROUGH
  1553. #endif
  1554. #if \
  1555. JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \
  1556. JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0)
  1557. #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__))
  1558. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough)
  1559. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]])
  1560. #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough)
  1561. #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]])
  1562. #elif defined(__fallthrough) /* SAL */
  1563. #define JSON_HEDLEY_FALL_THROUGH __fallthrough
  1564. #else
  1565. #define JSON_HEDLEY_FALL_THROUGH
  1566. #endif
  1567. #if defined(JSON_HEDLEY_RETURNS_NON_NULL)
  1568. #undef JSON_HEDLEY_RETURNS_NON_NULL
  1569. #endif
  1570. #if \
  1571. JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \
  1572. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0)
  1573. #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__))
  1574. #elif defined(_Ret_notnull_) /* SAL */
  1575. #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_
  1576. #else
  1577. #define JSON_HEDLEY_RETURNS_NON_NULL
  1578. #endif
  1579. #if defined(JSON_HEDLEY_ARRAY_PARAM)
  1580. #undef JSON_HEDLEY_ARRAY_PARAM
  1581. #endif
  1582. #if \
  1583. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
  1584. !defined(__STDC_NO_VLA__) && \
  1585. !defined(__cplusplus) && \
  1586. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1587. !defined(JSON_HEDLEY_TINYC_VERSION)
  1588. #define JSON_HEDLEY_ARRAY_PARAM(name) (name)
  1589. #else
  1590. #define JSON_HEDLEY_ARRAY_PARAM(name)
  1591. #endif
  1592. #if defined(JSON_HEDLEY_IS_CONSTANT)
  1593. #undef JSON_HEDLEY_IS_CONSTANT
  1594. #endif
  1595. #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR)
  1596. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  1597. #endif
  1598. /* JSON_HEDLEY_IS_CONSTEXPR_ is for
  1599. HEDLEY INTERNAL USE ONLY. API subject to change without notice. */
  1600. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1601. #undef JSON_HEDLEY_IS_CONSTEXPR_
  1602. #endif
  1603. #if \
  1604. JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \
  1605. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1606. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1607. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \
  1608. JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \
  1609. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1610. JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \
  1611. (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \
  1612. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0)
  1613. #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr)
  1614. #endif
  1615. #if !defined(__cplusplus)
  1616. # if \
  1617. JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \
  1618. JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \
  1619. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1620. JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \
  1621. JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \
  1622. JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \
  1623. JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24)
  1624. #if defined(__INTPTR_TYPE__)
  1625. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*)
  1626. #else
  1627. #include <stdint.h>
  1628. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*)
  1629. #endif
  1630. # elif \
  1631. ( \
  1632. defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \
  1633. !defined(JSON_HEDLEY_SUNPRO_VERSION) && \
  1634. !defined(JSON_HEDLEY_PGI_VERSION) && \
  1635. !defined(JSON_HEDLEY_IAR_VERSION)) || \
  1636. JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \
  1637. JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \
  1638. JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \
  1639. JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \
  1640. JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0)
  1641. #if defined(__INTPTR_TYPE__)
  1642. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0)
  1643. #else
  1644. #include <stdint.h>
  1645. #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0)
  1646. #endif
  1647. # elif \
  1648. defined(JSON_HEDLEY_GCC_VERSION) || \
  1649. defined(JSON_HEDLEY_INTEL_VERSION) || \
  1650. defined(JSON_HEDLEY_TINYC_VERSION) || \
  1651. defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \
  1652. JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \
  1653. defined(JSON_HEDLEY_TI_CL2000_VERSION) || \
  1654. defined(JSON_HEDLEY_TI_CL6X_VERSION) || \
  1655. defined(JSON_HEDLEY_TI_CL7X_VERSION) || \
  1656. defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \
  1657. defined(__clang__)
  1658. # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \
  1659. sizeof(void) != \
  1660. sizeof(*( \
  1661. 1 ? \
  1662. ((void*) ((expr) * 0L) ) : \
  1663. ((struct { char v[sizeof(void) * 2]; } *) 1) \
  1664. ) \
  1665. ) \
  1666. )
  1667. # endif
  1668. #endif
  1669. #if defined(JSON_HEDLEY_IS_CONSTEXPR_)
  1670. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1671. #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr)
  1672. #endif
  1673. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1))
  1674. #else
  1675. #if !defined(JSON_HEDLEY_IS_CONSTANT)
  1676. #define JSON_HEDLEY_IS_CONSTANT(expr) (0)
  1677. #endif
  1678. #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr)
  1679. #endif
  1680. #if defined(JSON_HEDLEY_BEGIN_C_DECLS)
  1681. #undef JSON_HEDLEY_BEGIN_C_DECLS
  1682. #endif
  1683. #if defined(JSON_HEDLEY_END_C_DECLS)
  1684. #undef JSON_HEDLEY_END_C_DECLS
  1685. #endif
  1686. #if defined(JSON_HEDLEY_C_DECL)
  1687. #undef JSON_HEDLEY_C_DECL
  1688. #endif
  1689. #if defined(__cplusplus)
  1690. #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" {
  1691. #define JSON_HEDLEY_END_C_DECLS }
  1692. #define JSON_HEDLEY_C_DECL extern "C"
  1693. #else
  1694. #define JSON_HEDLEY_BEGIN_C_DECLS
  1695. #define JSON_HEDLEY_END_C_DECLS
  1696. #define JSON_HEDLEY_C_DECL
  1697. #endif
  1698. #if defined(JSON_HEDLEY_STATIC_ASSERT)
  1699. #undef JSON_HEDLEY_STATIC_ASSERT
  1700. #endif
  1701. #if \
  1702. !defined(__cplusplus) && ( \
  1703. (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \
  1704. JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \
  1705. JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \
  1706. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \
  1707. defined(_Static_assert) \
  1708. )
  1709. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message)
  1710. #elif \
  1711. (defined(__cplusplus) && (__cplusplus >= 201103L)) || \
  1712. JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0)
  1713. # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message))
  1714. #else
  1715. # define JSON_HEDLEY_STATIC_ASSERT(expr, message)
  1716. #endif
  1717. #if defined(JSON_HEDLEY_NULL)
  1718. #undef JSON_HEDLEY_NULL
  1719. #endif
  1720. #if defined(__cplusplus)
  1721. #if __cplusplus >= 201103L
  1722. #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr)
  1723. #elif defined(NULL)
  1724. #define JSON_HEDLEY_NULL NULL
  1725. #else
  1726. #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0)
  1727. #endif
  1728. #elif defined(NULL)
  1729. #define JSON_HEDLEY_NULL NULL
  1730. #else
  1731. #define JSON_HEDLEY_NULL ((void*) 0)
  1732. #endif
  1733. #if defined(JSON_HEDLEY_MESSAGE)
  1734. #undef JSON_HEDLEY_MESSAGE
  1735. #endif
  1736. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1737. # define JSON_HEDLEY_MESSAGE(msg) \
  1738. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1739. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1740. JSON_HEDLEY_PRAGMA(message msg) \
  1741. JSON_HEDLEY_DIAGNOSTIC_POP
  1742. #elif \
  1743. JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \
  1744. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1745. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg)
  1746. #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0)
  1747. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg)
  1748. #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0)
  1749. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1750. #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0)
  1751. # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1752. #else
  1753. # define JSON_HEDLEY_MESSAGE(msg)
  1754. #endif
  1755. #if defined(JSON_HEDLEY_WARNING)
  1756. #undef JSON_HEDLEY_WARNING
  1757. #endif
  1758. #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas")
  1759. # define JSON_HEDLEY_WARNING(msg) \
  1760. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1761. JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \
  1762. JSON_HEDLEY_PRAGMA(clang warning msg) \
  1763. JSON_HEDLEY_DIAGNOSTIC_POP
  1764. #elif \
  1765. JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \
  1766. JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \
  1767. JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0)
  1768. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg)
  1769. #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0)
  1770. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg))
  1771. #else
  1772. # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg)
  1773. #endif
  1774. #if defined(JSON_HEDLEY_REQUIRE)
  1775. #undef JSON_HEDLEY_REQUIRE
  1776. #endif
  1777. #if defined(JSON_HEDLEY_REQUIRE_MSG)
  1778. #undef JSON_HEDLEY_REQUIRE_MSG
  1779. #endif
  1780. #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if)
  1781. # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat")
  1782. # define JSON_HEDLEY_REQUIRE(expr) \
  1783. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1784. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1785. __attribute__((diagnose_if(!(expr), #expr, "error"))) \
  1786. JSON_HEDLEY_DIAGNOSTIC_POP
  1787. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \
  1788. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1789. _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \
  1790. __attribute__((diagnose_if(!(expr), msg, "error"))) \
  1791. JSON_HEDLEY_DIAGNOSTIC_POP
  1792. # else
  1793. # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error")))
  1794. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error")))
  1795. # endif
  1796. #else
  1797. # define JSON_HEDLEY_REQUIRE(expr)
  1798. # define JSON_HEDLEY_REQUIRE_MSG(expr,msg)
  1799. #endif
  1800. #if defined(JSON_HEDLEY_FLAGS)
  1801. #undef JSON_HEDLEY_FLAGS
  1802. #endif
  1803. #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum)
  1804. #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__))
  1805. #endif
  1806. #if defined(JSON_HEDLEY_FLAGS_CAST)
  1807. #undef JSON_HEDLEY_FLAGS_CAST
  1808. #endif
  1809. #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0)
  1810. # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \
  1811. JSON_HEDLEY_DIAGNOSTIC_PUSH \
  1812. _Pragma("warning(disable:188)") \
  1813. ((T) (expr)); \
  1814. JSON_HEDLEY_DIAGNOSTIC_POP \
  1815. }))
  1816. #else
  1817. # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr)
  1818. #endif
  1819. #if defined(JSON_HEDLEY_EMPTY_BASES)
  1820. #undef JSON_HEDLEY_EMPTY_BASES
  1821. #endif
  1822. #if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)
  1823. #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases)
  1824. #else
  1825. #define JSON_HEDLEY_EMPTY_BASES
  1826. #endif
  1827. /* Remaining macros are deprecated. */
  1828. #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK)
  1829. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  1830. #endif
  1831. #if defined(__clang__)
  1832. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0)
  1833. #else
  1834. #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch)
  1835. #endif
  1836. #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE)
  1837. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  1838. #endif
  1839. #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute)
  1840. #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE)
  1841. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  1842. #endif
  1843. #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute)
  1844. #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN)
  1845. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  1846. #endif
  1847. #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin)
  1848. #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE)
  1849. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  1850. #endif
  1851. #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature)
  1852. #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION)
  1853. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  1854. #endif
  1855. #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension)
  1856. #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE)
  1857. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  1858. #endif
  1859. #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute)
  1860. #if defined(JSON_HEDLEY_CLANG_HAS_WARNING)
  1861. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  1862. #endif
  1863. #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning)
  1864. #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */
  1865. // This file contains all internal macro definitions
  1866. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  1867. // exclude unsupported compilers
  1868. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  1869. #if defined(__clang__)
  1870. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  1871. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  1872. #endif
  1873. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  1874. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  1875. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  1876. #endif
  1877. #endif
  1878. #endif
  1879. // C++ language standard detection
  1880. #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L)
  1881. #define JSON_HAS_CPP_20
  1882. #define JSON_HAS_CPP_17
  1883. #define JSON_HAS_CPP_14
  1884. #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  1885. #define JSON_HAS_CPP_17
  1886. #define JSON_HAS_CPP_14
  1887. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  1888. #define JSON_HAS_CPP_14
  1889. #endif
  1890. // disable float-equal warnings on GCC/clang
  1891. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  1892. #pragma GCC diagnostic push
  1893. #pragma GCC diagnostic ignored "-Wfloat-equal"
  1894. #endif
  1895. // disable documentation warnings on clang
  1896. #if defined(__clang__)
  1897. #pragma GCC diagnostic push
  1898. #pragma GCC diagnostic ignored "-Wdocumentation"
  1899. #endif
  1900. // allow to disable exceptions
  1901. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  1902. #define JSON_THROW(exception) throw exception
  1903. #define JSON_TRY try
  1904. #define JSON_CATCH(exception) catch(exception)
  1905. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  1906. #else
  1907. #include <cstdlib>
  1908. #define JSON_THROW(exception) std::abort()
  1909. #define JSON_TRY if(true)
  1910. #define JSON_CATCH(exception) if(false)
  1911. #define JSON_INTERNAL_CATCH(exception) if(false)
  1912. #endif
  1913. // override exception macros
  1914. #if defined(JSON_THROW_USER)
  1915. #undef JSON_THROW
  1916. #define JSON_THROW JSON_THROW_USER
  1917. #endif
  1918. #if defined(JSON_TRY_USER)
  1919. #undef JSON_TRY
  1920. #define JSON_TRY JSON_TRY_USER
  1921. #endif
  1922. #if defined(JSON_CATCH_USER)
  1923. #undef JSON_CATCH
  1924. #define JSON_CATCH JSON_CATCH_USER
  1925. #undef JSON_INTERNAL_CATCH
  1926. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  1927. #endif
  1928. #if defined(JSON_INTERNAL_CATCH_USER)
  1929. #undef JSON_INTERNAL_CATCH
  1930. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  1931. #endif
  1932. // allow to override assert
  1933. #if !defined(JSON_ASSERT)
  1934. #include <cassert> // assert
  1935. #define JSON_ASSERT(x) assert(x)
  1936. #endif
  1937. /*!
  1938. @brief macro to briefly define a mapping between an enum and JSON
  1939. @def NLOHMANN_JSON_SERIALIZE_ENUM
  1940. @since version 3.4.0
  1941. */
  1942. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  1943. template<typename BasicJsonType> \
  1944. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  1945. { \
  1946. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1947. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1948. auto it = std::find_if(std::begin(m), std::end(m), \
  1949. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1950. { \
  1951. return ej_pair.first == e; \
  1952. }); \
  1953. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  1954. } \
  1955. template<typename BasicJsonType> \
  1956. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  1957. { \
  1958. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  1959. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  1960. auto it = std::find_if(std::begin(m), std::end(m), \
  1961. [&j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  1962. { \
  1963. return ej_pair.second == j; \
  1964. }); \
  1965. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  1966. }
  1967. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  1968. // may be removed in the future once the class is split.
  1969. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  1970. template<template<typename, typename, typename...> class ObjectType, \
  1971. template<typename, typename...> class ArrayType, \
  1972. class StringType, class BooleanType, class NumberIntegerType, \
  1973. class NumberUnsignedType, class NumberFloatType, \
  1974. template<typename> class AllocatorType, \
  1975. template<typename, typename = void> class JSONSerializer, \
  1976. class BinaryType>
  1977. #define NLOHMANN_BASIC_JSON_TPL \
  1978. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  1979. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  1980. AllocatorType, JSONSerializer, BinaryType>
  1981. // Macros to simplify conversion from/to types
  1982. #define NLOHMANN_JSON_EXPAND( x ) x
  1983. #define NLOHMANN_JSON_GET_MACRO(_1,_2,_3,_4,_5,_6, _7, _8, _9, _10, _11, NAME,...) NAME
  1984. #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, NLOHMANN_JSON_PASTE11, \
  1985. NLOHMANN_JSON_PASTE10, NLOHMANN_JSON_PASTE9, NLOHMANN_JSON_PASTE8, NLOHMANN_JSON_PASTE7, \
  1986. NLOHMANN_JSON_PASTE6, NLOHMANN_JSON_PASTE5, NLOHMANN_JSON_PASTE4, NLOHMANN_JSON_PASTE3, \
  1987. NLOHMANN_JSON_PASTE2, NLOHMANN_JSON_PASTE1)(__VA_ARGS__))
  1988. #define NLOHMANN_JSON_PASTE2(func, v1) func(v1)
  1989. #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2)
  1990. #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3)
  1991. #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4)
  1992. #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5)
  1993. #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6)
  1994. #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7)
  1995. #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8)
  1996. #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8, v9)
  1997. #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8, v9, v10)
  1998. #define NLOHMANN_JSON_TO(v1) j[#v1] = t.v1;
  1999. #define NLOHMANN_JSON_FROM(v1) j.at(#v1).get_to(t.v1);
  2000. /*!
  2001. @brief macro
  2002. @def NLOHMANN_DEFINE_TYPE_INTRUSIVE
  2003. @since version 3.9.0
  2004. */
  2005. #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \
  2006. friend void to_json(nlohmann::json& j, const Type& t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2007. friend void from_json(const nlohmann::json& j, Type& t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2008. /*!
  2009. @brief macro
  2010. @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
  2011. @since version 3.9.0
  2012. */
  2013. #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \
  2014. void to_json(nlohmann::json& j, const Type& t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \
  2015. void from_json(const nlohmann::json& j, Type& t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) }
  2016. namespace nlohmann
  2017. {
  2018. namespace detail
  2019. {
  2020. ////////////////
  2021. // exceptions //
  2022. ////////////////
  2023. /*!
  2024. @brief general exception of the @ref basic_json class
  2025. This class is an extension of `std::exception` objects with a member @a id for
  2026. exception ids. It is used as the base class for all exceptions thrown by the
  2027. @ref basic_json class. This class can hence be used as "wildcard" to catch
  2028. exceptions.
  2029. Subclasses:
  2030. - @ref parse_error for exceptions indicating a parse error
  2031. - @ref invalid_iterator for exceptions indicating errors with iterators
  2032. - @ref type_error for exceptions indicating executing a member function with
  2033. a wrong type
  2034. - @ref out_of_range for exceptions indicating access out of the defined range
  2035. - @ref other_error for exceptions indicating other library errors
  2036. @internal
  2037. @note To have nothrow-copy-constructible exceptions, we internally use
  2038. `std::runtime_error` which can cope with arbitrary-length error messages.
  2039. Intermediate strings are built with static functions and then passed to
  2040. the actual constructor.
  2041. @endinternal
  2042. @liveexample{The following code shows how arbitrary library exceptions can be
  2043. caught.,exception}
  2044. @since version 3.0.0
  2045. */
  2046. class exception : public std::exception
  2047. {
  2048. public:
  2049. /// returns the explanatory string
  2050. JSON_HEDLEY_RETURNS_NON_NULL
  2051. const char* what() const noexcept override
  2052. {
  2053. return m.what();
  2054. }
  2055. /// the id of the exception
  2056. const int id;
  2057. protected:
  2058. JSON_HEDLEY_NON_NULL(3)
  2059. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  2060. static std::string name(const std::string& ename, int id_)
  2061. {
  2062. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  2063. }
  2064. private:
  2065. /// an exception object as storage for error messages
  2066. std::runtime_error m;
  2067. };
  2068. /*!
  2069. @brief exception indicating a parse error
  2070. This exception is thrown by the library when a parse error occurs. Parse errors
  2071. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  2072. as when using JSON Patch.
  2073. Member @a byte holds the byte index of the last read character in the input
  2074. file.
  2075. Exceptions have ids 1xx.
  2076. name / id | example message | description
  2077. ------------------------------ | --------------- | -------------------------
  2078. 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.
  2079. 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.
  2080. 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.
  2081. 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.
  2082. 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.
  2083. 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`.
  2084. 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.
  2085. 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.
  2086. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  2087. 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.
  2088. 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.
  2089. 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.
  2090. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  2091. @note For an input with n bytes, 1 is the index of the first character and n+1
  2092. is the index of the terminating null byte or the end of file. This also
  2093. holds true when reading a byte vector (CBOR or MessagePack).
  2094. @liveexample{The following code shows how a `parse_error` exception can be
  2095. caught.,parse_error}
  2096. @sa - @ref exception for the base class of the library exceptions
  2097. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2098. @sa - @ref type_error for exceptions indicating executing a member function with
  2099. a wrong type
  2100. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2101. @sa - @ref other_error for exceptions indicating other library errors
  2102. @since version 3.0.0
  2103. */
  2104. class parse_error : public exception
  2105. {
  2106. public:
  2107. /*!
  2108. @brief create a parse error exception
  2109. @param[in] id_ the id of the exception
  2110. @param[in] pos the position where the error occurred (or with
  2111. chars_read_total=0 if the position cannot be
  2112. determined)
  2113. @param[in] what_arg the explanatory string
  2114. @return parse_error object
  2115. */
  2116. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  2117. {
  2118. std::string w = exception::name("parse_error", id_) + "parse error" +
  2119. position_string(pos) + ": " + what_arg;
  2120. return parse_error(id_, pos.chars_read_total, w.c_str());
  2121. }
  2122. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  2123. {
  2124. std::string w = exception::name("parse_error", id_) + "parse error" +
  2125. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  2126. ": " + what_arg;
  2127. return parse_error(id_, byte_, w.c_str());
  2128. }
  2129. /*!
  2130. @brief byte index of the parse error
  2131. The byte index of the last read character in the input file.
  2132. @note For an input with n bytes, 1 is the index of the first character and
  2133. n+1 is the index of the terminating null byte or the end of file.
  2134. This also holds true when reading a byte vector (CBOR or MessagePack).
  2135. */
  2136. const std::size_t byte;
  2137. private:
  2138. parse_error(int id_, std::size_t byte_, const char* what_arg)
  2139. : exception(id_, what_arg), byte(byte_) {}
  2140. static std::string position_string(const position_t& pos)
  2141. {
  2142. return " at line " + std::to_string(pos.lines_read + 1) +
  2143. ", column " + std::to_string(pos.chars_read_current_line);
  2144. }
  2145. };
  2146. /*!
  2147. @brief exception indicating errors with iterators
  2148. This exception is thrown if iterators passed to a library function do not match
  2149. the expected semantics.
  2150. Exceptions have ids 2xx.
  2151. name / id | example message | description
  2152. ----------------------------------- | --------------- | -------------------------
  2153. 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.
  2154. 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.
  2155. 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.
  2156. 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.
  2157. 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.
  2158. 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.
  2159. 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.
  2160. 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.
  2161. 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.
  2162. 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.
  2163. 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.
  2164. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  2165. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  2166. 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().
  2167. @liveexample{The following code shows how an `invalid_iterator` exception can be
  2168. caught.,invalid_iterator}
  2169. @sa - @ref exception for the base class of the library exceptions
  2170. @sa - @ref parse_error for exceptions indicating a parse error
  2171. @sa - @ref type_error for exceptions indicating executing a member function with
  2172. a wrong type
  2173. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2174. @sa - @ref other_error for exceptions indicating other library errors
  2175. @since version 3.0.0
  2176. */
  2177. class invalid_iterator : public exception
  2178. {
  2179. public:
  2180. static invalid_iterator create(int id_, const std::string& what_arg)
  2181. {
  2182. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  2183. return invalid_iterator(id_, w.c_str());
  2184. }
  2185. private:
  2186. JSON_HEDLEY_NON_NULL(3)
  2187. invalid_iterator(int id_, const char* what_arg)
  2188. : exception(id_, what_arg) {}
  2189. };
  2190. /*!
  2191. @brief exception indicating executing a member function with a wrong type
  2192. This exception is thrown in case of a type error; that is, a library function is
  2193. executed on a JSON value whose type does not match the expected semantics.
  2194. Exceptions have ids 3xx.
  2195. name / id | example message | description
  2196. ----------------------------- | --------------- | -------------------------
  2197. 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.
  2198. 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.
  2199. 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 &.
  2200. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  2201. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  2202. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  2203. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  2204. 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.
  2205. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  2206. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  2207. 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.
  2208. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  2209. 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.
  2210. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  2211. 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.
  2212. 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. |
  2213. 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) |
  2214. @liveexample{The following code shows how a `type_error` exception can be
  2215. caught.,type_error}
  2216. @sa - @ref exception for the base class of the library exceptions
  2217. @sa - @ref parse_error for exceptions indicating a parse error
  2218. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2219. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2220. @sa - @ref other_error for exceptions indicating other library errors
  2221. @since version 3.0.0
  2222. */
  2223. class type_error : public exception
  2224. {
  2225. public:
  2226. static type_error create(int id_, const std::string& what_arg)
  2227. {
  2228. std::string w = exception::name("type_error", id_) + what_arg;
  2229. return type_error(id_, w.c_str());
  2230. }
  2231. private:
  2232. JSON_HEDLEY_NON_NULL(3)
  2233. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2234. };
  2235. /*!
  2236. @brief exception indicating access out of the defined range
  2237. This exception is thrown in case a library function is called on an input
  2238. parameter that exceeds the expected range, for instance in case of array
  2239. indices or nonexisting object keys.
  2240. Exceptions have ids 4xx.
  2241. name / id | example message | description
  2242. ------------------------------- | --------------- | -------------------------
  2243. 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.
  2244. 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.
  2245. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  2246. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  2247. 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.
  2248. 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.
  2249. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  2250. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  2251. 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 |
  2252. @liveexample{The following code shows how an `out_of_range` exception can be
  2253. caught.,out_of_range}
  2254. @sa - @ref exception for the base class of the library exceptions
  2255. @sa - @ref parse_error for exceptions indicating a parse error
  2256. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2257. @sa - @ref type_error for exceptions indicating executing a member function with
  2258. a wrong type
  2259. @sa - @ref other_error for exceptions indicating other library errors
  2260. @since version 3.0.0
  2261. */
  2262. class out_of_range : public exception
  2263. {
  2264. public:
  2265. static out_of_range create(int id_, const std::string& what_arg)
  2266. {
  2267. std::string w = exception::name("out_of_range", id_) + what_arg;
  2268. return out_of_range(id_, w.c_str());
  2269. }
  2270. private:
  2271. JSON_HEDLEY_NON_NULL(3)
  2272. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2273. };
  2274. /*!
  2275. @brief exception indicating other library errors
  2276. This exception is thrown in case of errors that cannot be classified with the
  2277. other exception types.
  2278. Exceptions have ids 5xx.
  2279. name / id | example message | description
  2280. ------------------------------ | --------------- | -------------------------
  2281. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  2282. @sa - @ref exception for the base class of the library exceptions
  2283. @sa - @ref parse_error for exceptions indicating a parse error
  2284. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  2285. @sa - @ref type_error for exceptions indicating executing a member function with
  2286. a wrong type
  2287. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  2288. @liveexample{The following code shows how an `other_error` exception can be
  2289. caught.,other_error}
  2290. @since version 3.0.0
  2291. */
  2292. class other_error : public exception
  2293. {
  2294. public:
  2295. static other_error create(int id_, const std::string& what_arg)
  2296. {
  2297. std::string w = exception::name("other_error", id_) + what_arg;
  2298. return other_error(id_, w.c_str());
  2299. }
  2300. private:
  2301. JSON_HEDLEY_NON_NULL(3)
  2302. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  2303. };
  2304. } // namespace detail
  2305. } // namespace nlohmann
  2306. // #include <nlohmann/detail/macro_scope.hpp>
  2307. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2308. #include <cstddef> // size_t
  2309. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  2310. namespace nlohmann
  2311. {
  2312. namespace detail
  2313. {
  2314. // alias templates to reduce boilerplate
  2315. template<bool B, typename T = void>
  2316. using enable_if_t = typename std::enable_if<B, T>::type;
  2317. template<typename T>
  2318. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  2319. // implementation of C++14 index_sequence and affiliates
  2320. // source: https://stackoverflow.com/a/32223343
  2321. template<std::size_t... Ints>
  2322. struct index_sequence
  2323. {
  2324. using type = index_sequence;
  2325. using value_type = std::size_t;
  2326. static constexpr std::size_t size() noexcept
  2327. {
  2328. return sizeof...(Ints);
  2329. }
  2330. };
  2331. template<class Sequence1, class Sequence2>
  2332. struct merge_and_renumber;
  2333. template<std::size_t... I1, std::size_t... I2>
  2334. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  2335. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  2336. template<std::size_t N>
  2337. struct make_index_sequence
  2338. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  2339. typename make_index_sequence < N - N / 2 >::type > {};
  2340. template<> struct make_index_sequence<0> : index_sequence<> {};
  2341. template<> struct make_index_sequence<1> : index_sequence<0> {};
  2342. template<typename... Ts>
  2343. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  2344. // dispatch utility (taken from ranges-v3)
  2345. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  2346. template<> struct priority_tag<0> {};
  2347. // taken from ranges-v3
  2348. template<typename T>
  2349. struct static_const
  2350. {
  2351. static constexpr T value{};
  2352. };
  2353. template<typename T>
  2354. constexpr T static_const<T>::value;
  2355. } // namespace detail
  2356. } // namespace nlohmann
  2357. // #include <nlohmann/detail/meta/type_traits.hpp>
  2358. #include <limits> // numeric_limits
  2359. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  2360. #include <utility> // declval
  2361. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  2362. #include <iterator> // random_access_iterator_tag
  2363. // #include <nlohmann/detail/meta/void_t.hpp>
  2364. namespace nlohmann
  2365. {
  2366. namespace detail
  2367. {
  2368. template<typename ...Ts> struct make_void
  2369. {
  2370. using type = void;
  2371. };
  2372. template<typename ...Ts> using void_t = typename make_void<Ts...>::type;
  2373. } // namespace detail
  2374. } // namespace nlohmann
  2375. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2376. namespace nlohmann
  2377. {
  2378. namespace detail
  2379. {
  2380. template<typename It, typename = void>
  2381. struct iterator_types {};
  2382. template<typename It>
  2383. struct iterator_types <
  2384. It,
  2385. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  2386. typename It::reference, typename It::iterator_category >>
  2387. {
  2388. using difference_type = typename It::difference_type;
  2389. using value_type = typename It::value_type;
  2390. using pointer = typename It::pointer;
  2391. using reference = typename It::reference;
  2392. using iterator_category = typename It::iterator_category;
  2393. };
  2394. // This is required as some compilers implement std::iterator_traits in a way that
  2395. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  2396. template<typename T, typename = void>
  2397. struct iterator_traits
  2398. {
  2399. };
  2400. template<typename T>
  2401. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  2402. : iterator_types<T>
  2403. {
  2404. };
  2405. template<typename T>
  2406. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  2407. {
  2408. using iterator_category = std::random_access_iterator_tag;
  2409. using value_type = T;
  2410. using difference_type = ptrdiff_t;
  2411. using pointer = T*;
  2412. using reference = T&;
  2413. };
  2414. } // namespace detail
  2415. } // namespace nlohmann
  2416. // #include <nlohmann/detail/macro_scope.hpp>
  2417. // #include <nlohmann/detail/meta/cpp_future.hpp>
  2418. // #include <nlohmann/detail/meta/detected.hpp>
  2419. #include <type_traits>
  2420. // #include <nlohmann/detail/meta/void_t.hpp>
  2421. // https://en.cppreference.com/w/cpp/experimental/is_detected
  2422. namespace nlohmann
  2423. {
  2424. namespace detail
  2425. {
  2426. struct nonesuch
  2427. {
  2428. nonesuch() = delete;
  2429. ~nonesuch() = delete;
  2430. nonesuch(nonesuch const&) = delete;
  2431. nonesuch(nonesuch const&&) = delete;
  2432. void operator=(nonesuch const&) = delete;
  2433. void operator=(nonesuch&&) = delete;
  2434. };
  2435. template<class Default,
  2436. class AlwaysVoid,
  2437. template<class...> class Op,
  2438. class... Args>
  2439. struct detector
  2440. {
  2441. using value_t = std::false_type;
  2442. using type = Default;
  2443. };
  2444. template<class Default, template<class...> class Op, class... Args>
  2445. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  2446. {
  2447. using value_t = std::true_type;
  2448. using type = Op<Args...>;
  2449. };
  2450. template<template<class...> class Op, class... Args>
  2451. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  2452. template<template<class...> class Op, class... Args>
  2453. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  2454. template<class Default, template<class...> class Op, class... Args>
  2455. using detected_or = detector<Default, void, Op, Args...>;
  2456. template<class Default, template<class...> class Op, class... Args>
  2457. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  2458. template<class Expected, template<class...> class Op, class... Args>
  2459. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  2460. template<class To, template<class...> class Op, class... Args>
  2461. using is_detected_convertible =
  2462. std::is_convertible<detected_t<Op, Args...>, To>;
  2463. } // namespace detail
  2464. } // namespace nlohmann
  2465. // #include <nlohmann/json_fwd.hpp>
  2466. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2467. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2468. #include <cstdint> // int64_t, uint64_t
  2469. #include <map> // map
  2470. #include <memory> // allocator
  2471. #include <string> // string
  2472. #include <vector> // vector
  2473. /*!
  2474. @brief namespace for Niels Lohmann
  2475. @see https://github.com/nlohmann
  2476. @since version 1.0.0
  2477. */
  2478. namespace nlohmann
  2479. {
  2480. /*!
  2481. @brief default JSONSerializer template argument
  2482. This serializer ignores the template arguments and uses ADL
  2483. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  2484. for serialization.
  2485. */
  2486. template<typename T = void, typename SFINAE = void>
  2487. struct adl_serializer;
  2488. template<template<typename U, typename V, typename... Args> class ObjectType =
  2489. std::map,
  2490. template<typename U, typename... Args> class ArrayType = std::vector,
  2491. class StringType = std::string, class BooleanType = bool,
  2492. class NumberIntegerType = std::int64_t,
  2493. class NumberUnsignedType = std::uint64_t,
  2494. class NumberFloatType = double,
  2495. template<typename U> class AllocatorType = std::allocator,
  2496. template<typename T, typename SFINAE = void> class JSONSerializer =
  2497. adl_serializer,
  2498. class BinaryType = std::vector<std::uint8_t>>
  2499. class basic_json;
  2500. /*!
  2501. @brief JSON Pointer
  2502. A JSON pointer defines a string syntax for identifying a specific value
  2503. within a JSON document. It can be used with functions `at` and
  2504. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  2505. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  2506. @since version 2.0.0
  2507. */
  2508. template<typename BasicJsonType>
  2509. class json_pointer;
  2510. /*!
  2511. @brief default JSON class
  2512. This type is the default specialization of the @ref basic_json class which
  2513. uses the standard template types.
  2514. @since version 1.0.0
  2515. */
  2516. using json = basic_json<>;
  2517. template<class Key, class T, class IgnoredLess, class Allocator>
  2518. struct ordered_map;
  2519. /*!
  2520. @brief ordered JSON class
  2521. This type preserves the insertion order of object keys.
  2522. @since version 3.9.0
  2523. */
  2524. using ordered_json = basic_json<nlohmann::ordered_map>;
  2525. } // namespace nlohmann
  2526. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  2527. namespace nlohmann
  2528. {
  2529. /*!
  2530. @brief detail namespace with internal helper functions
  2531. This namespace collects functions that should not be exposed,
  2532. implementations of some @ref basic_json methods, and meta-programming helpers.
  2533. @since version 2.1.0
  2534. */
  2535. namespace detail
  2536. {
  2537. /////////////
  2538. // helpers //
  2539. /////////////
  2540. // Note to maintainers:
  2541. //
  2542. // Every trait in this file expects a non CV-qualified type.
  2543. // The only exceptions are in the 'aliases for detected' section
  2544. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  2545. //
  2546. // In this case, T has to be properly CV-qualified to constraint the function arguments
  2547. // (e.g. to_json(BasicJsonType&, const T&))
  2548. template<typename> struct is_basic_json : std::false_type {};
  2549. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  2550. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  2551. //////////////////////
  2552. // json_ref helpers //
  2553. //////////////////////
  2554. template<typename>
  2555. class json_ref;
  2556. template<typename>
  2557. struct is_json_ref : std::false_type {};
  2558. template<typename T>
  2559. struct is_json_ref<json_ref<T>> : std::true_type {};
  2560. //////////////////////////
  2561. // aliases for detected //
  2562. //////////////////////////
  2563. template<typename T>
  2564. using mapped_type_t = typename T::mapped_type;
  2565. template<typename T>
  2566. using key_type_t = typename T::key_type;
  2567. template<typename T>
  2568. using value_type_t = typename T::value_type;
  2569. template<typename T>
  2570. using difference_type_t = typename T::difference_type;
  2571. template<typename T>
  2572. using pointer_t = typename T::pointer;
  2573. template<typename T>
  2574. using reference_t = typename T::reference;
  2575. template<typename T>
  2576. using iterator_category_t = typename T::iterator_category;
  2577. template<typename T>
  2578. using iterator_t = typename T::iterator;
  2579. template<typename T, typename... Args>
  2580. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  2581. template<typename T, typename... Args>
  2582. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  2583. template<typename T, typename U>
  2584. using get_template_function = decltype(std::declval<T>().template get<U>());
  2585. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  2586. template<typename BasicJsonType, typename T, typename = void>
  2587. struct has_from_json : std::false_type {};
  2588. template<typename BasicJsonType, typename T>
  2589. struct has_from_json < BasicJsonType, T,
  2590. enable_if_t < !is_basic_json<T>::value >>
  2591. {
  2592. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2593. static constexpr bool value =
  2594. is_detected_exact<void, from_json_function, serializer,
  2595. const BasicJsonType&, T&>::value;
  2596. };
  2597. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  2598. // this overload is used for non-default-constructible user-defined-types
  2599. template<typename BasicJsonType, typename T, typename = void>
  2600. struct has_non_default_from_json : std::false_type {};
  2601. template<typename BasicJsonType, typename T>
  2602. struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  2603. {
  2604. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2605. static constexpr bool value =
  2606. is_detected_exact<T, from_json_function, serializer,
  2607. const BasicJsonType&>::value;
  2608. };
  2609. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  2610. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  2611. template<typename BasicJsonType, typename T, typename = void>
  2612. struct has_to_json : std::false_type {};
  2613. template<typename BasicJsonType, typename T>
  2614. struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json<T>::value >>
  2615. {
  2616. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  2617. static constexpr bool value =
  2618. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  2619. T>::value;
  2620. };
  2621. ///////////////////
  2622. // is_ functions //
  2623. ///////////////////
  2624. template<typename T, typename = void>
  2625. struct is_iterator_traits : std::false_type {};
  2626. template<typename T>
  2627. struct is_iterator_traits<iterator_traits<T>>
  2628. {
  2629. private:
  2630. using traits = iterator_traits<T>;
  2631. public:
  2632. static constexpr auto value =
  2633. is_detected<value_type_t, traits>::value &&
  2634. is_detected<difference_type_t, traits>::value &&
  2635. is_detected<pointer_t, traits>::value &&
  2636. is_detected<iterator_category_t, traits>::value &&
  2637. is_detected<reference_t, traits>::value;
  2638. };
  2639. // source: https://stackoverflow.com/a/37193089/4116453
  2640. template<typename T, typename = void>
  2641. struct is_complete_type : std::false_type {};
  2642. template<typename T>
  2643. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  2644. template<typename BasicJsonType, typename CompatibleObjectType,
  2645. typename = void>
  2646. struct is_compatible_object_type_impl : std::false_type {};
  2647. template<typename BasicJsonType, typename CompatibleObjectType>
  2648. struct is_compatible_object_type_impl <
  2649. BasicJsonType, CompatibleObjectType,
  2650. enable_if_t < is_detected<mapped_type_t, CompatibleObjectType>::value&&
  2651. is_detected<key_type_t, CompatibleObjectType>::value >>
  2652. {
  2653. using object_t = typename BasicJsonType::object_t;
  2654. // macOS's is_constructible does not play well with nonesuch...
  2655. static constexpr bool value =
  2656. std::is_constructible<typename object_t::key_type,
  2657. typename CompatibleObjectType::key_type>::value &&
  2658. std::is_constructible<typename object_t::mapped_type,
  2659. typename CompatibleObjectType::mapped_type>::value;
  2660. };
  2661. template<typename BasicJsonType, typename CompatibleObjectType>
  2662. struct is_compatible_object_type
  2663. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  2664. template<typename BasicJsonType, typename ConstructibleObjectType,
  2665. typename = void>
  2666. struct is_constructible_object_type_impl : std::false_type {};
  2667. template<typename BasicJsonType, typename ConstructibleObjectType>
  2668. struct is_constructible_object_type_impl <
  2669. BasicJsonType, ConstructibleObjectType,
  2670. enable_if_t < is_detected<mapped_type_t, ConstructibleObjectType>::value&&
  2671. is_detected<key_type_t, ConstructibleObjectType>::value >>
  2672. {
  2673. using object_t = typename BasicJsonType::object_t;
  2674. static constexpr bool value =
  2675. (std::is_default_constructible<ConstructibleObjectType>::value &&
  2676. (std::is_move_assignable<ConstructibleObjectType>::value ||
  2677. std::is_copy_assignable<ConstructibleObjectType>::value) &&
  2678. (std::is_constructible<typename ConstructibleObjectType::key_type,
  2679. typename object_t::key_type>::value &&
  2680. std::is_same <
  2681. typename object_t::mapped_type,
  2682. typename ConstructibleObjectType::mapped_type >::value)) ||
  2683. (has_from_json<BasicJsonType,
  2684. typename ConstructibleObjectType::mapped_type>::value ||
  2685. has_non_default_from_json <
  2686. BasicJsonType,
  2687. typename ConstructibleObjectType::mapped_type >::value);
  2688. };
  2689. template<typename BasicJsonType, typename ConstructibleObjectType>
  2690. struct is_constructible_object_type
  2691. : is_constructible_object_type_impl<BasicJsonType,
  2692. ConstructibleObjectType> {};
  2693. template<typename BasicJsonType, typename CompatibleStringType,
  2694. typename = void>
  2695. struct is_compatible_string_type_impl : std::false_type {};
  2696. template<typename BasicJsonType, typename CompatibleStringType>
  2697. struct is_compatible_string_type_impl <
  2698. BasicJsonType, CompatibleStringType,
  2699. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2700. value_type_t, CompatibleStringType>::value >>
  2701. {
  2702. static constexpr auto value =
  2703. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  2704. };
  2705. template<typename BasicJsonType, typename ConstructibleStringType>
  2706. struct is_compatible_string_type
  2707. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2708. template<typename BasicJsonType, typename ConstructibleStringType,
  2709. typename = void>
  2710. struct is_constructible_string_type_impl : std::false_type {};
  2711. template<typename BasicJsonType, typename ConstructibleStringType>
  2712. struct is_constructible_string_type_impl <
  2713. BasicJsonType, ConstructibleStringType,
  2714. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  2715. value_type_t, ConstructibleStringType>::value >>
  2716. {
  2717. static constexpr auto value =
  2718. std::is_constructible<ConstructibleStringType,
  2719. typename BasicJsonType::string_t>::value;
  2720. };
  2721. template<typename BasicJsonType, typename ConstructibleStringType>
  2722. struct is_constructible_string_type
  2723. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  2724. template<typename BasicJsonType, typename CompatibleArrayType, typename = void>
  2725. struct is_compatible_array_type_impl : std::false_type {};
  2726. template<typename BasicJsonType, typename CompatibleArrayType>
  2727. struct is_compatible_array_type_impl <
  2728. BasicJsonType, CompatibleArrayType,
  2729. enable_if_t < is_detected<value_type_t, CompatibleArrayType>::value&&
  2730. is_detected<iterator_t, CompatibleArrayType>::value&&
  2731. // This is needed because json_reverse_iterator has a ::iterator type...
  2732. // Therefore it is detected as a CompatibleArrayType.
  2733. // The real fix would be to have an Iterable concept.
  2734. !is_iterator_traits <
  2735. iterator_traits<CompatibleArrayType >>::value >>
  2736. {
  2737. static constexpr bool value =
  2738. std::is_constructible<BasicJsonType,
  2739. typename CompatibleArrayType::value_type>::value;
  2740. };
  2741. template<typename BasicJsonType, typename CompatibleArrayType>
  2742. struct is_compatible_array_type
  2743. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  2744. template<typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  2745. struct is_constructible_array_type_impl : std::false_type {};
  2746. template<typename BasicJsonType, typename ConstructibleArrayType>
  2747. struct is_constructible_array_type_impl <
  2748. BasicJsonType, ConstructibleArrayType,
  2749. enable_if_t<std::is_same<ConstructibleArrayType,
  2750. typename BasicJsonType::value_type>::value >>
  2751. : std::true_type {};
  2752. template<typename BasicJsonType, typename ConstructibleArrayType>
  2753. struct is_constructible_array_type_impl <
  2754. BasicJsonType, ConstructibleArrayType,
  2755. enable_if_t < !std::is_same<ConstructibleArrayType,
  2756. typename BasicJsonType::value_type>::value&&
  2757. std::is_default_constructible<ConstructibleArrayType>::value&&
  2758. (std::is_move_assignable<ConstructibleArrayType>::value ||
  2759. std::is_copy_assignable<ConstructibleArrayType>::value)&&
  2760. is_detected<value_type_t, ConstructibleArrayType>::value&&
  2761. is_detected<iterator_t, ConstructibleArrayType>::value&&
  2762. is_complete_type <
  2763. detected_t<value_type_t, ConstructibleArrayType >>::value >>
  2764. {
  2765. static constexpr bool value =
  2766. // This is needed because json_reverse_iterator has a ::iterator type,
  2767. // furthermore, std::back_insert_iterator (and other iterators) have a
  2768. // base class `iterator`... Therefore it is detected as a
  2769. // ConstructibleArrayType. The real fix would be to have an Iterable
  2770. // concept.
  2771. !is_iterator_traits<iterator_traits<ConstructibleArrayType>>::value &&
  2772. (std::is_same<typename ConstructibleArrayType::value_type,
  2773. typename BasicJsonType::array_t::value_type>::value ||
  2774. has_from_json<BasicJsonType,
  2775. typename ConstructibleArrayType::value_type>::value ||
  2776. has_non_default_from_json <
  2777. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  2778. };
  2779. template<typename BasicJsonType, typename ConstructibleArrayType>
  2780. struct is_constructible_array_type
  2781. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  2782. template<typename RealIntegerType, typename CompatibleNumberIntegerType,
  2783. typename = void>
  2784. struct is_compatible_integer_type_impl : std::false_type {};
  2785. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  2786. struct is_compatible_integer_type_impl <
  2787. RealIntegerType, CompatibleNumberIntegerType,
  2788. enable_if_t < std::is_integral<RealIntegerType>::value&&
  2789. std::is_integral<CompatibleNumberIntegerType>::value&&
  2790. !std::is_same<bool, CompatibleNumberIntegerType>::value >>
  2791. {
  2792. // is there an assert somewhere on overflows?
  2793. using RealLimits = std::numeric_limits<RealIntegerType>;
  2794. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  2795. static constexpr auto value =
  2796. std::is_constructible<RealIntegerType,
  2797. CompatibleNumberIntegerType>::value &&
  2798. CompatibleLimits::is_integer &&
  2799. RealLimits::is_signed == CompatibleLimits::is_signed;
  2800. };
  2801. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  2802. struct is_compatible_integer_type
  2803. : is_compatible_integer_type_impl<RealIntegerType,
  2804. CompatibleNumberIntegerType> {};
  2805. template<typename BasicJsonType, typename CompatibleType, typename = void>
  2806. struct is_compatible_type_impl: std::false_type {};
  2807. template<typename BasicJsonType, typename CompatibleType>
  2808. struct is_compatible_type_impl <
  2809. BasicJsonType, CompatibleType,
  2810. enable_if_t<is_complete_type<CompatibleType>::value >>
  2811. {
  2812. static constexpr bool value =
  2813. has_to_json<BasicJsonType, CompatibleType>::value;
  2814. };
  2815. template<typename BasicJsonType, typename CompatibleType>
  2816. struct is_compatible_type
  2817. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  2818. // https://en.cppreference.com/w/cpp/types/conjunction
  2819. template<class...> struct conjunction : std::true_type { };
  2820. template<class B1> struct conjunction<B1> : B1 { };
  2821. template<class B1, class... Bn>
  2822. struct conjunction<B1, Bn...>
  2823. : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  2824. template<typename T1, typename T2>
  2825. struct is_constructible_tuple : std::false_type {};
  2826. template<typename T1, typename... Args>
  2827. struct is_constructible_tuple<T1, std::tuple<Args...>> : conjunction<std::is_constructible<T1, Args>...> {};
  2828. } // namespace detail
  2829. } // namespace nlohmann
  2830. // #include <nlohmann/detail/value_t.hpp>
  2831. #include <array> // array
  2832. #include <cstddef> // size_t
  2833. #include <cstdint> // uint8_t
  2834. #include <string> // string
  2835. namespace nlohmann
  2836. {
  2837. namespace detail
  2838. {
  2839. ///////////////////////////
  2840. // JSON type enumeration //
  2841. ///////////////////////////
  2842. /*!
  2843. @brief the JSON type enumeration
  2844. This enumeration collects the different JSON types. It is internally used to
  2845. distinguish the stored values, and the functions @ref basic_json::is_null(),
  2846. @ref basic_json::is_object(), @ref basic_json::is_array(),
  2847. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  2848. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  2849. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  2850. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  2851. @ref basic_json::is_structured() rely on it.
  2852. @note There are three enumeration entries (number_integer, number_unsigned, and
  2853. number_float), because the library distinguishes these three types for numbers:
  2854. @ref basic_json::number_unsigned_t is used for unsigned integers,
  2855. @ref basic_json::number_integer_t is used for signed integers, and
  2856. @ref basic_json::number_float_t is used for floating-point numbers or to
  2857. approximate integers which do not fit in the limits of their respective type.
  2858. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  2859. value with the default value for a given type
  2860. @since version 1.0.0
  2861. */
  2862. enum class value_t : std::uint8_t
  2863. {
  2864. null, ///< null value
  2865. object, ///< object (unordered set of name/value pairs)
  2866. array, ///< array (ordered collection of values)
  2867. string, ///< string value
  2868. boolean, ///< boolean value
  2869. number_integer, ///< number value (signed integer)
  2870. number_unsigned, ///< number value (unsigned integer)
  2871. number_float, ///< number value (floating-point)
  2872. binary, ///< binary array (ordered collection of bytes)
  2873. discarded ///< discarded by the parser callback function
  2874. };
  2875. /*!
  2876. @brief comparison operator for JSON types
  2877. Returns an ordering that is similar to Python:
  2878. - order: null < boolean < number < object < array < string < binary
  2879. - furthermore, each type is not smaller than itself
  2880. - discarded values are not comparable
  2881. - binary is represented as a b"" string in python and directly comparable to a
  2882. string; however, making a binary array directly comparable with a string would
  2883. be surprising behavior in a JSON file.
  2884. @since version 1.0.0
  2885. */
  2886. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  2887. {
  2888. static constexpr std::array<std::uint8_t, 9> order = {{
  2889. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  2890. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */,
  2891. 6 /* binary */
  2892. }
  2893. };
  2894. const auto l_index = static_cast<std::size_t>(lhs);
  2895. const auto r_index = static_cast<std::size_t>(rhs);
  2896. return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index];
  2897. }
  2898. } // namespace detail
  2899. } // namespace nlohmann
  2900. namespace nlohmann
  2901. {
  2902. namespace detail
  2903. {
  2904. template<typename BasicJsonType>
  2905. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  2906. {
  2907. if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
  2908. {
  2909. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  2910. }
  2911. n = nullptr;
  2912. }
  2913. // overloads for basic_json template parameters
  2914. template < typename BasicJsonType, typename ArithmeticType,
  2915. enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
  2916. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  2917. int > = 0 >
  2918. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  2919. {
  2920. switch (static_cast<value_t>(j))
  2921. {
  2922. case value_t::number_unsigned:
  2923. {
  2924. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  2925. break;
  2926. }
  2927. case value_t::number_integer:
  2928. {
  2929. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  2930. break;
  2931. }
  2932. case value_t::number_float:
  2933. {
  2934. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  2935. break;
  2936. }
  2937. default:
  2938. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  2939. }
  2940. }
  2941. template<typename BasicJsonType>
  2942. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  2943. {
  2944. if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
  2945. {
  2946. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  2947. }
  2948. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  2949. }
  2950. template<typename BasicJsonType>
  2951. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  2952. {
  2953. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  2954. {
  2955. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2956. }
  2957. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2958. }
  2959. template <
  2960. typename BasicJsonType, typename ConstructibleStringType,
  2961. enable_if_t <
  2962. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value&&
  2963. !std::is_same<typename BasicJsonType::string_t,
  2964. ConstructibleStringType>::value,
  2965. int > = 0 >
  2966. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  2967. {
  2968. if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
  2969. {
  2970. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  2971. }
  2972. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  2973. }
  2974. template<typename BasicJsonType>
  2975. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  2976. {
  2977. get_arithmetic_value(j, val);
  2978. }
  2979. template<typename BasicJsonType>
  2980. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  2981. {
  2982. get_arithmetic_value(j, val);
  2983. }
  2984. template<typename BasicJsonType>
  2985. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  2986. {
  2987. get_arithmetic_value(j, val);
  2988. }
  2989. template<typename BasicJsonType, typename EnumType,
  2990. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  2991. void from_json(const BasicJsonType& j, EnumType& e)
  2992. {
  2993. typename std::underlying_type<EnumType>::type val;
  2994. get_arithmetic_value(j, val);
  2995. e = static_cast<EnumType>(val);
  2996. }
  2997. // forward_list doesn't have an insert method
  2998. template<typename BasicJsonType, typename T, typename Allocator,
  2999. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  3000. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  3001. {
  3002. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3003. {
  3004. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3005. }
  3006. l.clear();
  3007. std::transform(j.rbegin(), j.rend(),
  3008. std::front_inserter(l), [](const BasicJsonType & i)
  3009. {
  3010. return i.template get<T>();
  3011. });
  3012. }
  3013. // valarray doesn't have an insert method
  3014. template<typename BasicJsonType, typename T,
  3015. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  3016. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  3017. {
  3018. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3019. {
  3020. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3021. }
  3022. l.resize(j.size());
  3023. std::copy(j.begin(), j.end(), std::begin(l));
  3024. }
  3025. template<typename BasicJsonType, typename T, std::size_t N>
  3026. auto from_json(const BasicJsonType& j, T (&arr)[N])
  3027. -> decltype(j.template get<T>(), void())
  3028. {
  3029. for (std::size_t i = 0; i < N; ++i)
  3030. {
  3031. arr[i] = j.at(i).template get<T>();
  3032. }
  3033. }
  3034. template<typename BasicJsonType>
  3035. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  3036. {
  3037. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  3038. }
  3039. template<typename BasicJsonType, typename T, std::size_t N>
  3040. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  3041. priority_tag<2> /*unused*/)
  3042. -> decltype(j.template get<T>(), void())
  3043. {
  3044. for (std::size_t i = 0; i < N; ++i)
  3045. {
  3046. arr[i] = j.at(i).template get<T>();
  3047. }
  3048. }
  3049. template<typename BasicJsonType, typename ConstructibleArrayType>
  3050. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  3051. -> decltype(
  3052. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  3053. j.template get<typename ConstructibleArrayType::value_type>(),
  3054. void())
  3055. {
  3056. using std::end;
  3057. ConstructibleArrayType ret;
  3058. ret.reserve(j.size());
  3059. std::transform(j.begin(), j.end(),
  3060. std::inserter(ret, end(ret)), [](const BasicJsonType & i)
  3061. {
  3062. // get<BasicJsonType>() returns *this, this won't call a from_json
  3063. // method when value_type is BasicJsonType
  3064. return i.template get<typename ConstructibleArrayType::value_type>();
  3065. });
  3066. arr = std::move(ret);
  3067. }
  3068. template<typename BasicJsonType, typename ConstructibleArrayType>
  3069. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  3070. priority_tag<0> /*unused*/)
  3071. {
  3072. using std::end;
  3073. ConstructibleArrayType ret;
  3074. std::transform(
  3075. j.begin(), j.end(), std::inserter(ret, end(ret)),
  3076. [](const BasicJsonType & i)
  3077. {
  3078. // get<BasicJsonType>() returns *this, this won't call a from_json
  3079. // method when value_type is BasicJsonType
  3080. return i.template get<typename ConstructibleArrayType::value_type>();
  3081. });
  3082. arr = std::move(ret);
  3083. }
  3084. template < typename BasicJsonType, typename ConstructibleArrayType,
  3085. enable_if_t <
  3086. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
  3087. !is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
  3088. !is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
  3089. !std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
  3090. !is_basic_json<ConstructibleArrayType>::value,
  3091. int > = 0 >
  3092. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  3093. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  3094. j.template get<typename ConstructibleArrayType::value_type>(),
  3095. void())
  3096. {
  3097. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3098. {
  3099. JSON_THROW(type_error::create(302, "type must be array, but is " +
  3100. std::string(j.type_name())));
  3101. }
  3102. from_json_array_impl(j, arr, priority_tag<3> {});
  3103. }
  3104. template<typename BasicJsonType>
  3105. void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
  3106. {
  3107. if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
  3108. {
  3109. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name())));
  3110. }
  3111. bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
  3112. }
  3113. template<typename BasicJsonType, typename ConstructibleObjectType,
  3114. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  3115. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  3116. {
  3117. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  3118. {
  3119. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  3120. }
  3121. ConstructibleObjectType ret;
  3122. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  3123. using value_type = typename ConstructibleObjectType::value_type;
  3124. std::transform(
  3125. inner_object->begin(), inner_object->end(),
  3126. std::inserter(ret, ret.begin()),
  3127. [](typename BasicJsonType::object_t::value_type const & p)
  3128. {
  3129. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  3130. });
  3131. obj = std::move(ret);
  3132. }
  3133. // overload for arithmetic types, not chosen for basic_json template arguments
  3134. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  3135. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  3136. // an arithmetic type?
  3137. template < typename BasicJsonType, typename ArithmeticType,
  3138. enable_if_t <
  3139. std::is_arithmetic<ArithmeticType>::value&&
  3140. !std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
  3141. !std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
  3142. !std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
  3143. !std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  3144. int > = 0 >
  3145. void from_json(const BasicJsonType& j, ArithmeticType& val)
  3146. {
  3147. switch (static_cast<value_t>(j))
  3148. {
  3149. case value_t::number_unsigned:
  3150. {
  3151. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  3152. break;
  3153. }
  3154. case value_t::number_integer:
  3155. {
  3156. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  3157. break;
  3158. }
  3159. case value_t::number_float:
  3160. {
  3161. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  3162. break;
  3163. }
  3164. case value_t::boolean:
  3165. {
  3166. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  3167. break;
  3168. }
  3169. default:
  3170. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  3171. }
  3172. }
  3173. template<typename BasicJsonType, typename A1, typename A2>
  3174. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  3175. {
  3176. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  3177. }
  3178. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3179. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  3180. {
  3181. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  3182. }
  3183. template<typename BasicJsonType, typename... Args>
  3184. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  3185. {
  3186. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  3187. }
  3188. template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  3189. typename = enable_if_t < !std::is_constructible <
  3190. typename BasicJsonType::string_t, Key >::value >>
  3191. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  3192. {
  3193. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3194. {
  3195. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3196. }
  3197. m.clear();
  3198. for (const auto& p : j)
  3199. {
  3200. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3201. {
  3202. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3203. }
  3204. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3205. }
  3206. }
  3207. template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  3208. typename = enable_if_t < !std::is_constructible <
  3209. typename BasicJsonType::string_t, Key >::value >>
  3210. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  3211. {
  3212. if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
  3213. {
  3214. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  3215. }
  3216. m.clear();
  3217. for (const auto& p : j)
  3218. {
  3219. if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
  3220. {
  3221. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  3222. }
  3223. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  3224. }
  3225. }
  3226. struct from_json_fn
  3227. {
  3228. template<typename BasicJsonType, typename T>
  3229. auto operator()(const BasicJsonType& j, T& val) const
  3230. noexcept(noexcept(from_json(j, val)))
  3231. -> decltype(from_json(j, val), void())
  3232. {
  3233. return from_json(j, val);
  3234. }
  3235. };
  3236. } // namespace detail
  3237. /// namespace to hold default `from_json` function
  3238. /// to see why this is required:
  3239. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  3240. namespace
  3241. {
  3242. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  3243. } // namespace
  3244. } // namespace nlohmann
  3245. // #include <nlohmann/detail/conversions/to_json.hpp>
  3246. #include <algorithm> // copy
  3247. #include <iterator> // begin, end
  3248. #include <string> // string
  3249. #include <tuple> // tuple, get
  3250. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  3251. #include <utility> // move, forward, declval, pair
  3252. #include <valarray> // valarray
  3253. #include <vector> // vector
  3254. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  3255. #include <cstddef> // size_t
  3256. #include <iterator> // input_iterator_tag
  3257. #include <string> // string, to_string
  3258. #include <tuple> // tuple_size, get, tuple_element
  3259. // #include <nlohmann/detail/meta/type_traits.hpp>
  3260. // #include <nlohmann/detail/value_t.hpp>
  3261. namespace nlohmann
  3262. {
  3263. namespace detail
  3264. {
  3265. template<typename string_type>
  3266. void int_to_string( string_type& target, std::size_t value )
  3267. {
  3268. // For ADL
  3269. using std::to_string;
  3270. target = to_string(value);
  3271. }
  3272. template<typename IteratorType> class iteration_proxy_value
  3273. {
  3274. public:
  3275. using difference_type = std::ptrdiff_t;
  3276. using value_type = iteration_proxy_value;
  3277. using pointer = value_type * ;
  3278. using reference = value_type & ;
  3279. using iterator_category = std::input_iterator_tag;
  3280. using string_type = typename std::remove_cv< typename std::remove_reference<decltype( std::declval<IteratorType>().key() ) >::type >::type;
  3281. private:
  3282. /// the iterator
  3283. IteratorType anchor;
  3284. /// an index for arrays (used to create key names)
  3285. std::size_t array_index = 0;
  3286. /// last stringified array index
  3287. mutable std::size_t array_index_last = 0;
  3288. /// a string representation of the array index
  3289. mutable string_type array_index_str = "0";
  3290. /// an empty string (to return a reference for primitive values)
  3291. const string_type empty_str = "";
  3292. public:
  3293. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  3294. /// dereference operator (needed for range-based for)
  3295. iteration_proxy_value& operator*()
  3296. {
  3297. return *this;
  3298. }
  3299. /// increment operator (needed for range-based for)
  3300. iteration_proxy_value& operator++()
  3301. {
  3302. ++anchor;
  3303. ++array_index;
  3304. return *this;
  3305. }
  3306. /// equality operator (needed for InputIterator)
  3307. bool operator==(const iteration_proxy_value& o) const
  3308. {
  3309. return anchor == o.anchor;
  3310. }
  3311. /// inequality operator (needed for range-based for)
  3312. bool operator!=(const iteration_proxy_value& o) const
  3313. {
  3314. return anchor != o.anchor;
  3315. }
  3316. /// return key of the iterator
  3317. const string_type& key() const
  3318. {
  3319. JSON_ASSERT(anchor.m_object != nullptr);
  3320. switch (anchor.m_object->type())
  3321. {
  3322. // use integer array index as key
  3323. case value_t::array:
  3324. {
  3325. if (array_index != array_index_last)
  3326. {
  3327. int_to_string( array_index_str, array_index );
  3328. array_index_last = array_index;
  3329. }
  3330. return array_index_str;
  3331. }
  3332. // use key from the object
  3333. case value_t::object:
  3334. return anchor.key();
  3335. // use an empty key for all primitive types
  3336. default:
  3337. return empty_str;
  3338. }
  3339. }
  3340. /// return value of the iterator
  3341. typename IteratorType::reference value() const
  3342. {
  3343. return anchor.value();
  3344. }
  3345. };
  3346. /// proxy class for the items() function
  3347. template<typename IteratorType> class iteration_proxy
  3348. {
  3349. private:
  3350. /// the container to iterate
  3351. typename IteratorType::reference container;
  3352. public:
  3353. /// construct iteration proxy from a container
  3354. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  3355. : container(cont) {}
  3356. /// return iterator begin (needed for range-based for)
  3357. iteration_proxy_value<IteratorType> begin() noexcept
  3358. {
  3359. return iteration_proxy_value<IteratorType>(container.begin());
  3360. }
  3361. /// return iterator end (needed for range-based for)
  3362. iteration_proxy_value<IteratorType> end() noexcept
  3363. {
  3364. return iteration_proxy_value<IteratorType>(container.end());
  3365. }
  3366. };
  3367. // Structured Bindings Support
  3368. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3369. // And see https://github.com/nlohmann/json/pull/1391
  3370. template<std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  3371. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  3372. {
  3373. return i.key();
  3374. }
  3375. // Structured Bindings Support
  3376. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3377. // And see https://github.com/nlohmann/json/pull/1391
  3378. template<std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  3379. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  3380. {
  3381. return i.value();
  3382. }
  3383. } // namespace detail
  3384. } // namespace nlohmann
  3385. // The Addition to the STD Namespace is required to add
  3386. // Structured Bindings Support to the iteration_proxy_value class
  3387. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  3388. // And see https://github.com/nlohmann/json/pull/1391
  3389. namespace std
  3390. {
  3391. #if defined(__clang__)
  3392. // Fix: https://github.com/nlohmann/json/issues/1401
  3393. #pragma clang diagnostic push
  3394. #pragma clang diagnostic ignored "-Wmismatched-tags"
  3395. #endif
  3396. template<typename IteratorType>
  3397. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  3398. : public std::integral_constant<std::size_t, 2> {};
  3399. template<std::size_t N, typename IteratorType>
  3400. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  3401. {
  3402. public:
  3403. using type = decltype(
  3404. get<N>(std::declval <
  3405. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  3406. };
  3407. #if defined(__clang__)
  3408. #pragma clang diagnostic pop
  3409. #endif
  3410. } // namespace std
  3411. // #include <nlohmann/detail/meta/cpp_future.hpp>
  3412. // #include <nlohmann/detail/meta/type_traits.hpp>
  3413. // #include <nlohmann/detail/value_t.hpp>
  3414. namespace nlohmann
  3415. {
  3416. namespace detail
  3417. {
  3418. //////////////////
  3419. // constructors //
  3420. //////////////////
  3421. template<value_t> struct external_constructor;
  3422. template<>
  3423. struct external_constructor<value_t::boolean>
  3424. {
  3425. template<typename BasicJsonType>
  3426. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  3427. {
  3428. j.m_type = value_t::boolean;
  3429. j.m_value = b;
  3430. j.assert_invariant();
  3431. }
  3432. };
  3433. template<>
  3434. struct external_constructor<value_t::string>
  3435. {
  3436. template<typename BasicJsonType>
  3437. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  3438. {
  3439. j.m_type = value_t::string;
  3440. j.m_value = s;
  3441. j.assert_invariant();
  3442. }
  3443. template<typename BasicJsonType>
  3444. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3445. {
  3446. j.m_type = value_t::string;
  3447. j.m_value = std::move(s);
  3448. j.assert_invariant();
  3449. }
  3450. template < typename BasicJsonType, typename CompatibleStringType,
  3451. enable_if_t < !std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  3452. int > = 0 >
  3453. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  3454. {
  3455. j.m_type = value_t::string;
  3456. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  3457. j.assert_invariant();
  3458. }
  3459. };
  3460. template<>
  3461. struct external_constructor<value_t::binary>
  3462. {
  3463. template<typename BasicJsonType>
  3464. static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b)
  3465. {
  3466. j.m_type = value_t::binary;
  3467. typename BasicJsonType::binary_t value{b};
  3468. j.m_value = value;
  3469. j.assert_invariant();
  3470. }
  3471. template<typename BasicJsonType>
  3472. static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b)
  3473. {
  3474. j.m_type = value_t::binary;
  3475. typename BasicJsonType::binary_t value{std::move(b)};
  3476. j.m_value = value;
  3477. j.assert_invariant();
  3478. }
  3479. };
  3480. template<>
  3481. struct external_constructor<value_t::number_float>
  3482. {
  3483. template<typename BasicJsonType>
  3484. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  3485. {
  3486. j.m_type = value_t::number_float;
  3487. j.m_value = val;
  3488. j.assert_invariant();
  3489. }
  3490. };
  3491. template<>
  3492. struct external_constructor<value_t::number_unsigned>
  3493. {
  3494. template<typename BasicJsonType>
  3495. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  3496. {
  3497. j.m_type = value_t::number_unsigned;
  3498. j.m_value = val;
  3499. j.assert_invariant();
  3500. }
  3501. };
  3502. template<>
  3503. struct external_constructor<value_t::number_integer>
  3504. {
  3505. template<typename BasicJsonType>
  3506. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  3507. {
  3508. j.m_type = value_t::number_integer;
  3509. j.m_value = val;
  3510. j.assert_invariant();
  3511. }
  3512. };
  3513. template<>
  3514. struct external_constructor<value_t::array>
  3515. {
  3516. template<typename BasicJsonType>
  3517. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  3518. {
  3519. j.m_type = value_t::array;
  3520. j.m_value = arr;
  3521. j.assert_invariant();
  3522. }
  3523. template<typename BasicJsonType>
  3524. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3525. {
  3526. j.m_type = value_t::array;
  3527. j.m_value = std::move(arr);
  3528. j.assert_invariant();
  3529. }
  3530. template < typename BasicJsonType, typename CompatibleArrayType,
  3531. enable_if_t < !std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  3532. int > = 0 >
  3533. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  3534. {
  3535. using std::begin;
  3536. using std::end;
  3537. j.m_type = value_t::array;
  3538. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  3539. j.assert_invariant();
  3540. }
  3541. template<typename BasicJsonType>
  3542. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  3543. {
  3544. j.m_type = value_t::array;
  3545. j.m_value = value_t::array;
  3546. j.m_value.array->reserve(arr.size());
  3547. for (const bool x : arr)
  3548. {
  3549. j.m_value.array->push_back(x);
  3550. }
  3551. j.assert_invariant();
  3552. }
  3553. template<typename BasicJsonType, typename T,
  3554. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3555. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  3556. {
  3557. j.m_type = value_t::array;
  3558. j.m_value = value_t::array;
  3559. j.m_value.array->resize(arr.size());
  3560. if (arr.size() > 0)
  3561. {
  3562. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  3563. }
  3564. j.assert_invariant();
  3565. }
  3566. };
  3567. template<>
  3568. struct external_constructor<value_t::object>
  3569. {
  3570. template<typename BasicJsonType>
  3571. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  3572. {
  3573. j.m_type = value_t::object;
  3574. j.m_value = obj;
  3575. j.assert_invariant();
  3576. }
  3577. template<typename BasicJsonType>
  3578. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3579. {
  3580. j.m_type = value_t::object;
  3581. j.m_value = std::move(obj);
  3582. j.assert_invariant();
  3583. }
  3584. template < typename BasicJsonType, typename CompatibleObjectType,
  3585. enable_if_t < !std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int > = 0 >
  3586. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  3587. {
  3588. using std::begin;
  3589. using std::end;
  3590. j.m_type = value_t::object;
  3591. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  3592. j.assert_invariant();
  3593. }
  3594. };
  3595. /////////////
  3596. // to_json //
  3597. /////////////
  3598. template<typename BasicJsonType, typename T,
  3599. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  3600. void to_json(BasicJsonType& j, T b) noexcept
  3601. {
  3602. external_constructor<value_t::boolean>::construct(j, b);
  3603. }
  3604. template<typename BasicJsonType, typename CompatibleString,
  3605. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  3606. void to_json(BasicJsonType& j, const CompatibleString& s)
  3607. {
  3608. external_constructor<value_t::string>::construct(j, s);
  3609. }
  3610. template<typename BasicJsonType>
  3611. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  3612. {
  3613. external_constructor<value_t::string>::construct(j, std::move(s));
  3614. }
  3615. template<typename BasicJsonType, typename FloatType,
  3616. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  3617. void to_json(BasicJsonType& j, FloatType val) noexcept
  3618. {
  3619. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  3620. }
  3621. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  3622. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  3623. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  3624. {
  3625. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  3626. }
  3627. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  3628. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  3629. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  3630. {
  3631. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  3632. }
  3633. template<typename BasicJsonType, typename EnumType,
  3634. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  3635. void to_json(BasicJsonType& j, EnumType e) noexcept
  3636. {
  3637. using underlying_type = typename std::underlying_type<EnumType>::type;
  3638. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  3639. }
  3640. template<typename BasicJsonType>
  3641. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  3642. {
  3643. external_constructor<value_t::array>::construct(j, e);
  3644. }
  3645. template < typename BasicJsonType, typename CompatibleArrayType,
  3646. enable_if_t < is_compatible_array_type<BasicJsonType,
  3647. CompatibleArrayType>::value&&
  3648. !is_compatible_object_type<BasicJsonType, CompatibleArrayType>::value&&
  3649. !is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value&&
  3650. !std::is_same<typename BasicJsonType::binary_t, CompatibleArrayType>::value&&
  3651. !is_basic_json<CompatibleArrayType>::value,
  3652. int > = 0 >
  3653. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  3654. {
  3655. external_constructor<value_t::array>::construct(j, arr);
  3656. }
  3657. template<typename BasicJsonType>
  3658. void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin)
  3659. {
  3660. external_constructor<value_t::binary>::construct(j, bin);
  3661. }
  3662. template<typename BasicJsonType, typename T,
  3663. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  3664. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  3665. {
  3666. external_constructor<value_t::array>::construct(j, std::move(arr));
  3667. }
  3668. template<typename BasicJsonType>
  3669. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  3670. {
  3671. external_constructor<value_t::array>::construct(j, std::move(arr));
  3672. }
  3673. template < typename BasicJsonType, typename CompatibleObjectType,
  3674. enable_if_t < is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value&& !is_basic_json<CompatibleObjectType>::value, int > = 0 >
  3675. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  3676. {
  3677. external_constructor<value_t::object>::construct(j, obj);
  3678. }
  3679. template<typename BasicJsonType>
  3680. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  3681. {
  3682. external_constructor<value_t::object>::construct(j, std::move(obj));
  3683. }
  3684. template <
  3685. typename BasicJsonType, typename T, std::size_t N,
  3686. enable_if_t < !std::is_constructible<typename BasicJsonType::string_t,
  3687. const T(&)[N]>::value,
  3688. int > = 0 >
  3689. void to_json(BasicJsonType& j, const T(&arr)[N])
  3690. {
  3691. external_constructor<value_t::array>::construct(j, arr);
  3692. }
  3693. template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible<BasicJsonType, T1>::value&& std::is_constructible<BasicJsonType, T2>::value, int > = 0 >
  3694. void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
  3695. {
  3696. j = { p.first, p.second };
  3697. }
  3698. // for https://github.com/nlohmann/json/pull/1134
  3699. template<typename BasicJsonType, typename T,
  3700. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  3701. void to_json(BasicJsonType& j, const T& b)
  3702. {
  3703. j = { {b.key(), b.value()} };
  3704. }
  3705. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  3706. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  3707. {
  3708. j = { std::get<Idx>(t)... };
  3709. }
  3710. template<typename BasicJsonType, typename T, enable_if_t<is_constructible_tuple<BasicJsonType, T>::value, int > = 0>
  3711. void to_json(BasicJsonType& j, const T& t)
  3712. {
  3713. to_json_tuple_impl(j, t, make_index_sequence<std::tuple_size<T>::value> {});
  3714. }
  3715. struct to_json_fn
  3716. {
  3717. template<typename BasicJsonType, typename T>
  3718. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  3719. -> decltype(to_json(j, std::forward<T>(val)), void())
  3720. {
  3721. return to_json(j, std::forward<T>(val));
  3722. }
  3723. };
  3724. } // namespace detail
  3725. /// namespace to hold default `to_json` function
  3726. namespace
  3727. {
  3728. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  3729. } // namespace
  3730. } // namespace nlohmann
  3731. namespace nlohmann
  3732. {
  3733. template<typename, typename>
  3734. struct adl_serializer
  3735. {
  3736. /*!
  3737. @brief convert a JSON value to any value type
  3738. This function is usually called by the `get()` function of the
  3739. @ref basic_json class (either explicit or via conversion operators).
  3740. @param[in] j JSON value to read from
  3741. @param[in,out] val value to write to
  3742. */
  3743. template<typename BasicJsonType, typename ValueType>
  3744. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  3745. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  3746. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  3747. {
  3748. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  3749. }
  3750. /*!
  3751. @brief convert any value type to a JSON value
  3752. This function is usually called by the constructors of the @ref basic_json
  3753. class.
  3754. @param[in,out] j JSON value to write to
  3755. @param[in] val value to read from
  3756. */
  3757. template<typename BasicJsonType, typename ValueType>
  3758. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  3759. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  3760. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  3761. {
  3762. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  3763. }
  3764. };
  3765. } // namespace nlohmann
  3766. // #include <nlohmann/byte_container_with_subtype.hpp>
  3767. #include <cstdint> // uint8_t
  3768. #include <tuple> // tie
  3769. #include <utility> // move
  3770. namespace nlohmann
  3771. {
  3772. /*!
  3773. @brief an internal type for a backed binary type
  3774. This type extends the template parameter @a BinaryType provided to `basic_json`
  3775. with a subtype used by BSON and MessagePack. This type exists so that the user
  3776. does not have to specify a type themselves with a specific naming scheme in
  3777. order to override the binary type.
  3778. @tparam BinaryType container to store bytes (`std::vector<std::uint8_t>` by
  3779. default)
  3780. @since version 3.8.0
  3781. */
  3782. template<typename BinaryType>
  3783. class byte_container_with_subtype : public BinaryType
  3784. {
  3785. public:
  3786. /// the type of the underlying container
  3787. using container_type = BinaryType;
  3788. byte_container_with_subtype() noexcept(noexcept(container_type()))
  3789. : container_type()
  3790. {}
  3791. byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b)))
  3792. : container_type(b)
  3793. {}
  3794. byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b))))
  3795. : container_type(std::move(b))
  3796. {}
  3797. byte_container_with_subtype(const container_type& b, std::uint8_t subtype) noexcept(noexcept(container_type(b)))
  3798. : container_type(b)
  3799. , m_subtype(subtype)
  3800. , m_has_subtype(true)
  3801. {}
  3802. byte_container_with_subtype(container_type&& b, std::uint8_t subtype) noexcept(noexcept(container_type(std::move(b))))
  3803. : container_type(std::move(b))
  3804. , m_subtype(subtype)
  3805. , m_has_subtype(true)
  3806. {}
  3807. bool operator==(const byte_container_with_subtype& rhs) const
  3808. {
  3809. return std::tie(static_cast<const BinaryType&>(*this), m_subtype, m_has_subtype) ==
  3810. std::tie(static_cast<const BinaryType&>(rhs), rhs.m_subtype, rhs.m_has_subtype);
  3811. }
  3812. bool operator!=(const byte_container_with_subtype& rhs) const
  3813. {
  3814. return !(rhs == *this);
  3815. }
  3816. /*!
  3817. @brief sets the binary subtype
  3818. Sets the binary subtype of the value, also flags a binary JSON value as
  3819. having a subtype, which has implications for serialization.
  3820. @complexity Constant.
  3821. @exceptionsafety No-throw guarantee: this member function never throws
  3822. exceptions.
  3823. @sa @ref subtype() -- return the binary subtype
  3824. @sa @ref clear_subtype() -- clears the binary subtype
  3825. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3826. subtype
  3827. @since version 3.8.0
  3828. */
  3829. void set_subtype(std::uint8_t subtype) noexcept
  3830. {
  3831. m_subtype = subtype;
  3832. m_has_subtype = true;
  3833. }
  3834. /*!
  3835. @brief return the binary subtype
  3836. Returns the numerical subtype of the value if it has a subtype. If it does
  3837. not have a subtype, this function will return size_t(-1) as a sentinel
  3838. value.
  3839. @return the numerical subtype of the binary value
  3840. @complexity Constant.
  3841. @exceptionsafety No-throw guarantee: this member function never throws
  3842. exceptions.
  3843. @sa @ref set_subtype() -- sets the binary subtype
  3844. @sa @ref clear_subtype() -- clears the binary subtype
  3845. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3846. subtype
  3847. @since version 3.8.0
  3848. */
  3849. constexpr std::uint8_t subtype() const noexcept
  3850. {
  3851. return m_subtype;
  3852. }
  3853. /*!
  3854. @brief return whether the value has a subtype
  3855. @return whether the value has a subtype
  3856. @complexity Constant.
  3857. @exceptionsafety No-throw guarantee: this member function never throws
  3858. exceptions.
  3859. @sa @ref subtype() -- return the binary subtype
  3860. @sa @ref set_subtype() -- sets the binary subtype
  3861. @sa @ref clear_subtype() -- clears the binary subtype
  3862. @since version 3.8.0
  3863. */
  3864. constexpr bool has_subtype() const noexcept
  3865. {
  3866. return m_has_subtype;
  3867. }
  3868. /*!
  3869. @brief clears the binary subtype
  3870. Clears the binary subtype and flags the value as not having a subtype, which
  3871. has implications for serialization; for instance MessagePack will prefer the
  3872. bin family over the ext family.
  3873. @complexity Constant.
  3874. @exceptionsafety No-throw guarantee: this member function never throws
  3875. exceptions.
  3876. @sa @ref subtype() -- return the binary subtype
  3877. @sa @ref set_subtype() -- sets the binary subtype
  3878. @sa @ref has_subtype() -- returns whether or not the binary value has a
  3879. subtype
  3880. @since version 3.8.0
  3881. */
  3882. void clear_subtype() noexcept
  3883. {
  3884. m_subtype = 0;
  3885. m_has_subtype = false;
  3886. }
  3887. private:
  3888. std::uint8_t m_subtype = 0;
  3889. bool m_has_subtype = false;
  3890. };
  3891. } // namespace nlohmann
  3892. // #include <nlohmann/detail/conversions/from_json.hpp>
  3893. // #include <nlohmann/detail/conversions/to_json.hpp>
  3894. // #include <nlohmann/detail/exceptions.hpp>
  3895. // #include <nlohmann/detail/input/binary_reader.hpp>
  3896. #include <algorithm> // generate_n
  3897. #include <array> // array
  3898. #include <cmath> // ldexp
  3899. #include <cstddef> // size_t
  3900. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  3901. #include <cstdio> // snprintf
  3902. #include <cstring> // memcpy
  3903. #include <iterator> // back_inserter
  3904. #include <limits> // numeric_limits
  3905. #include <string> // char_traits, string
  3906. #include <utility> // make_pair, move
  3907. // #include <nlohmann/detail/exceptions.hpp>
  3908. // #include <nlohmann/detail/input/input_adapters.hpp>
  3909. #include <array> // array
  3910. #include <cstddef> // size_t
  3911. #include <cstdio> //FILE *
  3912. #include <cstring> // strlen
  3913. #include <istream> // istream
  3914. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  3915. #include <memory> // shared_ptr, make_shared, addressof
  3916. #include <numeric> // accumulate
  3917. #include <string> // string, char_traits
  3918. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  3919. #include <utility> // pair, declval
  3920. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  3921. // #include <nlohmann/detail/macro_scope.hpp>
  3922. namespace nlohmann
  3923. {
  3924. namespace detail
  3925. {
  3926. /// the supported input formats
  3927. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  3928. ////////////////////
  3929. // input adapters //
  3930. ////////////////////
  3931. /*!
  3932. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  3933. buffer. This adapter is a very low level adapter.
  3934. */
  3935. class file_input_adapter
  3936. {
  3937. public:
  3938. using char_type = char;
  3939. JSON_HEDLEY_NON_NULL(2)
  3940. explicit file_input_adapter(std::FILE* f) noexcept
  3941. : m_file(f)
  3942. {}
  3943. // make class move-only
  3944. file_input_adapter(const file_input_adapter&) = delete;
  3945. file_input_adapter(file_input_adapter&&) = default;
  3946. file_input_adapter& operator=(const file_input_adapter&) = delete;
  3947. file_input_adapter& operator=(file_input_adapter&&) = delete;
  3948. std::char_traits<char>::int_type get_character() noexcept
  3949. {
  3950. return std::fgetc(m_file);
  3951. }
  3952. private:
  3953. /// the file pointer to read from
  3954. std::FILE* m_file;
  3955. };
  3956. /*!
  3957. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  3958. beginning of input. Does not support changing the underlying std::streambuf
  3959. in mid-input. Maintains underlying std::istream and std::streambuf to support
  3960. subsequent use of standard std::istream operations to process any input
  3961. characters following those used in parsing the JSON input. Clears the
  3962. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  3963. subsequent call for input from the std::istream.
  3964. */
  3965. class input_stream_adapter
  3966. {
  3967. public:
  3968. using char_type = char;
  3969. ~input_stream_adapter()
  3970. {
  3971. // clear stream flags; we use underlying streambuf I/O, do not
  3972. // maintain ifstream flags, except eof
  3973. if (is != nullptr)
  3974. {
  3975. is->clear(is->rdstate() & std::ios::eofbit);
  3976. }
  3977. }
  3978. explicit input_stream_adapter(std::istream& i)
  3979. : is(&i), sb(i.rdbuf())
  3980. {}
  3981. // delete because of pointer members
  3982. input_stream_adapter(const input_stream_adapter&) = delete;
  3983. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  3984. input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete;
  3985. input_stream_adapter(input_stream_adapter&& rhs) : is(rhs.is), sb(rhs.sb)
  3986. {
  3987. rhs.is = nullptr;
  3988. rhs.sb = nullptr;
  3989. }
  3990. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  3991. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  3992. // end up as the same value, eg. 0xFFFFFFFF.
  3993. std::char_traits<char>::int_type get_character()
  3994. {
  3995. auto res = sb->sbumpc();
  3996. // set eof manually, as we don't use the istream interface.
  3997. if (JSON_HEDLEY_UNLIKELY(res == EOF))
  3998. {
  3999. is->clear(is->rdstate() | std::ios::eofbit);
  4000. }
  4001. return res;
  4002. }
  4003. private:
  4004. /// the associated input stream
  4005. std::istream* is = nullptr;
  4006. std::streambuf* sb = nullptr;
  4007. };
  4008. // General-purpose iterator-based adapter. It might not be as fast as
  4009. // theoretically possible for some containers, but it is extremely versatile.
  4010. template<typename IteratorType>
  4011. class iterator_input_adapter
  4012. {
  4013. public:
  4014. using char_type = typename std::iterator_traits<IteratorType>::value_type;
  4015. iterator_input_adapter(IteratorType first, IteratorType last)
  4016. : current(std::move(first)), end(std::move(last)) {}
  4017. typename std::char_traits<char_type>::int_type get_character()
  4018. {
  4019. if (JSON_HEDLEY_LIKELY(current != end))
  4020. {
  4021. auto result = std::char_traits<char_type>::to_int_type(*current);
  4022. std::advance(current, 1);
  4023. return result;
  4024. }
  4025. else
  4026. {
  4027. return std::char_traits<char_type>::eof();
  4028. }
  4029. }
  4030. private:
  4031. IteratorType current;
  4032. IteratorType end;
  4033. template<typename BaseInputAdapter, size_t T>
  4034. friend struct wide_string_input_helper;
  4035. bool empty() const
  4036. {
  4037. return current == end;
  4038. }
  4039. };
  4040. template<typename BaseInputAdapter, size_t T>
  4041. struct wide_string_input_helper;
  4042. template<typename BaseInputAdapter>
  4043. struct wide_string_input_helper<BaseInputAdapter, 4>
  4044. {
  4045. // UTF-32
  4046. static void fill_buffer(BaseInputAdapter& input,
  4047. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4048. size_t& utf8_bytes_index,
  4049. size_t& utf8_bytes_filled)
  4050. {
  4051. utf8_bytes_index = 0;
  4052. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4053. {
  4054. utf8_bytes[0] = std::char_traits<char>::eof();
  4055. utf8_bytes_filled = 1;
  4056. }
  4057. else
  4058. {
  4059. // get the current character
  4060. const auto wc = input.get_character();
  4061. // UTF-32 to UTF-8 encoding
  4062. if (wc < 0x80)
  4063. {
  4064. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4065. utf8_bytes_filled = 1;
  4066. }
  4067. else if (wc <= 0x7FF)
  4068. {
  4069. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u) & 0x1Fu));
  4070. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4071. utf8_bytes_filled = 2;
  4072. }
  4073. else if (wc <= 0xFFFF)
  4074. {
  4075. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u) & 0x0Fu));
  4076. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4077. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4078. utf8_bytes_filled = 3;
  4079. }
  4080. else if (wc <= 0x10FFFF)
  4081. {
  4082. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((static_cast<unsigned int>(wc) >> 18u) & 0x07u));
  4083. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 12u) & 0x3Fu));
  4084. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4085. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4086. utf8_bytes_filled = 4;
  4087. }
  4088. else
  4089. {
  4090. // unknown character
  4091. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4092. utf8_bytes_filled = 1;
  4093. }
  4094. }
  4095. }
  4096. };
  4097. template<typename BaseInputAdapter>
  4098. struct wide_string_input_helper<BaseInputAdapter, 2>
  4099. {
  4100. // UTF-16
  4101. static void fill_buffer(BaseInputAdapter& input,
  4102. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  4103. size_t& utf8_bytes_index,
  4104. size_t& utf8_bytes_filled)
  4105. {
  4106. utf8_bytes_index = 0;
  4107. if (JSON_HEDLEY_UNLIKELY(input.empty()))
  4108. {
  4109. utf8_bytes[0] = std::char_traits<char>::eof();
  4110. utf8_bytes_filled = 1;
  4111. }
  4112. else
  4113. {
  4114. // get the current character
  4115. const auto wc = input.get_character();
  4116. // UTF-16 to UTF-8 encoding
  4117. if (wc < 0x80)
  4118. {
  4119. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4120. utf8_bytes_filled = 1;
  4121. }
  4122. else if (wc <= 0x7FF)
  4123. {
  4124. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((static_cast<unsigned int>(wc) >> 6u)));
  4125. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4126. utf8_bytes_filled = 2;
  4127. }
  4128. else if (0xD800 > wc || wc >= 0xE000)
  4129. {
  4130. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((static_cast<unsigned int>(wc) >> 12u)));
  4131. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((static_cast<unsigned int>(wc) >> 6u) & 0x3Fu));
  4132. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (static_cast<unsigned int>(wc) & 0x3Fu));
  4133. utf8_bytes_filled = 3;
  4134. }
  4135. else
  4136. {
  4137. if (JSON_HEDLEY_UNLIKELY(!input.empty()))
  4138. {
  4139. const auto wc2 = static_cast<unsigned int>(input.get_character());
  4140. const auto charcode = 0x10000u + (((static_cast<unsigned int>(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  4141. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  4142. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  4143. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  4144. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  4145. utf8_bytes_filled = 4;
  4146. }
  4147. else
  4148. {
  4149. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  4150. utf8_bytes_filled = 1;
  4151. }
  4152. }
  4153. }
  4154. }
  4155. };
  4156. // Wraps another input apdater to convert wide character types into individual bytes.
  4157. template<typename BaseInputAdapter, typename WideCharType>
  4158. class wide_string_input_adapter
  4159. {
  4160. public:
  4161. using char_type = char;
  4162. wide_string_input_adapter(BaseInputAdapter base)
  4163. : base_adapter(base) {}
  4164. typename std::char_traits<char>::int_type get_character() noexcept
  4165. {
  4166. // check if buffer needs to be filled
  4167. if (utf8_bytes_index == utf8_bytes_filled)
  4168. {
  4169. fill_buffer<sizeof(WideCharType)>();
  4170. JSON_ASSERT(utf8_bytes_filled > 0);
  4171. JSON_ASSERT(utf8_bytes_index == 0);
  4172. }
  4173. // use buffer
  4174. JSON_ASSERT(utf8_bytes_filled > 0);
  4175. JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled);
  4176. return utf8_bytes[utf8_bytes_index++];
  4177. }
  4178. private:
  4179. BaseInputAdapter base_adapter;
  4180. template<size_t T>
  4181. void fill_buffer()
  4182. {
  4183. wide_string_input_helper<BaseInputAdapter, T>::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  4184. }
  4185. /// a buffer for UTF-8 bytes
  4186. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  4187. /// index to the utf8_codes array for the next valid byte
  4188. std::size_t utf8_bytes_index = 0;
  4189. /// number of valid bytes in the utf8_codes array
  4190. std::size_t utf8_bytes_filled = 0;
  4191. };
  4192. template<typename IteratorType, typename Enable = void>
  4193. struct iterator_input_adapter_factory
  4194. {
  4195. using iterator_type = IteratorType;
  4196. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4197. using adapter_type = iterator_input_adapter<iterator_type>;
  4198. static adapter_type create(IteratorType first, IteratorType last)
  4199. {
  4200. return adapter_type(std::move(first), std::move(last));
  4201. }
  4202. };
  4203. template<typename T>
  4204. struct is_iterator_of_multibyte
  4205. {
  4206. using value_type = typename std::iterator_traits<T>::value_type;
  4207. enum
  4208. {
  4209. value = sizeof(value_type) > 1
  4210. };
  4211. };
  4212. template<typename IteratorType>
  4213. struct iterator_input_adapter_factory<IteratorType, enable_if_t<is_iterator_of_multibyte<IteratorType>::value>>
  4214. {
  4215. using iterator_type = IteratorType;
  4216. using char_type = typename std::iterator_traits<iterator_type>::value_type;
  4217. using base_adapter_type = iterator_input_adapter<iterator_type>;
  4218. using adapter_type = wide_string_input_adapter<base_adapter_type, char_type>;
  4219. static adapter_type create(IteratorType first, IteratorType last)
  4220. {
  4221. return adapter_type(base_adapter_type(std::move(first), std::move(last)));
  4222. }
  4223. };
  4224. // General purpose iterator-based input
  4225. template<typename IteratorType>
  4226. typename iterator_input_adapter_factory<IteratorType>::adapter_type input_adapter(IteratorType first, IteratorType last)
  4227. {
  4228. using factory_type = iterator_input_adapter_factory<IteratorType>;
  4229. return factory_type::create(first, last);
  4230. }
  4231. // Convenience shorthand from container to iterator
  4232. template<typename ContainerType>
  4233. auto input_adapter(const ContainerType& container) -> decltype(input_adapter(begin(container), end(container)))
  4234. {
  4235. // Enable ADL
  4236. using std::begin;
  4237. using std::end;
  4238. return input_adapter(begin(container), end(container));
  4239. }
  4240. // Special cases with fast paths
  4241. inline file_input_adapter input_adapter(std::FILE* file)
  4242. {
  4243. return file_input_adapter(file);
  4244. }
  4245. inline input_stream_adapter input_adapter(std::istream& stream)
  4246. {
  4247. return input_stream_adapter(stream);
  4248. }
  4249. inline input_stream_adapter input_adapter(std::istream&& stream)
  4250. {
  4251. return input_stream_adapter(stream);
  4252. }
  4253. using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval<const char*>(), std::declval<const char*>()));
  4254. // Null-delimited strings, and the like.
  4255. template < typename CharT,
  4256. typename std::enable_if <
  4257. std::is_pointer<CharT>::value&&
  4258. !std::is_array<CharT>::value&&
  4259. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4260. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4261. int >::type = 0 >
  4262. contiguous_bytes_input_adapter input_adapter(CharT b)
  4263. {
  4264. auto length = std::strlen(reinterpret_cast<const char*>(b));
  4265. const auto* ptr = reinterpret_cast<const char*>(b);
  4266. return input_adapter(ptr, ptr + length);
  4267. }
  4268. template<typename T, std::size_t N>
  4269. auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N))
  4270. {
  4271. return input_adapter(array, array + N);
  4272. }
  4273. // This class only handles inputs of input_buffer_adapter type.
  4274. // It's required so that expressions like {ptr, len} can be implicitely casted
  4275. // to the correct adapter.
  4276. class span_input_adapter
  4277. {
  4278. public:
  4279. template < typename CharT,
  4280. typename std::enable_if <
  4281. std::is_pointer<CharT>::value&&
  4282. std::is_integral<typename std::remove_pointer<CharT>::type>::value&&
  4283. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  4284. int >::type = 0 >
  4285. span_input_adapter(CharT b, std::size_t l)
  4286. : ia(reinterpret_cast<const char*>(b), reinterpret_cast<const char*>(b) + l) {}
  4287. template<class IteratorType,
  4288. typename std::enable_if<
  4289. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  4290. int>::type = 0>
  4291. span_input_adapter(IteratorType first, IteratorType last)
  4292. : ia(input_adapter(first, last)) {}
  4293. contiguous_bytes_input_adapter&& get()
  4294. {
  4295. return std::move(ia);
  4296. }
  4297. private:
  4298. contiguous_bytes_input_adapter ia;
  4299. };
  4300. } // namespace detail
  4301. } // namespace nlohmann
  4302. // #include <nlohmann/detail/input/json_sax.hpp>
  4303. #include <cstddef>
  4304. #include <string> // string
  4305. #include <utility> // move
  4306. #include <vector> // vector
  4307. // #include <nlohmann/detail/exceptions.hpp>
  4308. // #include <nlohmann/detail/macro_scope.hpp>
  4309. namespace nlohmann
  4310. {
  4311. /*!
  4312. @brief SAX interface
  4313. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  4314. Each function is called in different situations while the input is parsed. The
  4315. boolean return value informs the parser whether to continue processing the
  4316. input.
  4317. */
  4318. template<typename BasicJsonType>
  4319. struct json_sax
  4320. {
  4321. using number_integer_t = typename BasicJsonType::number_integer_t;
  4322. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4323. using number_float_t = typename BasicJsonType::number_float_t;
  4324. using string_t = typename BasicJsonType::string_t;
  4325. using binary_t = typename BasicJsonType::binary_t;
  4326. /*!
  4327. @brief a null value was read
  4328. @return whether parsing should proceed
  4329. */
  4330. virtual bool null() = 0;
  4331. /*!
  4332. @brief a boolean value was read
  4333. @param[in] val boolean value
  4334. @return whether parsing should proceed
  4335. */
  4336. virtual bool boolean(bool val) = 0;
  4337. /*!
  4338. @brief an integer number was read
  4339. @param[in] val integer value
  4340. @return whether parsing should proceed
  4341. */
  4342. virtual bool number_integer(number_integer_t val) = 0;
  4343. /*!
  4344. @brief an unsigned integer number was read
  4345. @param[in] val unsigned integer value
  4346. @return whether parsing should proceed
  4347. */
  4348. virtual bool number_unsigned(number_unsigned_t val) = 0;
  4349. /*!
  4350. @brief an floating-point number was read
  4351. @param[in] val floating-point value
  4352. @param[in] s raw token value
  4353. @return whether parsing should proceed
  4354. */
  4355. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  4356. /*!
  4357. @brief a string was read
  4358. @param[in] val string value
  4359. @return whether parsing should proceed
  4360. @note It is safe to move the passed string.
  4361. */
  4362. virtual bool string(string_t& val) = 0;
  4363. /*!
  4364. @brief a binary string was read
  4365. @param[in] val binary value
  4366. @return whether parsing should proceed
  4367. @note It is safe to move the passed binary.
  4368. */
  4369. virtual bool binary(binary_t& val) = 0;
  4370. /*!
  4371. @brief the beginning of an object was read
  4372. @param[in] elements number of object elements or -1 if unknown
  4373. @return whether parsing should proceed
  4374. @note binary formats may report the number of elements
  4375. */
  4376. virtual bool start_object(std::size_t elements) = 0;
  4377. /*!
  4378. @brief an object key was read
  4379. @param[in] val object key
  4380. @return whether parsing should proceed
  4381. @note It is safe to move the passed string.
  4382. */
  4383. virtual bool key(string_t& val) = 0;
  4384. /*!
  4385. @brief the end of an object was read
  4386. @return whether parsing should proceed
  4387. */
  4388. virtual bool end_object() = 0;
  4389. /*!
  4390. @brief the beginning of an array was read
  4391. @param[in] elements number of array elements or -1 if unknown
  4392. @return whether parsing should proceed
  4393. @note binary formats may report the number of elements
  4394. */
  4395. virtual bool start_array(std::size_t elements) = 0;
  4396. /*!
  4397. @brief the end of an array was read
  4398. @return whether parsing should proceed
  4399. */
  4400. virtual bool end_array() = 0;
  4401. /*!
  4402. @brief a parse error occurred
  4403. @param[in] position the position in the input where the error occurs
  4404. @param[in] last_token the last read token
  4405. @param[in] ex an exception object describing the error
  4406. @return whether parsing should proceed (must return false)
  4407. */
  4408. virtual bool parse_error(std::size_t position,
  4409. const std::string& last_token,
  4410. const detail::exception& ex) = 0;
  4411. virtual ~json_sax() = default;
  4412. };
  4413. namespace detail
  4414. {
  4415. /*!
  4416. @brief SAX implementation to create a JSON value from SAX events
  4417. This class implements the @ref json_sax interface and processes the SAX events
  4418. to create a JSON value which makes it basically a DOM parser. The structure or
  4419. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  4420. a pointer to the respective array or object for each recursion depth.
  4421. After successful parsing, the value that is passed by reference to the
  4422. constructor contains the parsed value.
  4423. @tparam BasicJsonType the JSON type
  4424. */
  4425. template<typename BasicJsonType>
  4426. class json_sax_dom_parser
  4427. {
  4428. public:
  4429. using number_integer_t = typename BasicJsonType::number_integer_t;
  4430. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4431. using number_float_t = typename BasicJsonType::number_float_t;
  4432. using string_t = typename BasicJsonType::string_t;
  4433. using binary_t = typename BasicJsonType::binary_t;
  4434. /*!
  4435. @param[in, out] r reference to a JSON value that is manipulated while
  4436. parsing
  4437. @param[in] allow_exceptions_ whether parse errors yield exceptions
  4438. */
  4439. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  4440. : root(r), allow_exceptions(allow_exceptions_)
  4441. {}
  4442. // make class move-only
  4443. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  4444. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  4445. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  4446. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  4447. ~json_sax_dom_parser() = default;
  4448. bool null()
  4449. {
  4450. handle_value(nullptr);
  4451. return true;
  4452. }
  4453. bool boolean(bool val)
  4454. {
  4455. handle_value(val);
  4456. return true;
  4457. }
  4458. bool number_integer(number_integer_t val)
  4459. {
  4460. handle_value(val);
  4461. return true;
  4462. }
  4463. bool number_unsigned(number_unsigned_t val)
  4464. {
  4465. handle_value(val);
  4466. return true;
  4467. }
  4468. bool number_float(number_float_t val, const string_t& /*unused*/)
  4469. {
  4470. handle_value(val);
  4471. return true;
  4472. }
  4473. bool string(string_t& val)
  4474. {
  4475. handle_value(val);
  4476. return true;
  4477. }
  4478. bool binary(binary_t& val)
  4479. {
  4480. handle_value(std::move(val));
  4481. return true;
  4482. }
  4483. bool start_object(std::size_t len)
  4484. {
  4485. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  4486. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4487. {
  4488. JSON_THROW(out_of_range::create(408,
  4489. "excessive object size: " + std::to_string(len)));
  4490. }
  4491. return true;
  4492. }
  4493. bool key(string_t& val)
  4494. {
  4495. // add null at given key and store the reference for later
  4496. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  4497. return true;
  4498. }
  4499. bool end_object()
  4500. {
  4501. ref_stack.pop_back();
  4502. return true;
  4503. }
  4504. bool start_array(std::size_t len)
  4505. {
  4506. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  4507. if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4508. {
  4509. JSON_THROW(out_of_range::create(408,
  4510. "excessive array size: " + std::to_string(len)));
  4511. }
  4512. return true;
  4513. }
  4514. bool end_array()
  4515. {
  4516. ref_stack.pop_back();
  4517. return true;
  4518. }
  4519. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4520. const detail::exception& ex)
  4521. {
  4522. errored = true;
  4523. if (allow_exceptions)
  4524. {
  4525. // determine the proper exception type from the id
  4526. switch ((ex.id / 100) % 100)
  4527. {
  4528. case 1:
  4529. JSON_THROW(*dynamic_cast<const detail::parse_error*>(&ex));
  4530. case 4:
  4531. JSON_THROW(*dynamic_cast<const detail::out_of_range*>(&ex));
  4532. // LCOV_EXCL_START
  4533. case 2:
  4534. JSON_THROW(*dynamic_cast<const detail::invalid_iterator*>(&ex));
  4535. case 3:
  4536. JSON_THROW(*dynamic_cast<const detail::type_error*>(&ex));
  4537. case 5:
  4538. JSON_THROW(*dynamic_cast<const detail::other_error*>(&ex));
  4539. default:
  4540. JSON_ASSERT(false);
  4541. // LCOV_EXCL_STOP
  4542. }
  4543. }
  4544. return false;
  4545. }
  4546. constexpr bool is_errored() const
  4547. {
  4548. return errored;
  4549. }
  4550. private:
  4551. /*!
  4552. @invariant If the ref stack is empty, then the passed value will be the new
  4553. root.
  4554. @invariant If the ref stack contains a value, then it is an array or an
  4555. object to which we can add elements
  4556. */
  4557. template<typename Value>
  4558. JSON_HEDLEY_RETURNS_NON_NULL
  4559. BasicJsonType* handle_value(Value&& v)
  4560. {
  4561. if (ref_stack.empty())
  4562. {
  4563. root = BasicJsonType(std::forward<Value>(v));
  4564. return &root;
  4565. }
  4566. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  4567. if (ref_stack.back()->is_array())
  4568. {
  4569. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  4570. return &(ref_stack.back()->m_value.array->back());
  4571. }
  4572. JSON_ASSERT(ref_stack.back()->is_object());
  4573. JSON_ASSERT(object_element);
  4574. *object_element = BasicJsonType(std::forward<Value>(v));
  4575. return object_element;
  4576. }
  4577. /// the parsed JSON value
  4578. BasicJsonType& root;
  4579. /// stack to model hierarchy of values
  4580. std::vector<BasicJsonType*> ref_stack {};
  4581. /// helper to hold the reference for the next object element
  4582. BasicJsonType* object_element = nullptr;
  4583. /// whether a syntax error occurred
  4584. bool errored = false;
  4585. /// whether to throw exceptions in case of errors
  4586. const bool allow_exceptions = true;
  4587. };
  4588. template<typename BasicJsonType>
  4589. class json_sax_dom_callback_parser
  4590. {
  4591. public:
  4592. using number_integer_t = typename BasicJsonType::number_integer_t;
  4593. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4594. using number_float_t = typename BasicJsonType::number_float_t;
  4595. using string_t = typename BasicJsonType::string_t;
  4596. using binary_t = typename BasicJsonType::binary_t;
  4597. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  4598. using parse_event_t = typename BasicJsonType::parse_event_t;
  4599. json_sax_dom_callback_parser(BasicJsonType& r,
  4600. const parser_callback_t cb,
  4601. const bool allow_exceptions_ = true)
  4602. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  4603. {
  4604. keep_stack.push_back(true);
  4605. }
  4606. // make class move-only
  4607. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  4608. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  4609. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  4610. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  4611. ~json_sax_dom_callback_parser() = default;
  4612. bool null()
  4613. {
  4614. handle_value(nullptr);
  4615. return true;
  4616. }
  4617. bool boolean(bool val)
  4618. {
  4619. handle_value(val);
  4620. return true;
  4621. }
  4622. bool number_integer(number_integer_t val)
  4623. {
  4624. handle_value(val);
  4625. return true;
  4626. }
  4627. bool number_unsigned(number_unsigned_t val)
  4628. {
  4629. handle_value(val);
  4630. return true;
  4631. }
  4632. bool number_float(number_float_t val, const string_t& /*unused*/)
  4633. {
  4634. handle_value(val);
  4635. return true;
  4636. }
  4637. bool string(string_t& val)
  4638. {
  4639. handle_value(val);
  4640. return true;
  4641. }
  4642. bool binary(binary_t& val)
  4643. {
  4644. handle_value(std::move(val));
  4645. return true;
  4646. }
  4647. bool start_object(std::size_t len)
  4648. {
  4649. // check callback for object start
  4650. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  4651. keep_stack.push_back(keep);
  4652. auto val = handle_value(BasicJsonType::value_t::object, true);
  4653. ref_stack.push_back(val.second);
  4654. // check object limit
  4655. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4656. {
  4657. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  4658. }
  4659. return true;
  4660. }
  4661. bool key(string_t& val)
  4662. {
  4663. BasicJsonType k = BasicJsonType(val);
  4664. // check callback for key
  4665. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  4666. key_keep_stack.push_back(keep);
  4667. // add discarded value at given key and store the reference for later
  4668. if (keep && ref_stack.back())
  4669. {
  4670. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  4671. }
  4672. return true;
  4673. }
  4674. bool end_object()
  4675. {
  4676. if (ref_stack.back() && !callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  4677. {
  4678. // discard object
  4679. *ref_stack.back() = discarded;
  4680. }
  4681. JSON_ASSERT(!ref_stack.empty());
  4682. JSON_ASSERT(!keep_stack.empty());
  4683. ref_stack.pop_back();
  4684. keep_stack.pop_back();
  4685. if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured())
  4686. {
  4687. // remove discarded value
  4688. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  4689. {
  4690. if (it->is_discarded())
  4691. {
  4692. ref_stack.back()->erase(it);
  4693. break;
  4694. }
  4695. }
  4696. }
  4697. return true;
  4698. }
  4699. bool start_array(std::size_t len)
  4700. {
  4701. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  4702. keep_stack.push_back(keep);
  4703. auto val = handle_value(BasicJsonType::value_t::array, true);
  4704. ref_stack.push_back(val.second);
  4705. // check array limit
  4706. if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size()))
  4707. {
  4708. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  4709. }
  4710. return true;
  4711. }
  4712. bool end_array()
  4713. {
  4714. bool keep = true;
  4715. if (ref_stack.back())
  4716. {
  4717. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  4718. if (!keep)
  4719. {
  4720. // discard array
  4721. *ref_stack.back() = discarded;
  4722. }
  4723. }
  4724. JSON_ASSERT(!ref_stack.empty());
  4725. JSON_ASSERT(!keep_stack.empty());
  4726. ref_stack.pop_back();
  4727. keep_stack.pop_back();
  4728. // remove discarded value
  4729. if (!keep && !ref_stack.empty() && ref_stack.back()->is_array())
  4730. {
  4731. ref_stack.back()->m_value.array->pop_back();
  4732. }
  4733. return true;
  4734. }
  4735. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  4736. const detail::exception& ex)
  4737. {
  4738. errored = true;
  4739. if (allow_exceptions)
  4740. {
  4741. // determine the proper exception type from the id
  4742. switch ((ex.id / 100) % 100)
  4743. {
  4744. case 1:
  4745. JSON_THROW(*dynamic_cast<const detail::parse_error*>(&ex));
  4746. case 4:
  4747. JSON_THROW(*dynamic_cast<const detail::out_of_range*>(&ex));
  4748. // LCOV_EXCL_START
  4749. case 2:
  4750. JSON_THROW(*dynamic_cast<const detail::invalid_iterator*>(&ex));
  4751. case 3:
  4752. JSON_THROW(*dynamic_cast<const detail::type_error*>(&ex));
  4753. case 5:
  4754. JSON_THROW(*dynamic_cast<const detail::other_error*>(&ex));
  4755. default:
  4756. JSON_ASSERT(false);
  4757. // LCOV_EXCL_STOP
  4758. }
  4759. }
  4760. return false;
  4761. }
  4762. constexpr bool is_errored() const
  4763. {
  4764. return errored;
  4765. }
  4766. private:
  4767. /*!
  4768. @param[in] v value to add to the JSON value we build during parsing
  4769. @param[in] skip_callback whether we should skip calling the callback
  4770. function; this is required after start_array() and
  4771. start_object() SAX events, because otherwise we would call the
  4772. callback function with an empty array or object, respectively.
  4773. @invariant If the ref stack is empty, then the passed value will be the new
  4774. root.
  4775. @invariant If the ref stack contains a value, then it is an array or an
  4776. object to which we can add elements
  4777. @return pair of boolean (whether value should be kept) and pointer (to the
  4778. passed value in the ref_stack hierarchy; nullptr if not kept)
  4779. */
  4780. template<typename Value>
  4781. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  4782. {
  4783. JSON_ASSERT(!keep_stack.empty());
  4784. // do not handle this value if we know it would be added to a discarded
  4785. // container
  4786. if (!keep_stack.back())
  4787. {
  4788. return {false, nullptr};
  4789. }
  4790. // create value
  4791. auto value = BasicJsonType(std::forward<Value>(v));
  4792. // check callback
  4793. const bool keep = skip_callback || callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  4794. // do not handle this value if we just learnt it shall be discarded
  4795. if (!keep)
  4796. {
  4797. return {false, nullptr};
  4798. }
  4799. if (ref_stack.empty())
  4800. {
  4801. root = std::move(value);
  4802. return {true, &root};
  4803. }
  4804. // skip this value if we already decided to skip the parent
  4805. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  4806. if (!ref_stack.back())
  4807. {
  4808. return {false, nullptr};
  4809. }
  4810. // we now only expect arrays and objects
  4811. JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object());
  4812. // array
  4813. if (ref_stack.back()->is_array())
  4814. {
  4815. ref_stack.back()->m_value.array->push_back(std::move(value));
  4816. return {true, &(ref_stack.back()->m_value.array->back())};
  4817. }
  4818. // object
  4819. JSON_ASSERT(ref_stack.back()->is_object());
  4820. // check if we should store an element for the current key
  4821. JSON_ASSERT(!key_keep_stack.empty());
  4822. const bool store_element = key_keep_stack.back();
  4823. key_keep_stack.pop_back();
  4824. if (!store_element)
  4825. {
  4826. return {false, nullptr};
  4827. }
  4828. JSON_ASSERT(object_element);
  4829. *object_element = std::move(value);
  4830. return {true, object_element};
  4831. }
  4832. /// the parsed JSON value
  4833. BasicJsonType& root;
  4834. /// stack to model hierarchy of values
  4835. std::vector<BasicJsonType*> ref_stack {};
  4836. /// stack to manage which values to keep
  4837. std::vector<bool> keep_stack {};
  4838. /// stack to manage which object keys to keep
  4839. std::vector<bool> key_keep_stack {};
  4840. /// helper to hold the reference for the next object element
  4841. BasicJsonType* object_element = nullptr;
  4842. /// whether a syntax error occurred
  4843. bool errored = false;
  4844. /// callback function
  4845. const parser_callback_t callback = nullptr;
  4846. /// whether to throw exceptions in case of errors
  4847. const bool allow_exceptions = true;
  4848. /// a discarded value for the callback
  4849. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  4850. };
  4851. template<typename BasicJsonType>
  4852. class json_sax_acceptor
  4853. {
  4854. public:
  4855. using number_integer_t = typename BasicJsonType::number_integer_t;
  4856. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4857. using number_float_t = typename BasicJsonType::number_float_t;
  4858. using string_t = typename BasicJsonType::string_t;
  4859. using binary_t = typename BasicJsonType::binary_t;
  4860. bool null()
  4861. {
  4862. return true;
  4863. }
  4864. bool boolean(bool /*unused*/)
  4865. {
  4866. return true;
  4867. }
  4868. bool number_integer(number_integer_t /*unused*/)
  4869. {
  4870. return true;
  4871. }
  4872. bool number_unsigned(number_unsigned_t /*unused*/)
  4873. {
  4874. return true;
  4875. }
  4876. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  4877. {
  4878. return true;
  4879. }
  4880. bool string(string_t& /*unused*/)
  4881. {
  4882. return true;
  4883. }
  4884. bool binary(binary_t& /*unused*/)
  4885. {
  4886. return true;
  4887. }
  4888. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  4889. {
  4890. return true;
  4891. }
  4892. bool key(string_t& /*unused*/)
  4893. {
  4894. return true;
  4895. }
  4896. bool end_object()
  4897. {
  4898. return true;
  4899. }
  4900. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  4901. {
  4902. return true;
  4903. }
  4904. bool end_array()
  4905. {
  4906. return true;
  4907. }
  4908. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  4909. {
  4910. return false;
  4911. }
  4912. };
  4913. } // namespace detail
  4914. } // namespace nlohmann
  4915. // #include <nlohmann/detail/macro_scope.hpp>
  4916. // #include <nlohmann/detail/meta/is_sax.hpp>
  4917. #include <cstdint> // size_t
  4918. #include <utility> // declval
  4919. #include <string> // string
  4920. // #include <nlohmann/detail/meta/detected.hpp>
  4921. // #include <nlohmann/detail/meta/type_traits.hpp>
  4922. namespace nlohmann
  4923. {
  4924. namespace detail
  4925. {
  4926. template<typename T>
  4927. using null_function_t = decltype(std::declval<T&>().null());
  4928. template<typename T>
  4929. using boolean_function_t =
  4930. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  4931. template<typename T, typename Integer>
  4932. using number_integer_function_t =
  4933. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  4934. template<typename T, typename Unsigned>
  4935. using number_unsigned_function_t =
  4936. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  4937. template<typename T, typename Float, typename String>
  4938. using number_float_function_t = decltype(std::declval<T&>().number_float(
  4939. std::declval<Float>(), std::declval<const String&>()));
  4940. template<typename T, typename String>
  4941. using string_function_t =
  4942. decltype(std::declval<T&>().string(std::declval<String&>()));
  4943. template<typename T>
  4944. using start_object_function_t =
  4945. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  4946. template<typename T, typename String>
  4947. using key_function_t =
  4948. decltype(std::declval<T&>().key(std::declval<String&>()));
  4949. template<typename T>
  4950. using end_object_function_t = decltype(std::declval<T&>().end_object());
  4951. template<typename T>
  4952. using start_array_function_t =
  4953. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  4954. template<typename T>
  4955. using end_array_function_t = decltype(std::declval<T&>().end_array());
  4956. template<typename T, typename Exception>
  4957. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  4958. std::declval<std::size_t>(), std::declval<const std::string&>(),
  4959. std::declval<const Exception&>()));
  4960. template<typename SAX, typename BasicJsonType>
  4961. struct is_sax
  4962. {
  4963. private:
  4964. static_assert(is_basic_json<BasicJsonType>::value,
  4965. "BasicJsonType must be of type basic_json<...>");
  4966. using number_integer_t = typename BasicJsonType::number_integer_t;
  4967. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4968. using number_float_t = typename BasicJsonType::number_float_t;
  4969. using string_t = typename BasicJsonType::string_t;
  4970. using exception_t = typename BasicJsonType::exception;
  4971. public:
  4972. static constexpr bool value =
  4973. is_detected_exact<bool, null_function_t, SAX>::value &&
  4974. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  4975. is_detected_exact<bool, number_integer_function_t, SAX,
  4976. number_integer_t>::value &&
  4977. is_detected_exact<bool, number_unsigned_function_t, SAX,
  4978. number_unsigned_t>::value &&
  4979. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  4980. string_t>::value &&
  4981. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  4982. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  4983. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  4984. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  4985. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  4986. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  4987. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  4988. };
  4989. template<typename SAX, typename BasicJsonType>
  4990. struct is_sax_static_asserts
  4991. {
  4992. private:
  4993. static_assert(is_basic_json<BasicJsonType>::value,
  4994. "BasicJsonType must be of type basic_json<...>");
  4995. using number_integer_t = typename BasicJsonType::number_integer_t;
  4996. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4997. using number_float_t = typename BasicJsonType::number_float_t;
  4998. using string_t = typename BasicJsonType::string_t;
  4999. using exception_t = typename BasicJsonType::exception;
  5000. public:
  5001. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  5002. "Missing/invalid function: bool null()");
  5003. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  5004. "Missing/invalid function: bool boolean(bool)");
  5005. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  5006. "Missing/invalid function: bool boolean(bool)");
  5007. static_assert(
  5008. is_detected_exact<bool, number_integer_function_t, SAX,
  5009. number_integer_t>::value,
  5010. "Missing/invalid function: bool number_integer(number_integer_t)");
  5011. static_assert(
  5012. is_detected_exact<bool, number_unsigned_function_t, SAX,
  5013. number_unsigned_t>::value,
  5014. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  5015. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  5016. number_float_t, string_t>::value,
  5017. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  5018. static_assert(
  5019. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  5020. "Missing/invalid function: bool string(string_t&)");
  5021. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  5022. "Missing/invalid function: bool start_object(std::size_t)");
  5023. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  5024. "Missing/invalid function: bool key(string_t&)");
  5025. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  5026. "Missing/invalid function: bool end_object()");
  5027. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  5028. "Missing/invalid function: bool start_array(std::size_t)");
  5029. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  5030. "Missing/invalid function: bool end_array()");
  5031. static_assert(
  5032. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  5033. "Missing/invalid function: bool parse_error(std::size_t, const "
  5034. "std::string&, const exception&)");
  5035. };
  5036. } // namespace detail
  5037. } // namespace nlohmann
  5038. // #include <nlohmann/detail/value_t.hpp>
  5039. namespace nlohmann
  5040. {
  5041. namespace detail
  5042. {
  5043. /*!
  5044. @brief determine system byte order
  5045. @return true if and only if system's byte order is little endian
  5046. @note from https://stackoverflow.com/a/1001328/266378
  5047. */
  5048. static inline bool little_endianess(int num = 1) noexcept
  5049. {
  5050. return *reinterpret_cast<char*>(&num) == 1;
  5051. }
  5052. ///////////////////
  5053. // binary reader //
  5054. ///////////////////
  5055. /*!
  5056. @brief deserialization of CBOR, MessagePack, and UBJSON values
  5057. */
  5058. template<typename BasicJsonType, typename InputAdapterType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  5059. class binary_reader
  5060. {
  5061. using number_integer_t = typename BasicJsonType::number_integer_t;
  5062. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5063. using number_float_t = typename BasicJsonType::number_float_t;
  5064. using string_t = typename BasicJsonType::string_t;
  5065. using binary_t = typename BasicJsonType::binary_t;
  5066. using json_sax_t = SAX;
  5067. using char_type = typename InputAdapterType::char_type;
  5068. using char_int_type = typename std::char_traits<char_type>::int_type;
  5069. public:
  5070. /*!
  5071. @brief create a binary reader
  5072. @param[in] adapter input adapter to read from
  5073. */
  5074. explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter))
  5075. {
  5076. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  5077. }
  5078. // make class move-only
  5079. binary_reader(const binary_reader&) = delete;
  5080. binary_reader(binary_reader&&) = default;
  5081. binary_reader& operator=(const binary_reader&) = delete;
  5082. binary_reader& operator=(binary_reader&&) = default;
  5083. ~binary_reader() = default;
  5084. /*!
  5085. @param[in] format the binary format to parse
  5086. @param[in] sax_ a SAX event processor
  5087. @param[in] strict whether to expect the input to be consumed completed
  5088. @return
  5089. */
  5090. JSON_HEDLEY_NON_NULL(3)
  5091. bool sax_parse(const input_format_t format,
  5092. json_sax_t* sax_,
  5093. const bool strict = true)
  5094. {
  5095. sax = sax_;
  5096. bool result = false;
  5097. switch (format)
  5098. {
  5099. case input_format_t::bson:
  5100. result = parse_bson_internal();
  5101. break;
  5102. case input_format_t::cbor:
  5103. result = parse_cbor_internal();
  5104. break;
  5105. case input_format_t::msgpack:
  5106. result = parse_msgpack_internal();
  5107. break;
  5108. case input_format_t::ubjson:
  5109. result = parse_ubjson_internal();
  5110. break;
  5111. default: // LCOV_EXCL_LINE
  5112. JSON_ASSERT(false); // LCOV_EXCL_LINE
  5113. }
  5114. // strict mode: next byte must be EOF
  5115. if (result && strict)
  5116. {
  5117. if (format == input_format_t::ubjson)
  5118. {
  5119. get_ignore_noop();
  5120. }
  5121. else
  5122. {
  5123. get();
  5124. }
  5125. if (JSON_HEDLEY_UNLIKELY(current != std::char_traits<char_type>::eof()))
  5126. {
  5127. return sax->parse_error(chars_read, get_token_string(),
  5128. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  5129. }
  5130. }
  5131. return result;
  5132. }
  5133. private:
  5134. //////////
  5135. // BSON //
  5136. //////////
  5137. /*!
  5138. @brief Reads in a BSON-object and passes it to the SAX-parser.
  5139. @return whether a valid BSON-value was passed to the SAX parser
  5140. */
  5141. bool parse_bson_internal()
  5142. {
  5143. std::int32_t document_size{};
  5144. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5145. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  5146. {
  5147. return false;
  5148. }
  5149. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false)))
  5150. {
  5151. return false;
  5152. }
  5153. return sax->end_object();
  5154. }
  5155. /*!
  5156. @brief Parses a C-style string from the BSON input.
  5157. @param[in, out] result A reference to the string variable where the read
  5158. string is to be stored.
  5159. @return `true` if the \x00-byte indicating the end of the string was
  5160. encountered before the EOF; false` indicates an unexpected EOF.
  5161. */
  5162. bool get_bson_cstr(string_t& result)
  5163. {
  5164. auto out = std::back_inserter(result);
  5165. while (true)
  5166. {
  5167. get();
  5168. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring")))
  5169. {
  5170. return false;
  5171. }
  5172. if (current == 0x00)
  5173. {
  5174. return true;
  5175. }
  5176. *out++ = static_cast<typename string_t::value_type>(current);
  5177. }
  5178. }
  5179. /*!
  5180. @brief Parses a zero-terminated string of length @a len from the BSON
  5181. input.
  5182. @param[in] len The length (including the zero-byte at the end) of the
  5183. string to be read.
  5184. @param[in, out] result A reference to the string variable where the read
  5185. string is to be stored.
  5186. @tparam NumberType The type of the length @a len
  5187. @pre len >= 1
  5188. @return `true` if the string was successfully parsed
  5189. */
  5190. template<typename NumberType>
  5191. bool get_bson_string(const NumberType len, string_t& result)
  5192. {
  5193. if (JSON_HEDLEY_UNLIKELY(len < 1))
  5194. {
  5195. auto last_token = get_token_string();
  5196. 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")));
  5197. }
  5198. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) && get() != std::char_traits<char_type>::eof();
  5199. }
  5200. /*!
  5201. @brief Parses a byte array input of length @a len from the BSON input.
  5202. @param[in] len The length of the byte array to be read.
  5203. @param[in, out] result A reference to the binary variable where the read
  5204. array is to be stored.
  5205. @tparam NumberType The type of the length @a len
  5206. @pre len >= 0
  5207. @return `true` if the byte array was successfully parsed
  5208. */
  5209. template<typename NumberType>
  5210. bool get_bson_binary(const NumberType len, binary_t& result)
  5211. {
  5212. if (JSON_HEDLEY_UNLIKELY(len < 0))
  5213. {
  5214. auto last_token = get_token_string();
  5215. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary")));
  5216. }
  5217. // All BSON binary values have a subtype
  5218. std::uint8_t subtype{};
  5219. get_number<std::uint8_t>(input_format_t::bson, subtype);
  5220. result.set_subtype(subtype);
  5221. return get_binary(input_format_t::bson, len, result);
  5222. }
  5223. /*!
  5224. @brief Read a BSON document element of the given @a element_type.
  5225. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  5226. @param[in] element_type_parse_position The position in the input stream,
  5227. where the `element_type` was read.
  5228. @warning Not all BSON element types are supported yet. An unsupported
  5229. @a element_type will give rise to a parse_error.114:
  5230. Unsupported BSON record type 0x...
  5231. @return whether a valid BSON-object/array was passed to the SAX parser
  5232. */
  5233. bool parse_bson_element_internal(const char_int_type element_type,
  5234. const std::size_t element_type_parse_position)
  5235. {
  5236. switch (element_type)
  5237. {
  5238. case 0x01: // double
  5239. {
  5240. double number{};
  5241. return get_number<double, true>(input_format_t::bson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  5242. }
  5243. case 0x02: // string
  5244. {
  5245. std::int32_t len{};
  5246. string_t value;
  5247. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value);
  5248. }
  5249. case 0x03: // object
  5250. {
  5251. return parse_bson_internal();
  5252. }
  5253. case 0x04: // array
  5254. {
  5255. return parse_bson_array();
  5256. }
  5257. case 0x05: // binary
  5258. {
  5259. std::int32_t len{};
  5260. binary_t value;
  5261. return get_number<std::int32_t, true>(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value);
  5262. }
  5263. case 0x08: // boolean
  5264. {
  5265. return sax->boolean(get() != 0);
  5266. }
  5267. case 0x0A: // null
  5268. {
  5269. return sax->null();
  5270. }
  5271. case 0x10: // int32
  5272. {
  5273. std::int32_t value{};
  5274. return get_number<std::int32_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  5275. }
  5276. case 0x12: // int64
  5277. {
  5278. std::int64_t value{};
  5279. return get_number<std::int64_t, true>(input_format_t::bson, value) && sax->number_integer(value);
  5280. }
  5281. default: // anything else not supported (yet)
  5282. {
  5283. std::array<char, 3> cr{{}};
  5284. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  5285. 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())));
  5286. }
  5287. }
  5288. }
  5289. /*!
  5290. @brief Read a BSON element list (as specified in the BSON-spec)
  5291. The same binary layout is used for objects and arrays, hence it must be
  5292. indicated with the argument @a is_array which one is expected
  5293. (true --> array, false --> object).
  5294. @param[in] is_array Determines if the element list being read is to be
  5295. treated as an object (@a is_array == false), or as an
  5296. array (@a is_array == true).
  5297. @return whether a valid BSON-object/array was passed to the SAX parser
  5298. */
  5299. bool parse_bson_element_list(const bool is_array)
  5300. {
  5301. string_t key;
  5302. while (auto element_type = get())
  5303. {
  5304. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list")))
  5305. {
  5306. return false;
  5307. }
  5308. const std::size_t element_type_parse_position = chars_read;
  5309. if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key)))
  5310. {
  5311. return false;
  5312. }
  5313. if (!is_array && !sax->key(key))
  5314. {
  5315. return false;
  5316. }
  5317. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position)))
  5318. {
  5319. return false;
  5320. }
  5321. // get_bson_cstr only appends
  5322. key.clear();
  5323. }
  5324. return true;
  5325. }
  5326. /*!
  5327. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  5328. @return whether a valid BSON-array was passed to the SAX parser
  5329. */
  5330. bool parse_bson_array()
  5331. {
  5332. std::int32_t document_size{};
  5333. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  5334. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  5335. {
  5336. return false;
  5337. }
  5338. if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true)))
  5339. {
  5340. return false;
  5341. }
  5342. return sax->end_array();
  5343. }
  5344. //////////
  5345. // CBOR //
  5346. //////////
  5347. /*!
  5348. @param[in] get_char whether a new character should be retrieved from the
  5349. input (true, default) or whether the last read
  5350. character should be considered instead
  5351. @return whether a valid CBOR value was passed to the SAX parser
  5352. */
  5353. bool parse_cbor_internal(const bool get_char = true)
  5354. {
  5355. switch (get_char ? get() : current)
  5356. {
  5357. // EOF
  5358. case std::char_traits<char_type>::eof():
  5359. return unexpect_eof(input_format_t::cbor, "value");
  5360. // Integer 0x00..0x17 (0..23)
  5361. case 0x00:
  5362. case 0x01:
  5363. case 0x02:
  5364. case 0x03:
  5365. case 0x04:
  5366. case 0x05:
  5367. case 0x06:
  5368. case 0x07:
  5369. case 0x08:
  5370. case 0x09:
  5371. case 0x0A:
  5372. case 0x0B:
  5373. case 0x0C:
  5374. case 0x0D:
  5375. case 0x0E:
  5376. case 0x0F:
  5377. case 0x10:
  5378. case 0x11:
  5379. case 0x12:
  5380. case 0x13:
  5381. case 0x14:
  5382. case 0x15:
  5383. case 0x16:
  5384. case 0x17:
  5385. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5386. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5387. {
  5388. std::uint8_t number{};
  5389. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  5390. }
  5391. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5392. {
  5393. std::uint16_t number{};
  5394. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  5395. }
  5396. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5397. {
  5398. std::uint32_t number{};
  5399. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  5400. }
  5401. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5402. {
  5403. std::uint64_t number{};
  5404. return get_number(input_format_t::cbor, number) && sax->number_unsigned(number);
  5405. }
  5406. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5407. case 0x20:
  5408. case 0x21:
  5409. case 0x22:
  5410. case 0x23:
  5411. case 0x24:
  5412. case 0x25:
  5413. case 0x26:
  5414. case 0x27:
  5415. case 0x28:
  5416. case 0x29:
  5417. case 0x2A:
  5418. case 0x2B:
  5419. case 0x2C:
  5420. case 0x2D:
  5421. case 0x2E:
  5422. case 0x2F:
  5423. case 0x30:
  5424. case 0x31:
  5425. case 0x32:
  5426. case 0x33:
  5427. case 0x34:
  5428. case 0x35:
  5429. case 0x36:
  5430. case 0x37:
  5431. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  5432. case 0x38: // Negative integer (one-byte uint8_t follows)
  5433. {
  5434. std::uint8_t number{};
  5435. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5436. }
  5437. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5438. {
  5439. std::uint16_t number{};
  5440. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5441. }
  5442. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5443. {
  5444. std::uint32_t number{};
  5445. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5446. }
  5447. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5448. {
  5449. std::uint64_t number{};
  5450. return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast<number_integer_t>(-1)
  5451. - static_cast<number_integer_t>(number));
  5452. }
  5453. // Binary data (0x00..0x17 bytes follow)
  5454. case 0x40:
  5455. case 0x41:
  5456. case 0x42:
  5457. case 0x43:
  5458. case 0x44:
  5459. case 0x45:
  5460. case 0x46:
  5461. case 0x47:
  5462. case 0x48:
  5463. case 0x49:
  5464. case 0x4A:
  5465. case 0x4B:
  5466. case 0x4C:
  5467. case 0x4D:
  5468. case 0x4E:
  5469. case 0x4F:
  5470. case 0x50:
  5471. case 0x51:
  5472. case 0x52:
  5473. case 0x53:
  5474. case 0x54:
  5475. case 0x55:
  5476. case 0x56:
  5477. case 0x57:
  5478. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5479. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5480. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5481. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5482. case 0x5F: // Binary data (indefinite length)
  5483. {
  5484. binary_t b;
  5485. return get_cbor_binary(b) && sax->binary(b);
  5486. }
  5487. // UTF-8 string (0x00..0x17 bytes follow)
  5488. case 0x60:
  5489. case 0x61:
  5490. case 0x62:
  5491. case 0x63:
  5492. case 0x64:
  5493. case 0x65:
  5494. case 0x66:
  5495. case 0x67:
  5496. case 0x68:
  5497. case 0x69:
  5498. case 0x6A:
  5499. case 0x6B:
  5500. case 0x6C:
  5501. case 0x6D:
  5502. case 0x6E:
  5503. case 0x6F:
  5504. case 0x70:
  5505. case 0x71:
  5506. case 0x72:
  5507. case 0x73:
  5508. case 0x74:
  5509. case 0x75:
  5510. case 0x76:
  5511. case 0x77:
  5512. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5513. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5514. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5515. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5516. case 0x7F: // UTF-8 string (indefinite length)
  5517. {
  5518. string_t s;
  5519. return get_cbor_string(s) && sax->string(s);
  5520. }
  5521. // array (0x00..0x17 data items follow)
  5522. case 0x80:
  5523. case 0x81:
  5524. case 0x82:
  5525. case 0x83:
  5526. case 0x84:
  5527. case 0x85:
  5528. case 0x86:
  5529. case 0x87:
  5530. case 0x88:
  5531. case 0x89:
  5532. case 0x8A:
  5533. case 0x8B:
  5534. case 0x8C:
  5535. case 0x8D:
  5536. case 0x8E:
  5537. case 0x8F:
  5538. case 0x90:
  5539. case 0x91:
  5540. case 0x92:
  5541. case 0x93:
  5542. case 0x94:
  5543. case 0x95:
  5544. case 0x96:
  5545. case 0x97:
  5546. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5547. case 0x98: // array (one-byte uint8_t for n follows)
  5548. {
  5549. std::uint8_t len{};
  5550. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len));
  5551. }
  5552. case 0x99: // array (two-byte uint16_t for n follow)
  5553. {
  5554. std::uint16_t len{};
  5555. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len));
  5556. }
  5557. case 0x9A: // array (four-byte uint32_t for n follow)
  5558. {
  5559. std::uint32_t len{};
  5560. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len));
  5561. }
  5562. case 0x9B: // array (eight-byte uint64_t for n follow)
  5563. {
  5564. std::uint64_t len{};
  5565. return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast<std::size_t>(len));
  5566. }
  5567. case 0x9F: // array (indefinite length)
  5568. return get_cbor_array(std::size_t(-1));
  5569. // map (0x00..0x17 pairs of data items follow)
  5570. case 0xA0:
  5571. case 0xA1:
  5572. case 0xA2:
  5573. case 0xA3:
  5574. case 0xA4:
  5575. case 0xA5:
  5576. case 0xA6:
  5577. case 0xA7:
  5578. case 0xA8:
  5579. case 0xA9:
  5580. case 0xAA:
  5581. case 0xAB:
  5582. case 0xAC:
  5583. case 0xAD:
  5584. case 0xAE:
  5585. case 0xAF:
  5586. case 0xB0:
  5587. case 0xB1:
  5588. case 0xB2:
  5589. case 0xB3:
  5590. case 0xB4:
  5591. case 0xB5:
  5592. case 0xB6:
  5593. case 0xB7:
  5594. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  5595. case 0xB8: // map (one-byte uint8_t for n follows)
  5596. {
  5597. std::uint8_t len{};
  5598. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len));
  5599. }
  5600. case 0xB9: // map (two-byte uint16_t for n follow)
  5601. {
  5602. std::uint16_t len{};
  5603. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len));
  5604. }
  5605. case 0xBA: // map (four-byte uint32_t for n follow)
  5606. {
  5607. std::uint32_t len{};
  5608. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len));
  5609. }
  5610. case 0xBB: // map (eight-byte uint64_t for n follow)
  5611. {
  5612. std::uint64_t len{};
  5613. return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast<std::size_t>(len));
  5614. }
  5615. case 0xBF: // map (indefinite length)
  5616. return get_cbor_object(std::size_t(-1));
  5617. case 0xF4: // false
  5618. return sax->boolean(false);
  5619. case 0xF5: // true
  5620. return sax->boolean(true);
  5621. case 0xF6: // null
  5622. return sax->null();
  5623. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5624. {
  5625. const auto byte1_raw = get();
  5626. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  5627. {
  5628. return false;
  5629. }
  5630. const auto byte2_raw = get();
  5631. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number")))
  5632. {
  5633. return false;
  5634. }
  5635. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  5636. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  5637. // code from RFC 7049, Appendix D, Figure 3:
  5638. // As half-precision floating-point numbers were only added
  5639. // to IEEE 754 in 2008, today's programming platforms often
  5640. // still only have limited support for them. It is very
  5641. // easy to include at least decoding support for them even
  5642. // without such support. An example of a small decoder for
  5643. // half-precision floating-point numbers in the C language
  5644. // is shown in Fig. 3.
  5645. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  5646. const double val = [&half]
  5647. {
  5648. const int exp = (half >> 10u) & 0x1Fu;
  5649. const unsigned int mant = half & 0x3FFu;
  5650. JSON_ASSERT(0 <= exp&& exp <= 32);
  5651. JSON_ASSERT(mant <= 1024);
  5652. switch (exp)
  5653. {
  5654. case 0:
  5655. return std::ldexp(mant, -24);
  5656. case 31:
  5657. return (mant == 0)
  5658. ? std::numeric_limits<double>::infinity()
  5659. : std::numeric_limits<double>::quiet_NaN();
  5660. default:
  5661. return std::ldexp(mant + 1024, exp - 25);
  5662. }
  5663. }();
  5664. return sax->number_float((half & 0x8000u) != 0
  5665. ? static_cast<number_float_t>(-val)
  5666. : static_cast<number_float_t>(val), "");
  5667. }
  5668. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5669. {
  5670. float number{};
  5671. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  5672. }
  5673. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5674. {
  5675. double number{};
  5676. return get_number(input_format_t::cbor, number) && sax->number_float(static_cast<number_float_t>(number), "");
  5677. }
  5678. default: // anything else (0xFF is handled inside the other types)
  5679. {
  5680. auto last_token = get_token_string();
  5681. 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")));
  5682. }
  5683. }
  5684. }
  5685. /*!
  5686. @brief reads a CBOR string
  5687. This function first reads starting bytes to determine the expected
  5688. string length and then copies this number of bytes into a string.
  5689. Additionally, CBOR's strings with indefinite lengths are supported.
  5690. @param[out] result created string
  5691. @return whether string creation completed
  5692. */
  5693. bool get_cbor_string(string_t& result)
  5694. {
  5695. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string")))
  5696. {
  5697. return false;
  5698. }
  5699. switch (current)
  5700. {
  5701. // UTF-8 string (0x00..0x17 bytes follow)
  5702. case 0x60:
  5703. case 0x61:
  5704. case 0x62:
  5705. case 0x63:
  5706. case 0x64:
  5707. case 0x65:
  5708. case 0x66:
  5709. case 0x67:
  5710. case 0x68:
  5711. case 0x69:
  5712. case 0x6A:
  5713. case 0x6B:
  5714. case 0x6C:
  5715. case 0x6D:
  5716. case 0x6E:
  5717. case 0x6F:
  5718. case 0x70:
  5719. case 0x71:
  5720. case 0x72:
  5721. case 0x73:
  5722. case 0x74:
  5723. case 0x75:
  5724. case 0x76:
  5725. case 0x77:
  5726. {
  5727. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5728. }
  5729. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5730. {
  5731. std::uint8_t len{};
  5732. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  5733. }
  5734. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5735. {
  5736. std::uint16_t len{};
  5737. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  5738. }
  5739. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5740. {
  5741. std::uint32_t len{};
  5742. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  5743. }
  5744. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5745. {
  5746. std::uint64_t len{};
  5747. return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result);
  5748. }
  5749. case 0x7F: // UTF-8 string (indefinite length)
  5750. {
  5751. while (get() != 0xFF)
  5752. {
  5753. string_t chunk;
  5754. if (!get_cbor_string(chunk))
  5755. {
  5756. return false;
  5757. }
  5758. result.append(chunk);
  5759. }
  5760. return true;
  5761. }
  5762. default:
  5763. {
  5764. auto last_token = get_token_string();
  5765. 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")));
  5766. }
  5767. }
  5768. }
  5769. /*!
  5770. @brief reads a CBOR byte array
  5771. This function first reads starting bytes to determine the expected
  5772. byte array length and then copies this number of bytes into the byte array.
  5773. Additionally, CBOR's byte arrays with indefinite lengths are supported.
  5774. @param[out] result created byte array
  5775. @return whether byte array creation completed
  5776. */
  5777. bool get_cbor_binary(binary_t& result)
  5778. {
  5779. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary")))
  5780. {
  5781. return false;
  5782. }
  5783. switch (current)
  5784. {
  5785. // Binary data (0x00..0x17 bytes follow)
  5786. case 0x40:
  5787. case 0x41:
  5788. case 0x42:
  5789. case 0x43:
  5790. case 0x44:
  5791. case 0x45:
  5792. case 0x46:
  5793. case 0x47:
  5794. case 0x48:
  5795. case 0x49:
  5796. case 0x4A:
  5797. case 0x4B:
  5798. case 0x4C:
  5799. case 0x4D:
  5800. case 0x4E:
  5801. case 0x4F:
  5802. case 0x50:
  5803. case 0x51:
  5804. case 0x52:
  5805. case 0x53:
  5806. case 0x54:
  5807. case 0x55:
  5808. case 0x56:
  5809. case 0x57:
  5810. {
  5811. return get_binary(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  5812. }
  5813. case 0x58: // Binary data (one-byte uint8_t for n follows)
  5814. {
  5815. std::uint8_t len{};
  5816. return get_number(input_format_t::cbor, len) &&
  5817. get_binary(input_format_t::cbor, len, result);
  5818. }
  5819. case 0x59: // Binary data (two-byte uint16_t for n follow)
  5820. {
  5821. std::uint16_t len{};
  5822. return get_number(input_format_t::cbor, len) &&
  5823. get_binary(input_format_t::cbor, len, result);
  5824. }
  5825. case 0x5A: // Binary data (four-byte uint32_t for n follow)
  5826. {
  5827. std::uint32_t len{};
  5828. return get_number(input_format_t::cbor, len) &&
  5829. get_binary(input_format_t::cbor, len, result);
  5830. }
  5831. case 0x5B: // Binary data (eight-byte uint64_t for n follow)
  5832. {
  5833. std::uint64_t len{};
  5834. return get_number(input_format_t::cbor, len) &&
  5835. get_binary(input_format_t::cbor, len, result);
  5836. }
  5837. case 0x5F: // Binary data (indefinite length)
  5838. {
  5839. while (get() != 0xFF)
  5840. {
  5841. binary_t chunk;
  5842. if (!get_cbor_binary(chunk))
  5843. {
  5844. return false;
  5845. }
  5846. result.insert(result.end(), chunk.begin(), chunk.end());
  5847. }
  5848. return true;
  5849. }
  5850. default:
  5851. {
  5852. auto last_token = get_token_string();
  5853. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary")));
  5854. }
  5855. }
  5856. }
  5857. /*!
  5858. @param[in] len the length of the array or std::size_t(-1) for an
  5859. array of indefinite size
  5860. @return whether array creation completed
  5861. */
  5862. bool get_cbor_array(const std::size_t len)
  5863. {
  5864. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  5865. {
  5866. return false;
  5867. }
  5868. if (len != std::size_t(-1))
  5869. {
  5870. for (std::size_t i = 0; i < len; ++i)
  5871. {
  5872. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal()))
  5873. {
  5874. return false;
  5875. }
  5876. }
  5877. }
  5878. else
  5879. {
  5880. while (get() != 0xFF)
  5881. {
  5882. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false)))
  5883. {
  5884. return false;
  5885. }
  5886. }
  5887. }
  5888. return sax->end_array();
  5889. }
  5890. /*!
  5891. @param[in] len the length of the object or std::size_t(-1) for an
  5892. object of indefinite size
  5893. @return whether object creation completed
  5894. */
  5895. bool get_cbor_object(const std::size_t len)
  5896. {
  5897. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  5898. {
  5899. return false;
  5900. }
  5901. string_t key;
  5902. if (len != std::size_t(-1))
  5903. {
  5904. for (std::size_t i = 0; i < len; ++i)
  5905. {
  5906. get();
  5907. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  5908. {
  5909. return false;
  5910. }
  5911. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal()))
  5912. {
  5913. return false;
  5914. }
  5915. key.clear();
  5916. }
  5917. }
  5918. else
  5919. {
  5920. while (get() != 0xFF)
  5921. {
  5922. if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key)))
  5923. {
  5924. return false;
  5925. }
  5926. if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal()))
  5927. {
  5928. return false;
  5929. }
  5930. key.clear();
  5931. }
  5932. }
  5933. return sax->end_object();
  5934. }
  5935. /////////////
  5936. // MsgPack //
  5937. /////////////
  5938. /*!
  5939. @return whether a valid MessagePack value was passed to the SAX parser
  5940. */
  5941. bool parse_msgpack_internal()
  5942. {
  5943. switch (get())
  5944. {
  5945. // EOF
  5946. case std::char_traits<char_type>::eof():
  5947. return unexpect_eof(input_format_t::msgpack, "value");
  5948. // positive fixint
  5949. case 0x00:
  5950. case 0x01:
  5951. case 0x02:
  5952. case 0x03:
  5953. case 0x04:
  5954. case 0x05:
  5955. case 0x06:
  5956. case 0x07:
  5957. case 0x08:
  5958. case 0x09:
  5959. case 0x0A:
  5960. case 0x0B:
  5961. case 0x0C:
  5962. case 0x0D:
  5963. case 0x0E:
  5964. case 0x0F:
  5965. case 0x10:
  5966. case 0x11:
  5967. case 0x12:
  5968. case 0x13:
  5969. case 0x14:
  5970. case 0x15:
  5971. case 0x16:
  5972. case 0x17:
  5973. case 0x18:
  5974. case 0x19:
  5975. case 0x1A:
  5976. case 0x1B:
  5977. case 0x1C:
  5978. case 0x1D:
  5979. case 0x1E:
  5980. case 0x1F:
  5981. case 0x20:
  5982. case 0x21:
  5983. case 0x22:
  5984. case 0x23:
  5985. case 0x24:
  5986. case 0x25:
  5987. case 0x26:
  5988. case 0x27:
  5989. case 0x28:
  5990. case 0x29:
  5991. case 0x2A:
  5992. case 0x2B:
  5993. case 0x2C:
  5994. case 0x2D:
  5995. case 0x2E:
  5996. case 0x2F:
  5997. case 0x30:
  5998. case 0x31:
  5999. case 0x32:
  6000. case 0x33:
  6001. case 0x34:
  6002. case 0x35:
  6003. case 0x36:
  6004. case 0x37:
  6005. case 0x38:
  6006. case 0x39:
  6007. case 0x3A:
  6008. case 0x3B:
  6009. case 0x3C:
  6010. case 0x3D:
  6011. case 0x3E:
  6012. case 0x3F:
  6013. case 0x40:
  6014. case 0x41:
  6015. case 0x42:
  6016. case 0x43:
  6017. case 0x44:
  6018. case 0x45:
  6019. case 0x46:
  6020. case 0x47:
  6021. case 0x48:
  6022. case 0x49:
  6023. case 0x4A:
  6024. case 0x4B:
  6025. case 0x4C:
  6026. case 0x4D:
  6027. case 0x4E:
  6028. case 0x4F:
  6029. case 0x50:
  6030. case 0x51:
  6031. case 0x52:
  6032. case 0x53:
  6033. case 0x54:
  6034. case 0x55:
  6035. case 0x56:
  6036. case 0x57:
  6037. case 0x58:
  6038. case 0x59:
  6039. case 0x5A:
  6040. case 0x5B:
  6041. case 0x5C:
  6042. case 0x5D:
  6043. case 0x5E:
  6044. case 0x5F:
  6045. case 0x60:
  6046. case 0x61:
  6047. case 0x62:
  6048. case 0x63:
  6049. case 0x64:
  6050. case 0x65:
  6051. case 0x66:
  6052. case 0x67:
  6053. case 0x68:
  6054. case 0x69:
  6055. case 0x6A:
  6056. case 0x6B:
  6057. case 0x6C:
  6058. case 0x6D:
  6059. case 0x6E:
  6060. case 0x6F:
  6061. case 0x70:
  6062. case 0x71:
  6063. case 0x72:
  6064. case 0x73:
  6065. case 0x74:
  6066. case 0x75:
  6067. case 0x76:
  6068. case 0x77:
  6069. case 0x78:
  6070. case 0x79:
  6071. case 0x7A:
  6072. case 0x7B:
  6073. case 0x7C:
  6074. case 0x7D:
  6075. case 0x7E:
  6076. case 0x7F:
  6077. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  6078. // fixmap
  6079. case 0x80:
  6080. case 0x81:
  6081. case 0x82:
  6082. case 0x83:
  6083. case 0x84:
  6084. case 0x85:
  6085. case 0x86:
  6086. case 0x87:
  6087. case 0x88:
  6088. case 0x89:
  6089. case 0x8A:
  6090. case 0x8B:
  6091. case 0x8C:
  6092. case 0x8D:
  6093. case 0x8E:
  6094. case 0x8F:
  6095. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  6096. // fixarray
  6097. case 0x90:
  6098. case 0x91:
  6099. case 0x92:
  6100. case 0x93:
  6101. case 0x94:
  6102. case 0x95:
  6103. case 0x96:
  6104. case 0x97:
  6105. case 0x98:
  6106. case 0x99:
  6107. case 0x9A:
  6108. case 0x9B:
  6109. case 0x9C:
  6110. case 0x9D:
  6111. case 0x9E:
  6112. case 0x9F:
  6113. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  6114. // fixstr
  6115. case 0xA0:
  6116. case 0xA1:
  6117. case 0xA2:
  6118. case 0xA3:
  6119. case 0xA4:
  6120. case 0xA5:
  6121. case 0xA6:
  6122. case 0xA7:
  6123. case 0xA8:
  6124. case 0xA9:
  6125. case 0xAA:
  6126. case 0xAB:
  6127. case 0xAC:
  6128. case 0xAD:
  6129. case 0xAE:
  6130. case 0xAF:
  6131. case 0xB0:
  6132. case 0xB1:
  6133. case 0xB2:
  6134. case 0xB3:
  6135. case 0xB4:
  6136. case 0xB5:
  6137. case 0xB6:
  6138. case 0xB7:
  6139. case 0xB8:
  6140. case 0xB9:
  6141. case 0xBA:
  6142. case 0xBB:
  6143. case 0xBC:
  6144. case 0xBD:
  6145. case 0xBE:
  6146. case 0xBF:
  6147. case 0xD9: // str 8
  6148. case 0xDA: // str 16
  6149. case 0xDB: // str 32
  6150. {
  6151. string_t s;
  6152. return get_msgpack_string(s) && sax->string(s);
  6153. }
  6154. case 0xC0: // nil
  6155. return sax->null();
  6156. case 0xC2: // false
  6157. return sax->boolean(false);
  6158. case 0xC3: // true
  6159. return sax->boolean(true);
  6160. case 0xC4: // bin 8
  6161. case 0xC5: // bin 16
  6162. case 0xC6: // bin 32
  6163. case 0xC7: // ext 8
  6164. case 0xC8: // ext 16
  6165. case 0xC9: // ext 32
  6166. case 0xD4: // fixext 1
  6167. case 0xD5: // fixext 2
  6168. case 0xD6: // fixext 4
  6169. case 0xD7: // fixext 8
  6170. case 0xD8: // fixext 16
  6171. {
  6172. binary_t b;
  6173. return get_msgpack_binary(b) && sax->binary(b);
  6174. }
  6175. case 0xCA: // float 32
  6176. {
  6177. float number{};
  6178. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  6179. }
  6180. case 0xCB: // float 64
  6181. {
  6182. double number{};
  6183. return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast<number_float_t>(number), "");
  6184. }
  6185. case 0xCC: // uint 8
  6186. {
  6187. std::uint8_t number{};
  6188. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  6189. }
  6190. case 0xCD: // uint 16
  6191. {
  6192. std::uint16_t number{};
  6193. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  6194. }
  6195. case 0xCE: // uint 32
  6196. {
  6197. std::uint32_t number{};
  6198. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  6199. }
  6200. case 0xCF: // uint 64
  6201. {
  6202. std::uint64_t number{};
  6203. return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number);
  6204. }
  6205. case 0xD0: // int 8
  6206. {
  6207. std::int8_t number{};
  6208. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  6209. }
  6210. case 0xD1: // int 16
  6211. {
  6212. std::int16_t number{};
  6213. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  6214. }
  6215. case 0xD2: // int 32
  6216. {
  6217. std::int32_t number{};
  6218. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  6219. }
  6220. case 0xD3: // int 64
  6221. {
  6222. std::int64_t number{};
  6223. return get_number(input_format_t::msgpack, number) && sax->number_integer(number);
  6224. }
  6225. case 0xDC: // array 16
  6226. {
  6227. std::uint16_t len{};
  6228. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  6229. }
  6230. case 0xDD: // array 32
  6231. {
  6232. std::uint32_t len{};
  6233. return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast<std::size_t>(len));
  6234. }
  6235. case 0xDE: // map 16
  6236. {
  6237. std::uint16_t len{};
  6238. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  6239. }
  6240. case 0xDF: // map 32
  6241. {
  6242. std::uint32_t len{};
  6243. return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast<std::size_t>(len));
  6244. }
  6245. // negative fixint
  6246. case 0xE0:
  6247. case 0xE1:
  6248. case 0xE2:
  6249. case 0xE3:
  6250. case 0xE4:
  6251. case 0xE5:
  6252. case 0xE6:
  6253. case 0xE7:
  6254. case 0xE8:
  6255. case 0xE9:
  6256. case 0xEA:
  6257. case 0xEB:
  6258. case 0xEC:
  6259. case 0xED:
  6260. case 0xEE:
  6261. case 0xEF:
  6262. case 0xF0:
  6263. case 0xF1:
  6264. case 0xF2:
  6265. case 0xF3:
  6266. case 0xF4:
  6267. case 0xF5:
  6268. case 0xF6:
  6269. case 0xF7:
  6270. case 0xF8:
  6271. case 0xF9:
  6272. case 0xFA:
  6273. case 0xFB:
  6274. case 0xFC:
  6275. case 0xFD:
  6276. case 0xFE:
  6277. case 0xFF:
  6278. return sax->number_integer(static_cast<std::int8_t>(current));
  6279. default: // anything else
  6280. {
  6281. auto last_token = get_token_string();
  6282. 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")));
  6283. }
  6284. }
  6285. }
  6286. /*!
  6287. @brief reads a MessagePack string
  6288. This function first reads starting bytes to determine the expected
  6289. string length and then copies this number of bytes into a string.
  6290. @param[out] result created string
  6291. @return whether string creation completed
  6292. */
  6293. bool get_msgpack_string(string_t& result)
  6294. {
  6295. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string")))
  6296. {
  6297. return false;
  6298. }
  6299. switch (current)
  6300. {
  6301. // fixstr
  6302. case 0xA0:
  6303. case 0xA1:
  6304. case 0xA2:
  6305. case 0xA3:
  6306. case 0xA4:
  6307. case 0xA5:
  6308. case 0xA6:
  6309. case 0xA7:
  6310. case 0xA8:
  6311. case 0xA9:
  6312. case 0xAA:
  6313. case 0xAB:
  6314. case 0xAC:
  6315. case 0xAD:
  6316. case 0xAE:
  6317. case 0xAF:
  6318. case 0xB0:
  6319. case 0xB1:
  6320. case 0xB2:
  6321. case 0xB3:
  6322. case 0xB4:
  6323. case 0xB5:
  6324. case 0xB6:
  6325. case 0xB7:
  6326. case 0xB8:
  6327. case 0xB9:
  6328. case 0xBA:
  6329. case 0xBB:
  6330. case 0xBC:
  6331. case 0xBD:
  6332. case 0xBE:
  6333. case 0xBF:
  6334. {
  6335. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  6336. }
  6337. case 0xD9: // str 8
  6338. {
  6339. std::uint8_t len{};
  6340. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  6341. }
  6342. case 0xDA: // str 16
  6343. {
  6344. std::uint16_t len{};
  6345. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  6346. }
  6347. case 0xDB: // str 32
  6348. {
  6349. std::uint32_t len{};
  6350. return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result);
  6351. }
  6352. default:
  6353. {
  6354. auto last_token = get_token_string();
  6355. 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")));
  6356. }
  6357. }
  6358. }
  6359. /*!
  6360. @brief reads a MessagePack byte array
  6361. This function first reads starting bytes to determine the expected
  6362. byte array length and then copies this number of bytes into a byte array.
  6363. @param[out] result created byte array
  6364. @return whether byte array creation completed
  6365. */
  6366. bool get_msgpack_binary(binary_t& result)
  6367. {
  6368. // helper function to set the subtype
  6369. auto assign_and_return_true = [&result](std::int8_t subtype)
  6370. {
  6371. result.set_subtype(static_cast<std::uint8_t>(subtype));
  6372. return true;
  6373. };
  6374. switch (current)
  6375. {
  6376. case 0xC4: // bin 8
  6377. {
  6378. std::uint8_t len{};
  6379. return get_number(input_format_t::msgpack, len) &&
  6380. get_binary(input_format_t::msgpack, len, result);
  6381. }
  6382. case 0xC5: // bin 16
  6383. {
  6384. std::uint16_t len{};
  6385. return get_number(input_format_t::msgpack, len) &&
  6386. get_binary(input_format_t::msgpack, len, result);
  6387. }
  6388. case 0xC6: // bin 32
  6389. {
  6390. std::uint32_t len{};
  6391. return get_number(input_format_t::msgpack, len) &&
  6392. get_binary(input_format_t::msgpack, len, result);
  6393. }
  6394. case 0xC7: // ext 8
  6395. {
  6396. std::uint8_t len{};
  6397. std::int8_t subtype{};
  6398. return get_number(input_format_t::msgpack, len) &&
  6399. get_number(input_format_t::msgpack, subtype) &&
  6400. get_binary(input_format_t::msgpack, len, result) &&
  6401. assign_and_return_true(subtype);
  6402. }
  6403. case 0xC8: // ext 16
  6404. {
  6405. std::uint16_t len{};
  6406. std::int8_t subtype{};
  6407. return get_number(input_format_t::msgpack, len) &&
  6408. get_number(input_format_t::msgpack, subtype) &&
  6409. get_binary(input_format_t::msgpack, len, result) &&
  6410. assign_and_return_true(subtype);
  6411. }
  6412. case 0xC9: // ext 32
  6413. {
  6414. std::uint32_t len{};
  6415. std::int8_t subtype{};
  6416. return get_number(input_format_t::msgpack, len) &&
  6417. get_number(input_format_t::msgpack, subtype) &&
  6418. get_binary(input_format_t::msgpack, len, result) &&
  6419. assign_and_return_true(subtype);
  6420. }
  6421. case 0xD4: // fixext 1
  6422. {
  6423. std::int8_t subtype{};
  6424. return get_number(input_format_t::msgpack, subtype) &&
  6425. get_binary(input_format_t::msgpack, 1, result) &&
  6426. assign_and_return_true(subtype);
  6427. }
  6428. case 0xD5: // fixext 2
  6429. {
  6430. std::int8_t subtype{};
  6431. return get_number(input_format_t::msgpack, subtype) &&
  6432. get_binary(input_format_t::msgpack, 2, result) &&
  6433. assign_and_return_true(subtype);
  6434. }
  6435. case 0xD6: // fixext 4
  6436. {
  6437. std::int8_t subtype{};
  6438. return get_number(input_format_t::msgpack, subtype) &&
  6439. get_binary(input_format_t::msgpack, 4, result) &&
  6440. assign_and_return_true(subtype);
  6441. }
  6442. case 0xD7: // fixext 8
  6443. {
  6444. std::int8_t subtype{};
  6445. return get_number(input_format_t::msgpack, subtype) &&
  6446. get_binary(input_format_t::msgpack, 8, result) &&
  6447. assign_and_return_true(subtype);
  6448. }
  6449. case 0xD8: // fixext 16
  6450. {
  6451. std::int8_t subtype{};
  6452. return get_number(input_format_t::msgpack, subtype) &&
  6453. get_binary(input_format_t::msgpack, 16, result) &&
  6454. assign_and_return_true(subtype);
  6455. }
  6456. default: // LCOV_EXCL_LINE
  6457. return false; // LCOV_EXCL_LINE
  6458. }
  6459. }
  6460. /*!
  6461. @param[in] len the length of the array
  6462. @return whether array creation completed
  6463. */
  6464. bool get_msgpack_array(const std::size_t len)
  6465. {
  6466. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len)))
  6467. {
  6468. return false;
  6469. }
  6470. for (std::size_t i = 0; i < len; ++i)
  6471. {
  6472. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  6473. {
  6474. return false;
  6475. }
  6476. }
  6477. return sax->end_array();
  6478. }
  6479. /*!
  6480. @param[in] len the length of the object
  6481. @return whether object creation completed
  6482. */
  6483. bool get_msgpack_object(const std::size_t len)
  6484. {
  6485. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len)))
  6486. {
  6487. return false;
  6488. }
  6489. string_t key;
  6490. for (std::size_t i = 0; i < len; ++i)
  6491. {
  6492. get();
  6493. if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key)))
  6494. {
  6495. return false;
  6496. }
  6497. if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal()))
  6498. {
  6499. return false;
  6500. }
  6501. key.clear();
  6502. }
  6503. return sax->end_object();
  6504. }
  6505. ////////////
  6506. // UBJSON //
  6507. ////////////
  6508. /*!
  6509. @param[in] get_char whether a new character should be retrieved from the
  6510. input (true, default) or whether the last read
  6511. character should be considered instead
  6512. @return whether a valid UBJSON value was passed to the SAX parser
  6513. */
  6514. bool parse_ubjson_internal(const bool get_char = true)
  6515. {
  6516. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  6517. }
  6518. /*!
  6519. @brief reads a UBJSON string
  6520. This function is either called after reading the 'S' byte explicitly
  6521. indicating a string, or in case of an object key where the 'S' byte can be
  6522. left out.
  6523. @param[out] result created string
  6524. @param[in] get_char whether a new character should be retrieved from the
  6525. input (true, default) or whether the last read
  6526. character should be considered instead
  6527. @return whether string creation completed
  6528. */
  6529. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6530. {
  6531. if (get_char)
  6532. {
  6533. get(); // TODO(niels): may we ignore N here?
  6534. }
  6535. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  6536. {
  6537. return false;
  6538. }
  6539. switch (current)
  6540. {
  6541. case 'U':
  6542. {
  6543. std::uint8_t len{};
  6544. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  6545. }
  6546. case 'i':
  6547. {
  6548. std::int8_t len{};
  6549. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  6550. }
  6551. case 'I':
  6552. {
  6553. std::int16_t len{};
  6554. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  6555. }
  6556. case 'l':
  6557. {
  6558. std::int32_t len{};
  6559. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  6560. }
  6561. case 'L':
  6562. {
  6563. std::int64_t len{};
  6564. return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result);
  6565. }
  6566. default:
  6567. auto last_token = get_token_string();
  6568. 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")));
  6569. }
  6570. }
  6571. /*!
  6572. @param[out] result determined size
  6573. @return whether size determination completed
  6574. */
  6575. bool get_ubjson_size_value(std::size_t& result)
  6576. {
  6577. switch (get_ignore_noop())
  6578. {
  6579. case 'U':
  6580. {
  6581. std::uint8_t number{};
  6582. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  6583. {
  6584. return false;
  6585. }
  6586. result = static_cast<std::size_t>(number);
  6587. return true;
  6588. }
  6589. case 'i':
  6590. {
  6591. std::int8_t number{};
  6592. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  6593. {
  6594. return false;
  6595. }
  6596. result = static_cast<std::size_t>(number);
  6597. return true;
  6598. }
  6599. case 'I':
  6600. {
  6601. std::int16_t number{};
  6602. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  6603. {
  6604. return false;
  6605. }
  6606. result = static_cast<std::size_t>(number);
  6607. return true;
  6608. }
  6609. case 'l':
  6610. {
  6611. std::int32_t number{};
  6612. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  6613. {
  6614. return false;
  6615. }
  6616. result = static_cast<std::size_t>(number);
  6617. return true;
  6618. }
  6619. case 'L':
  6620. {
  6621. std::int64_t number{};
  6622. if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number)))
  6623. {
  6624. return false;
  6625. }
  6626. result = static_cast<std::size_t>(number);
  6627. return true;
  6628. }
  6629. default:
  6630. {
  6631. auto last_token = get_token_string();
  6632. 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")));
  6633. }
  6634. }
  6635. }
  6636. /*!
  6637. @brief determine the type and size for a container
  6638. In the optimized UBJSON format, a type and a size can be provided to allow
  6639. for a more compact representation.
  6640. @param[out] result pair of the size and the type
  6641. @return whether pair creation completed
  6642. */
  6643. bool get_ubjson_size_type(std::pair<std::size_t, char_int_type>& result)
  6644. {
  6645. result.first = string_t::npos; // size
  6646. result.second = 0; // type
  6647. get_ignore_noop();
  6648. if (current == '$')
  6649. {
  6650. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6651. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type")))
  6652. {
  6653. return false;
  6654. }
  6655. get_ignore_noop();
  6656. if (JSON_HEDLEY_UNLIKELY(current != '#'))
  6657. {
  6658. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value")))
  6659. {
  6660. return false;
  6661. }
  6662. auto last_token = get_token_string();
  6663. 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")));
  6664. }
  6665. return get_ubjson_size_value(result.first);
  6666. }
  6667. if (current == '#')
  6668. {
  6669. return get_ubjson_size_value(result.first);
  6670. }
  6671. return true;
  6672. }
  6673. /*!
  6674. @param prefix the previously read or set type prefix
  6675. @return whether value creation completed
  6676. */
  6677. bool get_ubjson_value(const char_int_type prefix)
  6678. {
  6679. switch (prefix)
  6680. {
  6681. case std::char_traits<char_type>::eof(): // EOF
  6682. return unexpect_eof(input_format_t::ubjson, "value");
  6683. case 'T': // true
  6684. return sax->boolean(true);
  6685. case 'F': // false
  6686. return sax->boolean(false);
  6687. case 'Z': // null
  6688. return sax->null();
  6689. case 'U':
  6690. {
  6691. std::uint8_t number{};
  6692. return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number);
  6693. }
  6694. case 'i':
  6695. {
  6696. std::int8_t number{};
  6697. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  6698. }
  6699. case 'I':
  6700. {
  6701. std::int16_t number{};
  6702. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  6703. }
  6704. case 'l':
  6705. {
  6706. std::int32_t number{};
  6707. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  6708. }
  6709. case 'L':
  6710. {
  6711. std::int64_t number{};
  6712. return get_number(input_format_t::ubjson, number) && sax->number_integer(number);
  6713. }
  6714. case 'd':
  6715. {
  6716. float number{};
  6717. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  6718. }
  6719. case 'D':
  6720. {
  6721. double number{};
  6722. return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast<number_float_t>(number), "");
  6723. }
  6724. case 'C': // char
  6725. {
  6726. get();
  6727. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char")))
  6728. {
  6729. return false;
  6730. }
  6731. if (JSON_HEDLEY_UNLIKELY(current > 127))
  6732. {
  6733. auto last_token = get_token_string();
  6734. 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")));
  6735. }
  6736. string_t s(1, static_cast<typename string_t::value_type>(current));
  6737. return sax->string(s);
  6738. }
  6739. case 'S': // string
  6740. {
  6741. string_t s;
  6742. return get_ubjson_string(s) && sax->string(s);
  6743. }
  6744. case '[': // array
  6745. return get_ubjson_array();
  6746. case '{': // object
  6747. return get_ubjson_object();
  6748. default: // anything else
  6749. {
  6750. auto last_token = get_token_string();
  6751. 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")));
  6752. }
  6753. }
  6754. }
  6755. /*!
  6756. @return whether array creation completed
  6757. */
  6758. bool get_ubjson_array()
  6759. {
  6760. std::pair<std::size_t, char_int_type> size_and_type;
  6761. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  6762. {
  6763. return false;
  6764. }
  6765. if (size_and_type.first != string_t::npos)
  6766. {
  6767. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first)))
  6768. {
  6769. return false;
  6770. }
  6771. if (size_and_type.second != 0)
  6772. {
  6773. if (size_and_type.second != 'N')
  6774. {
  6775. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6776. {
  6777. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  6778. {
  6779. return false;
  6780. }
  6781. }
  6782. }
  6783. }
  6784. else
  6785. {
  6786. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6787. {
  6788. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  6789. {
  6790. return false;
  6791. }
  6792. }
  6793. }
  6794. }
  6795. else
  6796. {
  6797. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  6798. {
  6799. return false;
  6800. }
  6801. while (current != ']')
  6802. {
  6803. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false)))
  6804. {
  6805. return false;
  6806. }
  6807. get_ignore_noop();
  6808. }
  6809. }
  6810. return sax->end_array();
  6811. }
  6812. /*!
  6813. @return whether object creation completed
  6814. */
  6815. bool get_ubjson_object()
  6816. {
  6817. std::pair<std::size_t, char_int_type> size_and_type;
  6818. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type)))
  6819. {
  6820. return false;
  6821. }
  6822. string_t key;
  6823. if (size_and_type.first != string_t::npos)
  6824. {
  6825. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first)))
  6826. {
  6827. return false;
  6828. }
  6829. if (size_and_type.second != 0)
  6830. {
  6831. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6832. {
  6833. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  6834. {
  6835. return false;
  6836. }
  6837. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second)))
  6838. {
  6839. return false;
  6840. }
  6841. key.clear();
  6842. }
  6843. }
  6844. else
  6845. {
  6846. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6847. {
  6848. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key)))
  6849. {
  6850. return false;
  6851. }
  6852. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  6853. {
  6854. return false;
  6855. }
  6856. key.clear();
  6857. }
  6858. }
  6859. }
  6860. else
  6861. {
  6862. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  6863. {
  6864. return false;
  6865. }
  6866. while (current != '}')
  6867. {
  6868. if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key)))
  6869. {
  6870. return false;
  6871. }
  6872. if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal()))
  6873. {
  6874. return false;
  6875. }
  6876. get_ignore_noop();
  6877. key.clear();
  6878. }
  6879. }
  6880. return sax->end_object();
  6881. }
  6882. // Note, no reader for UBJSON binary types is implemented because they do
  6883. // not exist
  6884. ///////////////////////
  6885. // Utility functions //
  6886. ///////////////////////
  6887. /*!
  6888. @brief get next character from the input
  6889. This function provides the interface to the used input adapter. It does
  6890. not throw in case the input reached EOF, but returns a -'ve valued
  6891. `std::char_traits<char_type>::eof()` in that case.
  6892. @return character read from the input
  6893. */
  6894. char_int_type get()
  6895. {
  6896. ++chars_read;
  6897. return current = ia.get_character();
  6898. }
  6899. /*!
  6900. @return character read from the input after ignoring all 'N' entries
  6901. */
  6902. char_int_type get_ignore_noop()
  6903. {
  6904. do
  6905. {
  6906. get();
  6907. }
  6908. while (current == 'N');
  6909. return current;
  6910. }
  6911. /*
  6912. @brief read a number from the input
  6913. @tparam NumberType the type of the number
  6914. @param[in] format the current format (for diagnostics)
  6915. @param[out] result number of type @a NumberType
  6916. @return whether conversion completed
  6917. @note This function needs to respect the system's endianess, because
  6918. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  6919. (big endian) and therefore need reordering on little endian systems.
  6920. */
  6921. template<typename NumberType, bool InputIsLittleEndian = false>
  6922. bool get_number(const input_format_t format, NumberType& result)
  6923. {
  6924. // step 1: read input into array with system's byte order
  6925. std::array<std::uint8_t, sizeof(NumberType)> vec;
  6926. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  6927. {
  6928. get();
  6929. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number")))
  6930. {
  6931. return false;
  6932. }
  6933. // reverse byte order prior to conversion if necessary
  6934. if (is_little_endian != InputIsLittleEndian)
  6935. {
  6936. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  6937. }
  6938. else
  6939. {
  6940. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  6941. }
  6942. }
  6943. // step 2: convert array into number of type T and return
  6944. std::memcpy(&result, vec.data(), sizeof(NumberType));
  6945. return true;
  6946. }
  6947. /*!
  6948. @brief create a string by reading characters from the input
  6949. @tparam NumberType the type of the number
  6950. @param[in] format the current format (for diagnostics)
  6951. @param[in] len number of characters to read
  6952. @param[out] result string created by reading @a len bytes
  6953. @return whether string creation completed
  6954. @note We can not reserve @a len bytes for the result, because @a len
  6955. may be too large. Usually, @ref unexpect_eof() detects the end of
  6956. the input before we run out of string memory.
  6957. */
  6958. template<typename NumberType>
  6959. bool get_string(const input_format_t format,
  6960. const NumberType len,
  6961. string_t& result)
  6962. {
  6963. bool success = true;
  6964. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6965. {
  6966. get();
  6967. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string")))
  6968. {
  6969. success = false;
  6970. }
  6971. return std::char_traits<char_type>::to_char_type(current);
  6972. });
  6973. return success;
  6974. }
  6975. /*!
  6976. @brief create a byte array by reading bytes from the input
  6977. @tparam NumberType the type of the number
  6978. @param[in] format the current format (for diagnostics)
  6979. @param[in] len number of bytes to read
  6980. @param[out] result byte array created by reading @a len bytes
  6981. @return whether byte array creation completed
  6982. @note We can not reserve @a len bytes for the result, because @a len
  6983. may be too large. Usually, @ref unexpect_eof() detects the end of
  6984. the input before we run out of memory.
  6985. */
  6986. template<typename NumberType>
  6987. bool get_binary(const input_format_t format,
  6988. const NumberType len,
  6989. binary_t& result)
  6990. {
  6991. bool success = true;
  6992. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  6993. {
  6994. get();
  6995. if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary")))
  6996. {
  6997. success = false;
  6998. }
  6999. return static_cast<std::uint8_t>(current);
  7000. });
  7001. return success;
  7002. }
  7003. /*!
  7004. @param[in] format the current format (for diagnostics)
  7005. @param[in] context further context information (for diagnostics)
  7006. @return whether the last read character is not EOF
  7007. */
  7008. JSON_HEDLEY_NON_NULL(3)
  7009. bool unexpect_eof(const input_format_t format, const char* context) const
  7010. {
  7011. if (JSON_HEDLEY_UNLIKELY(current == std::char_traits<char_type>::eof()))
  7012. {
  7013. return sax->parse_error(chars_read, "<end of file>",
  7014. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  7015. }
  7016. return true;
  7017. }
  7018. /*!
  7019. @return a string representation of the last read byte
  7020. */
  7021. std::string get_token_string() const
  7022. {
  7023. std::array<char, 3> cr{{}};
  7024. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  7025. return std::string{cr.data()};
  7026. }
  7027. /*!
  7028. @param[in] format the current format
  7029. @param[in] detail a detailed error message
  7030. @param[in] context further context information
  7031. @return a message string to use in the parse_error exceptions
  7032. */
  7033. std::string exception_message(const input_format_t format,
  7034. const std::string& detail,
  7035. const std::string& context) const
  7036. {
  7037. std::string error_msg = "syntax error while parsing ";
  7038. switch (format)
  7039. {
  7040. case input_format_t::cbor:
  7041. error_msg += "CBOR";
  7042. break;
  7043. case input_format_t::msgpack:
  7044. error_msg += "MessagePack";
  7045. break;
  7046. case input_format_t::ubjson:
  7047. error_msg += "UBJSON";
  7048. break;
  7049. case input_format_t::bson:
  7050. error_msg += "BSON";
  7051. break;
  7052. default: // LCOV_EXCL_LINE
  7053. JSON_ASSERT(false); // LCOV_EXCL_LINE
  7054. }
  7055. return error_msg + " " + context + ": " + detail;
  7056. }
  7057. private:
  7058. /// input adapter
  7059. InputAdapterType ia;
  7060. /// the current character
  7061. char_int_type current = std::char_traits<char_type>::eof();
  7062. /// the number of characters read
  7063. std::size_t chars_read = 0;
  7064. /// whether we can assume little endianess
  7065. const bool is_little_endian = little_endianess();
  7066. /// the SAX parser
  7067. json_sax_t* sax = nullptr;
  7068. };
  7069. } // namespace detail
  7070. } // namespace nlohmann
  7071. // #include <nlohmann/detail/input/input_adapters.hpp>
  7072. // #include <nlohmann/detail/input/lexer.hpp>
  7073. #include <array> // array
  7074. #include <clocale> // localeconv
  7075. #include <cstddef> // size_t
  7076. #include <cstdio> // snprintf
  7077. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  7078. #include <initializer_list> // initializer_list
  7079. #include <string> // char_traits, string
  7080. #include <utility> // move
  7081. #include <vector> // vector
  7082. // #include <nlohmann/detail/input/input_adapters.hpp>
  7083. // #include <nlohmann/detail/input/position_t.hpp>
  7084. // #include <nlohmann/detail/macro_scope.hpp>
  7085. namespace nlohmann
  7086. {
  7087. namespace detail
  7088. {
  7089. ///////////
  7090. // lexer //
  7091. ///////////
  7092. template<typename BasicJsonType>
  7093. class lexer_base
  7094. {
  7095. public:
  7096. /// token types for the parser
  7097. enum class token_type
  7098. {
  7099. uninitialized, ///< indicating the scanner is uninitialized
  7100. literal_true, ///< the `true` literal
  7101. literal_false, ///< the `false` literal
  7102. literal_null, ///< the `null` literal
  7103. value_string, ///< a string -- use get_string() for actual value
  7104. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  7105. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  7106. value_float, ///< an floating point number -- use get_number_float() for actual value
  7107. begin_array, ///< the character for array begin `[`
  7108. begin_object, ///< the character for object begin `{`
  7109. end_array, ///< the character for array end `]`
  7110. end_object, ///< the character for object end `}`
  7111. name_separator, ///< the name separator `:`
  7112. value_separator, ///< the value separator `,`
  7113. parse_error, ///< indicating a parse error
  7114. end_of_input, ///< indicating the end of the input buffer
  7115. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  7116. };
  7117. /// return name of values of type token_type (only used for errors)
  7118. JSON_HEDLEY_RETURNS_NON_NULL
  7119. JSON_HEDLEY_CONST
  7120. static const char* token_type_name(const token_type t) noexcept
  7121. {
  7122. switch (t)
  7123. {
  7124. case token_type::uninitialized:
  7125. return "<uninitialized>";
  7126. case token_type::literal_true:
  7127. return "true literal";
  7128. case token_type::literal_false:
  7129. return "false literal";
  7130. case token_type::literal_null:
  7131. return "null literal";
  7132. case token_type::value_string:
  7133. return "string literal";
  7134. case token_type::value_unsigned:
  7135. case token_type::value_integer:
  7136. case token_type::value_float:
  7137. return "number literal";
  7138. case token_type::begin_array:
  7139. return "'['";
  7140. case token_type::begin_object:
  7141. return "'{'";
  7142. case token_type::end_array:
  7143. return "']'";
  7144. case token_type::end_object:
  7145. return "'}'";
  7146. case token_type::name_separator:
  7147. return "':'";
  7148. case token_type::value_separator:
  7149. return "','";
  7150. case token_type::parse_error:
  7151. return "<parse error>";
  7152. case token_type::end_of_input:
  7153. return "end of input";
  7154. case token_type::literal_or_value:
  7155. return "'[', '{', or a literal";
  7156. // LCOV_EXCL_START
  7157. default: // catch non-enum values
  7158. return "unknown token";
  7159. // LCOV_EXCL_STOP
  7160. }
  7161. }
  7162. };
  7163. /*!
  7164. @brief lexical analysis
  7165. This class organizes the lexical analysis during JSON deserialization.
  7166. */
  7167. template<typename BasicJsonType, typename InputAdapterType>
  7168. class lexer : public lexer_base<BasicJsonType>
  7169. {
  7170. using number_integer_t = typename BasicJsonType::number_integer_t;
  7171. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  7172. using number_float_t = typename BasicJsonType::number_float_t;
  7173. using string_t = typename BasicJsonType::string_t;
  7174. using char_type = typename InputAdapterType::char_type;
  7175. using char_int_type = typename std::char_traits<char_type>::int_type;
  7176. public:
  7177. using token_type = typename lexer_base<BasicJsonType>::token_type;
  7178. explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false)
  7179. : ia(std::move(adapter))
  7180. , ignore_comments(ignore_comments_)
  7181. , decimal_point_char(static_cast<char_int_type>(get_decimal_point()))
  7182. {}
  7183. // delete because of pointer members
  7184. lexer(const lexer&) = delete;
  7185. lexer(lexer&&) = default;
  7186. lexer& operator=(lexer&) = delete;
  7187. lexer& operator=(lexer&&) = default;
  7188. ~lexer() = default;
  7189. private:
  7190. /////////////////////
  7191. // locales
  7192. /////////////////////
  7193. /// return the locale-dependent decimal point
  7194. JSON_HEDLEY_PURE
  7195. static char get_decimal_point() noexcept
  7196. {
  7197. const auto* loc = localeconv();
  7198. JSON_ASSERT(loc != nullptr);
  7199. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  7200. }
  7201. /////////////////////
  7202. // scan functions
  7203. /////////////////////
  7204. /*!
  7205. @brief get codepoint from 4 hex characters following `\u`
  7206. For input "\u c1 c2 c3 c4" the codepoint is:
  7207. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  7208. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  7209. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  7210. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  7211. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  7212. between the ASCII value of the character and the desired integer value.
  7213. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  7214. non-hex character)
  7215. */
  7216. int get_codepoint()
  7217. {
  7218. // this function only makes sense after reading `\u`
  7219. JSON_ASSERT(current == 'u');
  7220. int codepoint = 0;
  7221. const auto factors = { 12u, 8u, 4u, 0u };
  7222. for (const auto factor : factors)
  7223. {
  7224. get();
  7225. if (current >= '0' && current <= '9')
  7226. {
  7227. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  7228. }
  7229. else if (current >= 'A' && current <= 'F')
  7230. {
  7231. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  7232. }
  7233. else if (current >= 'a' && current <= 'f')
  7234. {
  7235. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  7236. }
  7237. else
  7238. {
  7239. return -1;
  7240. }
  7241. }
  7242. JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF);
  7243. return codepoint;
  7244. }
  7245. /*!
  7246. @brief check if the next byte(s) are inside a given range
  7247. Adds the current byte and, for each passed range, reads a new byte and
  7248. checks if it is inside the range. If a violation was detected, set up an
  7249. error message and return false. Otherwise, return true.
  7250. @param[in] ranges list of integers; interpreted as list of pairs of
  7251. inclusive lower and upper bound, respectively
  7252. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  7253. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  7254. @return true if and only if no range violation was detected
  7255. */
  7256. bool next_byte_in_range(std::initializer_list<char_int_type> ranges)
  7257. {
  7258. JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6);
  7259. add(current);
  7260. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  7261. {
  7262. get();
  7263. if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range)))
  7264. {
  7265. add(current);
  7266. }
  7267. else
  7268. {
  7269. error_message = "invalid string: ill-formed UTF-8 byte";
  7270. return false;
  7271. }
  7272. }
  7273. return true;
  7274. }
  7275. /*!
  7276. @brief scan a string literal
  7277. This function scans a string according to Sect. 7 of RFC 7159. While
  7278. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  7279. function returns successfully, token_buffer is *not* null-terminated (as it
  7280. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  7281. string.
  7282. @return token_type::value_string if string could be successfully scanned,
  7283. token_type::parse_error otherwise
  7284. @note In case of errors, variable error_message contains a textual
  7285. description.
  7286. */
  7287. token_type scan_string()
  7288. {
  7289. // reset token_buffer (ignore opening quote)
  7290. reset();
  7291. // we entered the function by reading an open quote
  7292. JSON_ASSERT(current == '\"');
  7293. while (true)
  7294. {
  7295. // get next character
  7296. switch (get())
  7297. {
  7298. // end of file while parsing string
  7299. case std::char_traits<char_type>::eof():
  7300. {
  7301. error_message = "invalid string: missing closing quote";
  7302. return token_type::parse_error;
  7303. }
  7304. // closing quote
  7305. case '\"':
  7306. {
  7307. return token_type::value_string;
  7308. }
  7309. // escapes
  7310. case '\\':
  7311. {
  7312. switch (get())
  7313. {
  7314. // quotation mark
  7315. case '\"':
  7316. add('\"');
  7317. break;
  7318. // reverse solidus
  7319. case '\\':
  7320. add('\\');
  7321. break;
  7322. // solidus
  7323. case '/':
  7324. add('/');
  7325. break;
  7326. // backspace
  7327. case 'b':
  7328. add('\b');
  7329. break;
  7330. // form feed
  7331. case 'f':
  7332. add('\f');
  7333. break;
  7334. // line feed
  7335. case 'n':
  7336. add('\n');
  7337. break;
  7338. // carriage return
  7339. case 'r':
  7340. add('\r');
  7341. break;
  7342. // tab
  7343. case 't':
  7344. add('\t');
  7345. break;
  7346. // unicode escapes
  7347. case 'u':
  7348. {
  7349. const int codepoint1 = get_codepoint();
  7350. int codepoint = codepoint1; // start with codepoint1
  7351. if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1))
  7352. {
  7353. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7354. return token_type::parse_error;
  7355. }
  7356. // check if code point is a high surrogate
  7357. if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF)
  7358. {
  7359. // expect next \uxxxx entry
  7360. if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u'))
  7361. {
  7362. const int codepoint2 = get_codepoint();
  7363. if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1))
  7364. {
  7365. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  7366. return token_type::parse_error;
  7367. }
  7368. // check if codepoint2 is a low surrogate
  7369. if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF))
  7370. {
  7371. // overwrite codepoint
  7372. codepoint = static_cast<int>(
  7373. // high surrogate occupies the most significant 22 bits
  7374. (static_cast<unsigned int>(codepoint1) << 10u)
  7375. // low surrogate occupies the least significant 15 bits
  7376. + static_cast<unsigned int>(codepoint2)
  7377. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  7378. // in the result so we have to subtract with:
  7379. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  7380. - 0x35FDC00u);
  7381. }
  7382. else
  7383. {
  7384. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7385. return token_type::parse_error;
  7386. }
  7387. }
  7388. else
  7389. {
  7390. error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF";
  7391. return token_type::parse_error;
  7392. }
  7393. }
  7394. else
  7395. {
  7396. if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF))
  7397. {
  7398. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  7399. return token_type::parse_error;
  7400. }
  7401. }
  7402. // result of the above calculation yields a proper codepoint
  7403. JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF);
  7404. // translate codepoint into bytes
  7405. if (codepoint < 0x80)
  7406. {
  7407. // 1-byte characters: 0xxxxxxx (ASCII)
  7408. add(static_cast<char_int_type>(codepoint));
  7409. }
  7410. else if (codepoint <= 0x7FF)
  7411. {
  7412. // 2-byte characters: 110xxxxx 10xxxxxx
  7413. add(static_cast<char_int_type>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  7414. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7415. }
  7416. else if (codepoint <= 0xFFFF)
  7417. {
  7418. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  7419. add(static_cast<char_int_type>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  7420. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7421. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7422. }
  7423. else
  7424. {
  7425. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  7426. add(static_cast<char_int_type>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  7427. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  7428. add(static_cast<char_int_type>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  7429. add(static_cast<char_int_type>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  7430. }
  7431. break;
  7432. }
  7433. // other characters after escape
  7434. default:
  7435. error_message = "invalid string: forbidden character after backslash";
  7436. return token_type::parse_error;
  7437. }
  7438. break;
  7439. }
  7440. // invalid control characters
  7441. case 0x00:
  7442. {
  7443. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  7444. return token_type::parse_error;
  7445. }
  7446. case 0x01:
  7447. {
  7448. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  7449. return token_type::parse_error;
  7450. }
  7451. case 0x02:
  7452. {
  7453. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  7454. return token_type::parse_error;
  7455. }
  7456. case 0x03:
  7457. {
  7458. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  7459. return token_type::parse_error;
  7460. }
  7461. case 0x04:
  7462. {
  7463. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  7464. return token_type::parse_error;
  7465. }
  7466. case 0x05:
  7467. {
  7468. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  7469. return token_type::parse_error;
  7470. }
  7471. case 0x06:
  7472. {
  7473. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  7474. return token_type::parse_error;
  7475. }
  7476. case 0x07:
  7477. {
  7478. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  7479. return token_type::parse_error;
  7480. }
  7481. case 0x08:
  7482. {
  7483. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  7484. return token_type::parse_error;
  7485. }
  7486. case 0x09:
  7487. {
  7488. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  7489. return token_type::parse_error;
  7490. }
  7491. case 0x0A:
  7492. {
  7493. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  7494. return token_type::parse_error;
  7495. }
  7496. case 0x0B:
  7497. {
  7498. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  7499. return token_type::parse_error;
  7500. }
  7501. case 0x0C:
  7502. {
  7503. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  7504. return token_type::parse_error;
  7505. }
  7506. case 0x0D:
  7507. {
  7508. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  7509. return token_type::parse_error;
  7510. }
  7511. case 0x0E:
  7512. {
  7513. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  7514. return token_type::parse_error;
  7515. }
  7516. case 0x0F:
  7517. {
  7518. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  7519. return token_type::parse_error;
  7520. }
  7521. case 0x10:
  7522. {
  7523. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  7524. return token_type::parse_error;
  7525. }
  7526. case 0x11:
  7527. {
  7528. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  7529. return token_type::parse_error;
  7530. }
  7531. case 0x12:
  7532. {
  7533. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  7534. return token_type::parse_error;
  7535. }
  7536. case 0x13:
  7537. {
  7538. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  7539. return token_type::parse_error;
  7540. }
  7541. case 0x14:
  7542. {
  7543. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  7544. return token_type::parse_error;
  7545. }
  7546. case 0x15:
  7547. {
  7548. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  7549. return token_type::parse_error;
  7550. }
  7551. case 0x16:
  7552. {
  7553. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  7554. return token_type::parse_error;
  7555. }
  7556. case 0x17:
  7557. {
  7558. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  7559. return token_type::parse_error;
  7560. }
  7561. case 0x18:
  7562. {
  7563. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  7564. return token_type::parse_error;
  7565. }
  7566. case 0x19:
  7567. {
  7568. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  7569. return token_type::parse_error;
  7570. }
  7571. case 0x1A:
  7572. {
  7573. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  7574. return token_type::parse_error;
  7575. }
  7576. case 0x1B:
  7577. {
  7578. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  7579. return token_type::parse_error;
  7580. }
  7581. case 0x1C:
  7582. {
  7583. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  7584. return token_type::parse_error;
  7585. }
  7586. case 0x1D:
  7587. {
  7588. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  7589. return token_type::parse_error;
  7590. }
  7591. case 0x1E:
  7592. {
  7593. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  7594. return token_type::parse_error;
  7595. }
  7596. case 0x1F:
  7597. {
  7598. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  7599. return token_type::parse_error;
  7600. }
  7601. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  7602. case 0x20:
  7603. case 0x21:
  7604. case 0x23:
  7605. case 0x24:
  7606. case 0x25:
  7607. case 0x26:
  7608. case 0x27:
  7609. case 0x28:
  7610. case 0x29:
  7611. case 0x2A:
  7612. case 0x2B:
  7613. case 0x2C:
  7614. case 0x2D:
  7615. case 0x2E:
  7616. case 0x2F:
  7617. case 0x30:
  7618. case 0x31:
  7619. case 0x32:
  7620. case 0x33:
  7621. case 0x34:
  7622. case 0x35:
  7623. case 0x36:
  7624. case 0x37:
  7625. case 0x38:
  7626. case 0x39:
  7627. case 0x3A:
  7628. case 0x3B:
  7629. case 0x3C:
  7630. case 0x3D:
  7631. case 0x3E:
  7632. case 0x3F:
  7633. case 0x40:
  7634. case 0x41:
  7635. case 0x42:
  7636. case 0x43:
  7637. case 0x44:
  7638. case 0x45:
  7639. case 0x46:
  7640. case 0x47:
  7641. case 0x48:
  7642. case 0x49:
  7643. case 0x4A:
  7644. case 0x4B:
  7645. case 0x4C:
  7646. case 0x4D:
  7647. case 0x4E:
  7648. case 0x4F:
  7649. case 0x50:
  7650. case 0x51:
  7651. case 0x52:
  7652. case 0x53:
  7653. case 0x54:
  7654. case 0x55:
  7655. case 0x56:
  7656. case 0x57:
  7657. case 0x58:
  7658. case 0x59:
  7659. case 0x5A:
  7660. case 0x5B:
  7661. case 0x5D:
  7662. case 0x5E:
  7663. case 0x5F:
  7664. case 0x60:
  7665. case 0x61:
  7666. case 0x62:
  7667. case 0x63:
  7668. case 0x64:
  7669. case 0x65:
  7670. case 0x66:
  7671. case 0x67:
  7672. case 0x68:
  7673. case 0x69:
  7674. case 0x6A:
  7675. case 0x6B:
  7676. case 0x6C:
  7677. case 0x6D:
  7678. case 0x6E:
  7679. case 0x6F:
  7680. case 0x70:
  7681. case 0x71:
  7682. case 0x72:
  7683. case 0x73:
  7684. case 0x74:
  7685. case 0x75:
  7686. case 0x76:
  7687. case 0x77:
  7688. case 0x78:
  7689. case 0x79:
  7690. case 0x7A:
  7691. case 0x7B:
  7692. case 0x7C:
  7693. case 0x7D:
  7694. case 0x7E:
  7695. case 0x7F:
  7696. {
  7697. add(current);
  7698. break;
  7699. }
  7700. // U+0080..U+07FF: bytes C2..DF 80..BF
  7701. case 0xC2:
  7702. case 0xC3:
  7703. case 0xC4:
  7704. case 0xC5:
  7705. case 0xC6:
  7706. case 0xC7:
  7707. case 0xC8:
  7708. case 0xC9:
  7709. case 0xCA:
  7710. case 0xCB:
  7711. case 0xCC:
  7712. case 0xCD:
  7713. case 0xCE:
  7714. case 0xCF:
  7715. case 0xD0:
  7716. case 0xD1:
  7717. case 0xD2:
  7718. case 0xD3:
  7719. case 0xD4:
  7720. case 0xD5:
  7721. case 0xD6:
  7722. case 0xD7:
  7723. case 0xD8:
  7724. case 0xD9:
  7725. case 0xDA:
  7726. case 0xDB:
  7727. case 0xDC:
  7728. case 0xDD:
  7729. case 0xDE:
  7730. case 0xDF:
  7731. {
  7732. if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF})))
  7733. {
  7734. return token_type::parse_error;
  7735. }
  7736. break;
  7737. }
  7738. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  7739. case 0xE0:
  7740. {
  7741. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  7742. {
  7743. return token_type::parse_error;
  7744. }
  7745. break;
  7746. }
  7747. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  7748. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  7749. case 0xE1:
  7750. case 0xE2:
  7751. case 0xE3:
  7752. case 0xE4:
  7753. case 0xE5:
  7754. case 0xE6:
  7755. case 0xE7:
  7756. case 0xE8:
  7757. case 0xE9:
  7758. case 0xEA:
  7759. case 0xEB:
  7760. case 0xEC:
  7761. case 0xEE:
  7762. case 0xEF:
  7763. {
  7764. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  7765. {
  7766. return token_type::parse_error;
  7767. }
  7768. break;
  7769. }
  7770. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  7771. case 0xED:
  7772. {
  7773. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  7774. {
  7775. return token_type::parse_error;
  7776. }
  7777. break;
  7778. }
  7779. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  7780. case 0xF0:
  7781. {
  7782. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7783. {
  7784. return token_type::parse_error;
  7785. }
  7786. break;
  7787. }
  7788. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  7789. case 0xF1:
  7790. case 0xF2:
  7791. case 0xF3:
  7792. {
  7793. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  7794. {
  7795. return token_type::parse_error;
  7796. }
  7797. break;
  7798. }
  7799. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  7800. case 0xF4:
  7801. {
  7802. if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  7803. {
  7804. return token_type::parse_error;
  7805. }
  7806. break;
  7807. }
  7808. // remaining bytes (80..C1 and F5..FF) are ill-formed
  7809. default:
  7810. {
  7811. error_message = "invalid string: ill-formed UTF-8 byte";
  7812. return token_type::parse_error;
  7813. }
  7814. }
  7815. }
  7816. }
  7817. /*!
  7818. * @brief scan a comment
  7819. * @return whether comment could be scanned successfully
  7820. */
  7821. bool scan_comment()
  7822. {
  7823. switch (get())
  7824. {
  7825. // single-line comments skip input until a newline or EOF is read
  7826. case '/':
  7827. {
  7828. while (true)
  7829. {
  7830. switch (get())
  7831. {
  7832. case '\n':
  7833. case '\r':
  7834. case std::char_traits<char_type>::eof():
  7835. case '\0':
  7836. return true;
  7837. default:
  7838. break;
  7839. }
  7840. }
  7841. }
  7842. // multi-line comments skip input until */ is read
  7843. case '*':
  7844. {
  7845. while (true)
  7846. {
  7847. switch (get())
  7848. {
  7849. case std::char_traits<char_type>::eof():
  7850. case '\0':
  7851. {
  7852. error_message = "invalid comment; missing closing '*/'";
  7853. return false;
  7854. }
  7855. case '*':
  7856. {
  7857. switch (get())
  7858. {
  7859. case '/':
  7860. return true;
  7861. default:
  7862. {
  7863. unget();
  7864. break;
  7865. }
  7866. }
  7867. }
  7868. default:
  7869. break;
  7870. }
  7871. }
  7872. }
  7873. // unexpected character after reading '/'
  7874. default:
  7875. {
  7876. error_message = "invalid comment; expecting '/' or '*' after '/'";
  7877. return false;
  7878. }
  7879. }
  7880. }
  7881. JSON_HEDLEY_NON_NULL(2)
  7882. static void strtof(float& f, const char* str, char** endptr) noexcept
  7883. {
  7884. f = std::strtof(str, endptr);
  7885. }
  7886. JSON_HEDLEY_NON_NULL(2)
  7887. static void strtof(double& f, const char* str, char** endptr) noexcept
  7888. {
  7889. f = std::strtod(str, endptr);
  7890. }
  7891. JSON_HEDLEY_NON_NULL(2)
  7892. static void strtof(long double& f, const char* str, char** endptr) noexcept
  7893. {
  7894. f = std::strtold(str, endptr);
  7895. }
  7896. /*!
  7897. @brief scan a number literal
  7898. This function scans a string according to Sect. 6 of RFC 7159.
  7899. The function is realized with a deterministic finite state machine derived
  7900. from the grammar described in RFC 7159. Starting in state "init", the
  7901. input is read and used to determined the next state. Only state "done"
  7902. accepts the number. State "error" is a trap state to model errors. In the
  7903. table below, "anything" means any character but the ones listed before.
  7904. state | 0 | 1-9 | e E | + | - | . | anything
  7905. ---------|----------|----------|----------|---------|---------|----------|-----------
  7906. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  7907. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  7908. zero | done | done | exponent | done | done | decimal1 | done
  7909. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  7910. decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error]
  7911. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  7912. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  7913. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  7914. any2 | any2 | any2 | done | done | done | done | done
  7915. The state machine is realized with one label per state (prefixed with
  7916. "scan_number_") and `goto` statements between them. The state machine
  7917. contains cycles, but any cycle can be left when EOF is read. Therefore,
  7918. the function is guaranteed to terminate.
  7919. During scanning, the read bytes are stored in token_buffer. This string is
  7920. then converted to a signed integer, an unsigned integer, or a
  7921. floating-point number.
  7922. @return token_type::value_unsigned, token_type::value_integer, or
  7923. token_type::value_float if number could be successfully scanned,
  7924. token_type::parse_error otherwise
  7925. @note The scanner is independent of the current locale. Internally, the
  7926. locale's decimal point is used instead of `.` to work with the
  7927. locale-dependent converters.
  7928. */
  7929. token_type scan_number() // lgtm [cpp/use-of-goto]
  7930. {
  7931. // reset token_buffer to store the number's bytes
  7932. reset();
  7933. // the type of the parsed number; initially set to unsigned; will be
  7934. // changed if minus sign, decimal point or exponent is read
  7935. token_type number_type = token_type::value_unsigned;
  7936. // state (init): we just found out we need to scan a number
  7937. switch (current)
  7938. {
  7939. case '-':
  7940. {
  7941. add(current);
  7942. goto scan_number_minus;
  7943. }
  7944. case '0':
  7945. {
  7946. add(current);
  7947. goto scan_number_zero;
  7948. }
  7949. case '1':
  7950. case '2':
  7951. case '3':
  7952. case '4':
  7953. case '5':
  7954. case '6':
  7955. case '7':
  7956. case '8':
  7957. case '9':
  7958. {
  7959. add(current);
  7960. goto scan_number_any1;
  7961. }
  7962. // all other characters are rejected outside scan_number()
  7963. default: // LCOV_EXCL_LINE
  7964. JSON_ASSERT(false); // LCOV_EXCL_LINE
  7965. }
  7966. scan_number_minus:
  7967. // state: we just parsed a leading minus sign
  7968. number_type = token_type::value_integer;
  7969. switch (get())
  7970. {
  7971. case '0':
  7972. {
  7973. add(current);
  7974. goto scan_number_zero;
  7975. }
  7976. case '1':
  7977. case '2':
  7978. case '3':
  7979. case '4':
  7980. case '5':
  7981. case '6':
  7982. case '7':
  7983. case '8':
  7984. case '9':
  7985. {
  7986. add(current);
  7987. goto scan_number_any1;
  7988. }
  7989. default:
  7990. {
  7991. error_message = "invalid number; expected digit after '-'";
  7992. return token_type::parse_error;
  7993. }
  7994. }
  7995. scan_number_zero:
  7996. // state: we just parse a zero (maybe with a leading minus sign)
  7997. switch (get())
  7998. {
  7999. case '.':
  8000. {
  8001. add(decimal_point_char);
  8002. goto scan_number_decimal1;
  8003. }
  8004. case 'e':
  8005. case 'E':
  8006. {
  8007. add(current);
  8008. goto scan_number_exponent;
  8009. }
  8010. default:
  8011. goto scan_number_done;
  8012. }
  8013. scan_number_any1:
  8014. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  8015. switch (get())
  8016. {
  8017. case '0':
  8018. case '1':
  8019. case '2':
  8020. case '3':
  8021. case '4':
  8022. case '5':
  8023. case '6':
  8024. case '7':
  8025. case '8':
  8026. case '9':
  8027. {
  8028. add(current);
  8029. goto scan_number_any1;
  8030. }
  8031. case '.':
  8032. {
  8033. add(decimal_point_char);
  8034. goto scan_number_decimal1;
  8035. }
  8036. case 'e':
  8037. case 'E':
  8038. {
  8039. add(current);
  8040. goto scan_number_exponent;
  8041. }
  8042. default:
  8043. goto scan_number_done;
  8044. }
  8045. scan_number_decimal1:
  8046. // state: we just parsed a decimal point
  8047. number_type = token_type::value_float;
  8048. switch (get())
  8049. {
  8050. case '0':
  8051. case '1':
  8052. case '2':
  8053. case '3':
  8054. case '4':
  8055. case '5':
  8056. case '6':
  8057. case '7':
  8058. case '8':
  8059. case '9':
  8060. {
  8061. add(current);
  8062. goto scan_number_decimal2;
  8063. }
  8064. default:
  8065. {
  8066. error_message = "invalid number; expected digit after '.'";
  8067. return token_type::parse_error;
  8068. }
  8069. }
  8070. scan_number_decimal2:
  8071. // we just parsed at least one number after a decimal point
  8072. switch (get())
  8073. {
  8074. case '0':
  8075. case '1':
  8076. case '2':
  8077. case '3':
  8078. case '4':
  8079. case '5':
  8080. case '6':
  8081. case '7':
  8082. case '8':
  8083. case '9':
  8084. {
  8085. add(current);
  8086. goto scan_number_decimal2;
  8087. }
  8088. case 'e':
  8089. case 'E':
  8090. {
  8091. add(current);
  8092. goto scan_number_exponent;
  8093. }
  8094. default:
  8095. goto scan_number_done;
  8096. }
  8097. scan_number_exponent:
  8098. // we just parsed an exponent
  8099. number_type = token_type::value_float;
  8100. switch (get())
  8101. {
  8102. case '+':
  8103. case '-':
  8104. {
  8105. add(current);
  8106. goto scan_number_sign;
  8107. }
  8108. case '0':
  8109. case '1':
  8110. case '2':
  8111. case '3':
  8112. case '4':
  8113. case '5':
  8114. case '6':
  8115. case '7':
  8116. case '8':
  8117. case '9':
  8118. {
  8119. add(current);
  8120. goto scan_number_any2;
  8121. }
  8122. default:
  8123. {
  8124. error_message =
  8125. "invalid number; expected '+', '-', or digit after exponent";
  8126. return token_type::parse_error;
  8127. }
  8128. }
  8129. scan_number_sign:
  8130. // we just parsed an exponent sign
  8131. switch (get())
  8132. {
  8133. case '0':
  8134. case '1':
  8135. case '2':
  8136. case '3':
  8137. case '4':
  8138. case '5':
  8139. case '6':
  8140. case '7':
  8141. case '8':
  8142. case '9':
  8143. {
  8144. add(current);
  8145. goto scan_number_any2;
  8146. }
  8147. default:
  8148. {
  8149. error_message = "invalid number; expected digit after exponent sign";
  8150. return token_type::parse_error;
  8151. }
  8152. }
  8153. scan_number_any2:
  8154. // we just parsed a number after the exponent or exponent sign
  8155. switch (get())
  8156. {
  8157. case '0':
  8158. case '1':
  8159. case '2':
  8160. case '3':
  8161. case '4':
  8162. case '5':
  8163. case '6':
  8164. case '7':
  8165. case '8':
  8166. case '9':
  8167. {
  8168. add(current);
  8169. goto scan_number_any2;
  8170. }
  8171. default:
  8172. goto scan_number_done;
  8173. }
  8174. scan_number_done:
  8175. // unget the character after the number (we only read it to know that
  8176. // we are done scanning a number)
  8177. unget();
  8178. char* endptr = nullptr;
  8179. errno = 0;
  8180. // try to parse integers first and fall back to floats
  8181. if (number_type == token_type::value_unsigned)
  8182. {
  8183. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  8184. // we checked the number format before
  8185. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  8186. if (errno == 0)
  8187. {
  8188. value_unsigned = static_cast<number_unsigned_t>(x);
  8189. if (value_unsigned == x)
  8190. {
  8191. return token_type::value_unsigned;
  8192. }
  8193. }
  8194. }
  8195. else if (number_type == token_type::value_integer)
  8196. {
  8197. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  8198. // we checked the number format before
  8199. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  8200. if (errno == 0)
  8201. {
  8202. value_integer = static_cast<number_integer_t>(x);
  8203. if (value_integer == x)
  8204. {
  8205. return token_type::value_integer;
  8206. }
  8207. }
  8208. }
  8209. // this code is reached if we parse a floating-point number or if an
  8210. // integer conversion above failed
  8211. strtof(value_float, token_buffer.data(), &endptr);
  8212. // we checked the number format before
  8213. JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size());
  8214. return token_type::value_float;
  8215. }
  8216. /*!
  8217. @param[in] literal_text the literal text to expect
  8218. @param[in] length the length of the passed literal text
  8219. @param[in] return_type the token type to return on success
  8220. */
  8221. JSON_HEDLEY_NON_NULL(2)
  8222. token_type scan_literal(const char_type* literal_text, const std::size_t length,
  8223. token_type return_type)
  8224. {
  8225. JSON_ASSERT(std::char_traits<char_type>::to_char_type(current) == literal_text[0]);
  8226. for (std::size_t i = 1; i < length; ++i)
  8227. {
  8228. if (JSON_HEDLEY_UNLIKELY(std::char_traits<char_type>::to_char_type(get()) != literal_text[i]))
  8229. {
  8230. error_message = "invalid literal";
  8231. return token_type::parse_error;
  8232. }
  8233. }
  8234. return return_type;
  8235. }
  8236. /////////////////////
  8237. // input management
  8238. /////////////////////
  8239. /// reset token_buffer; current character is beginning of token
  8240. void reset() noexcept
  8241. {
  8242. token_buffer.clear();
  8243. token_string.clear();
  8244. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  8245. }
  8246. /*
  8247. @brief get next character from the input
  8248. This function provides the interface to the used input adapter. It does
  8249. not throw in case the input reached EOF, but returns a
  8250. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  8251. for use in error messages.
  8252. @return character read from the input
  8253. */
  8254. char_int_type get()
  8255. {
  8256. ++position.chars_read_total;
  8257. ++position.chars_read_current_line;
  8258. if (next_unget)
  8259. {
  8260. // just reset the next_unget variable and work with current
  8261. next_unget = false;
  8262. }
  8263. else
  8264. {
  8265. current = ia.get_character();
  8266. }
  8267. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  8268. {
  8269. token_string.push_back(std::char_traits<char_type>::to_char_type(current));
  8270. }
  8271. if (current == '\n')
  8272. {
  8273. ++position.lines_read;
  8274. position.chars_read_current_line = 0;
  8275. }
  8276. return current;
  8277. }
  8278. /*!
  8279. @brief unget current character (read it again on next get)
  8280. We implement unget by setting variable next_unget to true. The input is not
  8281. changed - we just simulate ungetting by modifying chars_read_total,
  8282. chars_read_current_line, and token_string. The next call to get() will
  8283. behave as if the unget character is read again.
  8284. */
  8285. void unget()
  8286. {
  8287. next_unget = true;
  8288. --position.chars_read_total;
  8289. // in case we "unget" a newline, we have to also decrement the lines_read
  8290. if (position.chars_read_current_line == 0)
  8291. {
  8292. if (position.lines_read > 0)
  8293. {
  8294. --position.lines_read;
  8295. }
  8296. }
  8297. else
  8298. {
  8299. --position.chars_read_current_line;
  8300. }
  8301. if (JSON_HEDLEY_LIKELY(current != std::char_traits<char_type>::eof()))
  8302. {
  8303. JSON_ASSERT(!token_string.empty());
  8304. token_string.pop_back();
  8305. }
  8306. }
  8307. /// add a character to token_buffer
  8308. void add(char_int_type c)
  8309. {
  8310. token_buffer.push_back(static_cast<typename string_t::value_type>(c));
  8311. }
  8312. public:
  8313. /////////////////////
  8314. // value getters
  8315. /////////////////////
  8316. /// return integer value
  8317. constexpr number_integer_t get_number_integer() const noexcept
  8318. {
  8319. return value_integer;
  8320. }
  8321. /// return unsigned integer value
  8322. constexpr number_unsigned_t get_number_unsigned() const noexcept
  8323. {
  8324. return value_unsigned;
  8325. }
  8326. /// return floating-point value
  8327. constexpr number_float_t get_number_float() const noexcept
  8328. {
  8329. return value_float;
  8330. }
  8331. /// return current string value (implicitly resets the token; useful only once)
  8332. string_t& get_string()
  8333. {
  8334. return token_buffer;
  8335. }
  8336. /////////////////////
  8337. // diagnostics
  8338. /////////////////////
  8339. /// return position of last read token
  8340. constexpr position_t get_position() const noexcept
  8341. {
  8342. return position;
  8343. }
  8344. /// return the last read token (for errors only). Will never contain EOF
  8345. /// (an arbitrary value that is not a valid char value, often -1), because
  8346. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  8347. std::string get_token_string() const
  8348. {
  8349. // escape control characters
  8350. std::string result;
  8351. for (const auto c : token_string)
  8352. {
  8353. if (static_cast<unsigned char>(c) <= '\x1F')
  8354. {
  8355. // escape control characters
  8356. std::array<char, 9> cs{{}};
  8357. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  8358. result += cs.data();
  8359. }
  8360. else
  8361. {
  8362. // add character as is
  8363. result.push_back(static_cast<std::string::value_type>(c));
  8364. }
  8365. }
  8366. return result;
  8367. }
  8368. /// return syntax error message
  8369. JSON_HEDLEY_RETURNS_NON_NULL
  8370. constexpr const char* get_error_message() const noexcept
  8371. {
  8372. return error_message;
  8373. }
  8374. /////////////////////
  8375. // actual scanner
  8376. /////////////////////
  8377. /*!
  8378. @brief skip the UTF-8 byte order mark
  8379. @return true iff there is no BOM or the correct BOM has been skipped
  8380. */
  8381. bool skip_bom()
  8382. {
  8383. if (get() == 0xEF)
  8384. {
  8385. // check if we completely parse the BOM
  8386. return get() == 0xBB && get() == 0xBF;
  8387. }
  8388. // the first character is not the beginning of the BOM; unget it to
  8389. // process is later
  8390. unget();
  8391. return true;
  8392. }
  8393. void skip_whitespace()
  8394. {
  8395. do
  8396. {
  8397. get();
  8398. }
  8399. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  8400. }
  8401. token_type scan()
  8402. {
  8403. // initially, skip the BOM
  8404. if (position.chars_read_total == 0 && !skip_bom())
  8405. {
  8406. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  8407. return token_type::parse_error;
  8408. }
  8409. // read next character and ignore whitespace
  8410. skip_whitespace();
  8411. // ignore comments
  8412. if (ignore_comments && current == '/')
  8413. {
  8414. if (!scan_comment())
  8415. {
  8416. return token_type::parse_error;
  8417. }
  8418. // skip following whitespace
  8419. skip_whitespace();
  8420. }
  8421. while (current == ' ' || current == '\t' || current == '\n' || current == '\r');
  8422. switch (current)
  8423. {
  8424. // structural characters
  8425. case '[':
  8426. return token_type::begin_array;
  8427. case ']':
  8428. return token_type::end_array;
  8429. case '{':
  8430. return token_type::begin_object;
  8431. case '}':
  8432. return token_type::end_object;
  8433. case ':':
  8434. return token_type::name_separator;
  8435. case ',':
  8436. return token_type::value_separator;
  8437. // literals
  8438. case 't':
  8439. {
  8440. std::array<char_type, 4> true_literal = {{'t', 'r', 'u', 'e'}};
  8441. return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true);
  8442. }
  8443. case 'f':
  8444. {
  8445. std::array<char_type, 5> false_literal = {{'f', 'a', 'l', 's', 'e'}};
  8446. return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false);
  8447. }
  8448. case 'n':
  8449. {
  8450. std::array<char_type, 4> null_literal = {{'n', 'u', 'l', 'l'}};
  8451. return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null);
  8452. }
  8453. // string
  8454. case '\"':
  8455. return scan_string();
  8456. // number
  8457. case '-':
  8458. case '0':
  8459. case '1':
  8460. case '2':
  8461. case '3':
  8462. case '4':
  8463. case '5':
  8464. case '6':
  8465. case '7':
  8466. case '8':
  8467. case '9':
  8468. return scan_number();
  8469. // end of input (the null byte is needed when parsing from
  8470. // string literals)
  8471. case '\0':
  8472. case std::char_traits<char_type>::eof():
  8473. return token_type::end_of_input;
  8474. // error
  8475. default:
  8476. error_message = "invalid literal";
  8477. return token_type::parse_error;
  8478. }
  8479. }
  8480. private:
  8481. /// input adapter
  8482. InputAdapterType ia;
  8483. /// whether comments should be ignored (true) or signaled as errors (false)
  8484. const bool ignore_comments = false;
  8485. /// the current character
  8486. char_int_type current = std::char_traits<char_type>::eof();
  8487. /// whether the next get() call should just return current
  8488. bool next_unget = false;
  8489. /// the start position of the current token
  8490. position_t position {};
  8491. /// raw input token string (for error messages)
  8492. std::vector<char_type> token_string {};
  8493. /// buffer for variable-length tokens (numbers, strings)
  8494. string_t token_buffer {};
  8495. /// a description of occurred lexer errors
  8496. const char* error_message = "";
  8497. // number values
  8498. number_integer_t value_integer = 0;
  8499. number_unsigned_t value_unsigned = 0;
  8500. number_float_t value_float = 0;
  8501. /// the decimal point
  8502. const char_int_type decimal_point_char = '.';
  8503. };
  8504. } // namespace detail
  8505. } // namespace nlohmann
  8506. // #include <nlohmann/detail/input/parser.hpp>
  8507. #include <cmath> // isfinite
  8508. #include <cstdint> // uint8_t
  8509. #include <functional> // function
  8510. #include <string> // string
  8511. #include <utility> // move
  8512. #include <vector> // vector
  8513. // #include <nlohmann/detail/exceptions.hpp>
  8514. // #include <nlohmann/detail/input/input_adapters.hpp>
  8515. // #include <nlohmann/detail/input/json_sax.hpp>
  8516. // #include <nlohmann/detail/input/lexer.hpp>
  8517. // #include <nlohmann/detail/macro_scope.hpp>
  8518. // #include <nlohmann/detail/meta/is_sax.hpp>
  8519. // #include <nlohmann/detail/value_t.hpp>
  8520. namespace nlohmann
  8521. {
  8522. namespace detail
  8523. {
  8524. ////////////
  8525. // parser //
  8526. ////////////
  8527. enum class parse_event_t : uint8_t
  8528. {
  8529. /// the parser read `{` and started to process a JSON object
  8530. object_start,
  8531. /// the parser read `}` and finished processing a JSON object
  8532. object_end,
  8533. /// the parser read `[` and started to process a JSON array
  8534. array_start,
  8535. /// the parser read `]` and finished processing a JSON array
  8536. array_end,
  8537. /// the parser read a key of a value in an object
  8538. key,
  8539. /// the parser finished reading a JSON value
  8540. value
  8541. };
  8542. template<typename BasicJsonType>
  8543. using parser_callback_t =
  8544. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  8545. /*!
  8546. @brief syntax analysis
  8547. This class implements a recursive descent parser.
  8548. */
  8549. template<typename BasicJsonType, typename InputAdapterType>
  8550. class parser
  8551. {
  8552. using number_integer_t = typename BasicJsonType::number_integer_t;
  8553. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8554. using number_float_t = typename BasicJsonType::number_float_t;
  8555. using string_t = typename BasicJsonType::string_t;
  8556. using lexer_t = lexer<BasicJsonType, InputAdapterType>;
  8557. using token_type = typename lexer_t::token_type;
  8558. public:
  8559. /// a parser reading from an input adapter
  8560. explicit parser(InputAdapterType&& adapter,
  8561. const parser_callback_t<BasicJsonType> cb = nullptr,
  8562. const bool allow_exceptions_ = true,
  8563. const bool skip_comments = false)
  8564. : callback(cb)
  8565. , m_lexer(std::move(adapter), skip_comments)
  8566. , allow_exceptions(allow_exceptions_)
  8567. {
  8568. // read first token
  8569. get_token();
  8570. }
  8571. /*!
  8572. @brief public parser interface
  8573. @param[in] strict whether to expect the last token to be EOF
  8574. @param[in,out] result parsed JSON value
  8575. @throw parse_error.101 in case of an unexpected token
  8576. @throw parse_error.102 if to_unicode fails or surrogate error
  8577. @throw parse_error.103 if to_unicode fails
  8578. */
  8579. void parse(const bool strict, BasicJsonType& result)
  8580. {
  8581. if (callback)
  8582. {
  8583. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  8584. sax_parse_internal(&sdp);
  8585. result.assert_invariant();
  8586. // in strict mode, input must be completely read
  8587. if (strict && (get_token() != token_type::end_of_input))
  8588. {
  8589. sdp.parse_error(m_lexer.get_position(),
  8590. m_lexer.get_token_string(),
  8591. parse_error::create(101, m_lexer.get_position(),
  8592. exception_message(token_type::end_of_input, "value")));
  8593. }
  8594. // in case of an error, return discarded value
  8595. if (sdp.is_errored())
  8596. {
  8597. result = value_t::discarded;
  8598. return;
  8599. }
  8600. // set top-level value to null if it was discarded by the callback
  8601. // function
  8602. if (result.is_discarded())
  8603. {
  8604. result = nullptr;
  8605. }
  8606. }
  8607. else
  8608. {
  8609. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  8610. sax_parse_internal(&sdp);
  8611. result.assert_invariant();
  8612. // in strict mode, input must be completely read
  8613. if (strict && (get_token() != token_type::end_of_input))
  8614. {
  8615. sdp.parse_error(m_lexer.get_position(),
  8616. m_lexer.get_token_string(),
  8617. parse_error::create(101, m_lexer.get_position(),
  8618. exception_message(token_type::end_of_input, "value")));
  8619. }
  8620. // in case of an error, return discarded value
  8621. if (sdp.is_errored())
  8622. {
  8623. result = value_t::discarded;
  8624. return;
  8625. }
  8626. }
  8627. }
  8628. /*!
  8629. @brief public accept interface
  8630. @param[in] strict whether to expect the last token to be EOF
  8631. @return whether the input is a proper JSON text
  8632. */
  8633. bool accept(const bool strict = true)
  8634. {
  8635. json_sax_acceptor<BasicJsonType> sax_acceptor;
  8636. return sax_parse(&sax_acceptor, strict);
  8637. }
  8638. template<typename SAX>
  8639. JSON_HEDLEY_NON_NULL(2)
  8640. bool sax_parse(SAX* sax, const bool strict = true)
  8641. {
  8642. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  8643. const bool result = sax_parse_internal(sax);
  8644. // strict mode: next byte must be EOF
  8645. if (result && strict && (get_token() != token_type::end_of_input))
  8646. {
  8647. return sax->parse_error(m_lexer.get_position(),
  8648. m_lexer.get_token_string(),
  8649. parse_error::create(101, m_lexer.get_position(),
  8650. exception_message(token_type::end_of_input, "value")));
  8651. }
  8652. return result;
  8653. }
  8654. private:
  8655. template<typename SAX>
  8656. JSON_HEDLEY_NON_NULL(2)
  8657. bool sax_parse_internal(SAX* sax)
  8658. {
  8659. // stack to remember the hierarchy of structured values we are parsing
  8660. // true = array; false = object
  8661. std::vector<bool> states;
  8662. // value to avoid a goto (see comment where set to true)
  8663. bool skip_to_state_evaluation = false;
  8664. while (true)
  8665. {
  8666. if (!skip_to_state_evaluation)
  8667. {
  8668. // invariant: get_token() was called before each iteration
  8669. switch (last_token)
  8670. {
  8671. case token_type::begin_object:
  8672. {
  8673. if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1))))
  8674. {
  8675. return false;
  8676. }
  8677. // closing } -> we are done
  8678. if (get_token() == token_type::end_object)
  8679. {
  8680. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  8681. {
  8682. return false;
  8683. }
  8684. break;
  8685. }
  8686. // parse key
  8687. if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string))
  8688. {
  8689. return sax->parse_error(m_lexer.get_position(),
  8690. m_lexer.get_token_string(),
  8691. parse_error::create(101, m_lexer.get_position(),
  8692. exception_message(token_type::value_string, "object key")));
  8693. }
  8694. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  8695. {
  8696. return false;
  8697. }
  8698. // parse separator (:)
  8699. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8700. {
  8701. return sax->parse_error(m_lexer.get_position(),
  8702. m_lexer.get_token_string(),
  8703. parse_error::create(101, m_lexer.get_position(),
  8704. exception_message(token_type::name_separator, "object separator")));
  8705. }
  8706. // remember we are now inside an object
  8707. states.push_back(false);
  8708. // parse values
  8709. get_token();
  8710. continue;
  8711. }
  8712. case token_type::begin_array:
  8713. {
  8714. if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1))))
  8715. {
  8716. return false;
  8717. }
  8718. // closing ] -> we are done
  8719. if (get_token() == token_type::end_array)
  8720. {
  8721. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  8722. {
  8723. return false;
  8724. }
  8725. break;
  8726. }
  8727. // remember we are now inside an array
  8728. states.push_back(true);
  8729. // parse values (no need to call get_token)
  8730. continue;
  8731. }
  8732. case token_type::value_float:
  8733. {
  8734. const auto res = m_lexer.get_number_float();
  8735. if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res)))
  8736. {
  8737. return sax->parse_error(m_lexer.get_position(),
  8738. m_lexer.get_token_string(),
  8739. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  8740. }
  8741. if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string())))
  8742. {
  8743. return false;
  8744. }
  8745. break;
  8746. }
  8747. case token_type::literal_false:
  8748. {
  8749. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false)))
  8750. {
  8751. return false;
  8752. }
  8753. break;
  8754. }
  8755. case token_type::literal_null:
  8756. {
  8757. if (JSON_HEDLEY_UNLIKELY(!sax->null()))
  8758. {
  8759. return false;
  8760. }
  8761. break;
  8762. }
  8763. case token_type::literal_true:
  8764. {
  8765. if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true)))
  8766. {
  8767. return false;
  8768. }
  8769. break;
  8770. }
  8771. case token_type::value_integer:
  8772. {
  8773. if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer())))
  8774. {
  8775. return false;
  8776. }
  8777. break;
  8778. }
  8779. case token_type::value_string:
  8780. {
  8781. if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string())))
  8782. {
  8783. return false;
  8784. }
  8785. break;
  8786. }
  8787. case token_type::value_unsigned:
  8788. {
  8789. if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned())))
  8790. {
  8791. return false;
  8792. }
  8793. break;
  8794. }
  8795. case token_type::parse_error:
  8796. {
  8797. // using "uninitialized" to avoid "expected" message
  8798. return sax->parse_error(m_lexer.get_position(),
  8799. m_lexer.get_token_string(),
  8800. parse_error::create(101, m_lexer.get_position(),
  8801. exception_message(token_type::uninitialized, "value")));
  8802. }
  8803. default: // the last token was unexpected
  8804. {
  8805. return sax->parse_error(m_lexer.get_position(),
  8806. m_lexer.get_token_string(),
  8807. parse_error::create(101, m_lexer.get_position(),
  8808. exception_message(token_type::literal_or_value, "value")));
  8809. }
  8810. }
  8811. }
  8812. else
  8813. {
  8814. skip_to_state_evaluation = false;
  8815. }
  8816. // we reached this line after we successfully parsed a value
  8817. if (states.empty())
  8818. {
  8819. // empty stack: we reached the end of the hierarchy: done
  8820. return true;
  8821. }
  8822. if (states.back()) // array
  8823. {
  8824. // comma -> next value
  8825. if (get_token() == token_type::value_separator)
  8826. {
  8827. // parse a new value
  8828. get_token();
  8829. continue;
  8830. }
  8831. // closing ]
  8832. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array))
  8833. {
  8834. if (JSON_HEDLEY_UNLIKELY(!sax->end_array()))
  8835. {
  8836. return false;
  8837. }
  8838. // We are done with this array. Before we can parse a
  8839. // new value, we need to evaluate the new state first.
  8840. // By setting skip_to_state_evaluation to false, we
  8841. // are effectively jumping to the beginning of this if.
  8842. JSON_ASSERT(!states.empty());
  8843. states.pop_back();
  8844. skip_to_state_evaluation = true;
  8845. continue;
  8846. }
  8847. return sax->parse_error(m_lexer.get_position(),
  8848. m_lexer.get_token_string(),
  8849. parse_error::create(101, m_lexer.get_position(),
  8850. exception_message(token_type::end_array, "array")));
  8851. }
  8852. else // object
  8853. {
  8854. // comma -> next value
  8855. if (get_token() == token_type::value_separator)
  8856. {
  8857. // parse key
  8858. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string))
  8859. {
  8860. return sax->parse_error(m_lexer.get_position(),
  8861. m_lexer.get_token_string(),
  8862. parse_error::create(101, m_lexer.get_position(),
  8863. exception_message(token_type::value_string, "object key")));
  8864. }
  8865. if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string())))
  8866. {
  8867. return false;
  8868. }
  8869. // parse separator (:)
  8870. if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator))
  8871. {
  8872. return sax->parse_error(m_lexer.get_position(),
  8873. m_lexer.get_token_string(),
  8874. parse_error::create(101, m_lexer.get_position(),
  8875. exception_message(token_type::name_separator, "object separator")));
  8876. }
  8877. // parse values
  8878. get_token();
  8879. continue;
  8880. }
  8881. // closing }
  8882. if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object))
  8883. {
  8884. if (JSON_HEDLEY_UNLIKELY(!sax->end_object()))
  8885. {
  8886. return false;
  8887. }
  8888. // We are done with this object. Before we can parse a
  8889. // new value, we need to evaluate the new state first.
  8890. // By setting skip_to_state_evaluation to false, we
  8891. // are effectively jumping to the beginning of this if.
  8892. JSON_ASSERT(!states.empty());
  8893. states.pop_back();
  8894. skip_to_state_evaluation = true;
  8895. continue;
  8896. }
  8897. return sax->parse_error(m_lexer.get_position(),
  8898. m_lexer.get_token_string(),
  8899. parse_error::create(101, m_lexer.get_position(),
  8900. exception_message(token_type::end_object, "object")));
  8901. }
  8902. }
  8903. }
  8904. /// get next token from lexer
  8905. token_type get_token()
  8906. {
  8907. return last_token = m_lexer.scan();
  8908. }
  8909. std::string exception_message(const token_type expected, const std::string& context)
  8910. {
  8911. std::string error_msg = "syntax error ";
  8912. if (!context.empty())
  8913. {
  8914. error_msg += "while parsing " + context + " ";
  8915. }
  8916. error_msg += "- ";
  8917. if (last_token == token_type::parse_error)
  8918. {
  8919. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  8920. m_lexer.get_token_string() + "'";
  8921. }
  8922. else
  8923. {
  8924. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  8925. }
  8926. if (expected != token_type::uninitialized)
  8927. {
  8928. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  8929. }
  8930. return error_msg;
  8931. }
  8932. private:
  8933. /// callback function
  8934. const parser_callback_t<BasicJsonType> callback = nullptr;
  8935. /// the type of the last read token
  8936. token_type last_token = token_type::uninitialized;
  8937. /// the lexer
  8938. lexer_t m_lexer;
  8939. /// whether to throw exceptions in case of errors
  8940. const bool allow_exceptions = true;
  8941. };
  8942. } // namespace detail
  8943. } // namespace nlohmann
  8944. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  8945. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  8946. #include <cstddef> // ptrdiff_t
  8947. #include <limits> // numeric_limits
  8948. namespace nlohmann
  8949. {
  8950. namespace detail
  8951. {
  8952. /*
  8953. @brief an iterator for primitive JSON types
  8954. This class models an iterator for primitive JSON types (boolean, number,
  8955. string). It's only purpose is to allow the iterator/const_iterator classes
  8956. to "iterate" over primitive values. Internally, the iterator is modeled by
  8957. a `difference_type` variable. Value begin_value (`0`) models the begin,
  8958. end_value (`1`) models past the end.
  8959. */
  8960. class primitive_iterator_t
  8961. {
  8962. private:
  8963. using difference_type = std::ptrdiff_t;
  8964. static constexpr difference_type begin_value = 0;
  8965. static constexpr difference_type end_value = begin_value + 1;
  8966. /// iterator as signed integer type
  8967. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  8968. public:
  8969. constexpr difference_type get_value() const noexcept
  8970. {
  8971. return m_it;
  8972. }
  8973. /// set iterator to a defined beginning
  8974. void set_begin() noexcept
  8975. {
  8976. m_it = begin_value;
  8977. }
  8978. /// set iterator to a defined past the end
  8979. void set_end() noexcept
  8980. {
  8981. m_it = end_value;
  8982. }
  8983. /// return whether the iterator can be dereferenced
  8984. constexpr bool is_begin() const noexcept
  8985. {
  8986. return m_it == begin_value;
  8987. }
  8988. /// return whether the iterator is at end
  8989. constexpr bool is_end() const noexcept
  8990. {
  8991. return m_it == end_value;
  8992. }
  8993. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8994. {
  8995. return lhs.m_it == rhs.m_it;
  8996. }
  8997. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  8998. {
  8999. return lhs.m_it < rhs.m_it;
  9000. }
  9001. primitive_iterator_t operator+(difference_type n) noexcept
  9002. {
  9003. auto result = *this;
  9004. result += n;
  9005. return result;
  9006. }
  9007. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  9008. {
  9009. return lhs.m_it - rhs.m_it;
  9010. }
  9011. primitive_iterator_t& operator++() noexcept
  9012. {
  9013. ++m_it;
  9014. return *this;
  9015. }
  9016. primitive_iterator_t const operator++(int) noexcept
  9017. {
  9018. auto result = *this;
  9019. ++m_it;
  9020. return result;
  9021. }
  9022. primitive_iterator_t& operator--() noexcept
  9023. {
  9024. --m_it;
  9025. return *this;
  9026. }
  9027. primitive_iterator_t const operator--(int) noexcept
  9028. {
  9029. auto result = *this;
  9030. --m_it;
  9031. return result;
  9032. }
  9033. primitive_iterator_t& operator+=(difference_type n) noexcept
  9034. {
  9035. m_it += n;
  9036. return *this;
  9037. }
  9038. primitive_iterator_t& operator-=(difference_type n) noexcept
  9039. {
  9040. m_it -= n;
  9041. return *this;
  9042. }
  9043. };
  9044. } // namespace detail
  9045. } // namespace nlohmann
  9046. namespace nlohmann
  9047. {
  9048. namespace detail
  9049. {
  9050. /*!
  9051. @brief an iterator value
  9052. @note This structure could easily be a union, but MSVC currently does not allow
  9053. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  9054. */
  9055. template<typename BasicJsonType> struct internal_iterator
  9056. {
  9057. /// iterator for JSON objects
  9058. typename BasicJsonType::object_t::iterator object_iterator {};
  9059. /// iterator for JSON arrays
  9060. typename BasicJsonType::array_t::iterator array_iterator {};
  9061. /// generic iterator for all other types
  9062. primitive_iterator_t primitive_iterator {};
  9063. };
  9064. } // namespace detail
  9065. } // namespace nlohmann
  9066. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  9067. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  9068. #include <type_traits> // conditional, is_const, remove_const
  9069. // #include <nlohmann/detail/exceptions.hpp>
  9070. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  9071. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9072. // #include <nlohmann/detail/macro_scope.hpp>
  9073. // #include <nlohmann/detail/meta/cpp_future.hpp>
  9074. // #include <nlohmann/detail/meta/type_traits.hpp>
  9075. // #include <nlohmann/detail/value_t.hpp>
  9076. namespace nlohmann
  9077. {
  9078. namespace detail
  9079. {
  9080. // forward declare, to be able to friend it later on
  9081. template<typename IteratorType> class iteration_proxy;
  9082. template<typename IteratorType> class iteration_proxy_value;
  9083. /*!
  9084. @brief a template for a bidirectional iterator for the @ref basic_json class
  9085. This class implements a both iterators (iterator and const_iterator) for the
  9086. @ref basic_json class.
  9087. @note An iterator is called *initialized* when a pointer to a JSON value has
  9088. been set (e.g., by a constructor or a copy assignment). If the iterator is
  9089. default-constructed, it is *uninitialized* and most methods are undefined.
  9090. **The library uses assertions to detect calls on uninitialized iterators.**
  9091. @requirement The class satisfies the following concept requirements:
  9092. -
  9093. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9094. The iterator that can be moved can be moved in both directions (i.e.
  9095. incremented and decremented).
  9096. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  9097. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  9098. */
  9099. template<typename BasicJsonType>
  9100. class iter_impl
  9101. {
  9102. /// allow basic_json to access private members
  9103. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  9104. friend BasicJsonType;
  9105. friend iteration_proxy<iter_impl>;
  9106. friend iteration_proxy_value<iter_impl>;
  9107. using object_t = typename BasicJsonType::object_t;
  9108. using array_t = typename BasicJsonType::array_t;
  9109. // make sure BasicJsonType is basic_json or const basic_json
  9110. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  9111. "iter_impl only accepts (const) basic_json");
  9112. public:
  9113. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  9114. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  9115. /// A user-defined iterator should provide publicly accessible typedefs named
  9116. /// iterator_category, value_type, difference_type, pointer, and reference.
  9117. /// Note that value_type is required to be non-const, even for constant iterators.
  9118. using iterator_category = std::bidirectional_iterator_tag;
  9119. /// the type of the values when the iterator is dereferenced
  9120. using value_type = typename BasicJsonType::value_type;
  9121. /// a type to represent differences between iterators
  9122. using difference_type = typename BasicJsonType::difference_type;
  9123. /// defines a pointer to the type iterated over (value_type)
  9124. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  9125. typename BasicJsonType::const_pointer,
  9126. typename BasicJsonType::pointer>::type;
  9127. /// defines a reference to the type iterated over (value_type)
  9128. using reference =
  9129. typename std::conditional<std::is_const<BasicJsonType>::value,
  9130. typename BasicJsonType::const_reference,
  9131. typename BasicJsonType::reference>::type;
  9132. /// default constructor
  9133. iter_impl() = default;
  9134. /*!
  9135. @brief constructor for a given JSON instance
  9136. @param[in] object pointer to a JSON object for this iterator
  9137. @pre object != nullptr
  9138. @post The iterator is initialized; i.e. `m_object != nullptr`.
  9139. */
  9140. explicit iter_impl(pointer object) noexcept : m_object(object)
  9141. {
  9142. JSON_ASSERT(m_object != nullptr);
  9143. switch (m_object->m_type)
  9144. {
  9145. case value_t::object:
  9146. {
  9147. m_it.object_iterator = typename object_t::iterator();
  9148. break;
  9149. }
  9150. case value_t::array:
  9151. {
  9152. m_it.array_iterator = typename array_t::iterator();
  9153. break;
  9154. }
  9155. default:
  9156. {
  9157. m_it.primitive_iterator = primitive_iterator_t();
  9158. break;
  9159. }
  9160. }
  9161. }
  9162. /*!
  9163. @note The conventional copy constructor and copy assignment are implicitly
  9164. defined. Combined with the following converting constructor and
  9165. assignment, they support: (1) copy from iterator to iterator, (2)
  9166. copy from const iterator to const iterator, and (3) conversion from
  9167. iterator to const iterator. However conversion from const iterator
  9168. to iterator is not defined.
  9169. */
  9170. /*!
  9171. @brief const copy constructor
  9172. @param[in] other const iterator to copy from
  9173. @note This copy constructor had to be defined explicitly to circumvent a bug
  9174. occurring on msvc v19.0 compiler (VS 2015) debug build. For more
  9175. information refer to: https://github.com/nlohmann/json/issues/1608
  9176. */
  9177. iter_impl(const iter_impl<const BasicJsonType>& other) noexcept
  9178. : m_object(other.m_object), m_it(other.m_it)
  9179. {}
  9180. /*!
  9181. @brief converting assignment
  9182. @param[in] other const iterator to copy from
  9183. @return const/non-const iterator
  9184. @note It is not checked whether @a other is initialized.
  9185. */
  9186. iter_impl& operator=(const iter_impl<const BasicJsonType>& other) noexcept
  9187. {
  9188. m_object = other.m_object;
  9189. m_it = other.m_it;
  9190. return *this;
  9191. }
  9192. /*!
  9193. @brief converting constructor
  9194. @param[in] other non-const iterator to copy from
  9195. @note It is not checked whether @a other is initialized.
  9196. */
  9197. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9198. : m_object(other.m_object), m_it(other.m_it)
  9199. {}
  9200. /*!
  9201. @brief converting assignment
  9202. @param[in] other non-const iterator to copy from
  9203. @return const/non-const iterator
  9204. @note It is not checked whether @a other is initialized.
  9205. */
  9206. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  9207. {
  9208. m_object = other.m_object;
  9209. m_it = other.m_it;
  9210. return *this;
  9211. }
  9212. private:
  9213. /*!
  9214. @brief set the iterator to the first value
  9215. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9216. */
  9217. void set_begin() noexcept
  9218. {
  9219. JSON_ASSERT(m_object != nullptr);
  9220. switch (m_object->m_type)
  9221. {
  9222. case value_t::object:
  9223. {
  9224. m_it.object_iterator = m_object->m_value.object->begin();
  9225. break;
  9226. }
  9227. case value_t::array:
  9228. {
  9229. m_it.array_iterator = m_object->m_value.array->begin();
  9230. break;
  9231. }
  9232. case value_t::null:
  9233. {
  9234. // set to end so begin()==end() is true: null is empty
  9235. m_it.primitive_iterator.set_end();
  9236. break;
  9237. }
  9238. default:
  9239. {
  9240. m_it.primitive_iterator.set_begin();
  9241. break;
  9242. }
  9243. }
  9244. }
  9245. /*!
  9246. @brief set the iterator past the last value
  9247. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9248. */
  9249. void set_end() noexcept
  9250. {
  9251. JSON_ASSERT(m_object != nullptr);
  9252. switch (m_object->m_type)
  9253. {
  9254. case value_t::object:
  9255. {
  9256. m_it.object_iterator = m_object->m_value.object->end();
  9257. break;
  9258. }
  9259. case value_t::array:
  9260. {
  9261. m_it.array_iterator = m_object->m_value.array->end();
  9262. break;
  9263. }
  9264. default:
  9265. {
  9266. m_it.primitive_iterator.set_end();
  9267. break;
  9268. }
  9269. }
  9270. }
  9271. public:
  9272. /*!
  9273. @brief return a reference to the value pointed to by the iterator
  9274. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9275. */
  9276. reference operator*() const
  9277. {
  9278. JSON_ASSERT(m_object != nullptr);
  9279. switch (m_object->m_type)
  9280. {
  9281. case value_t::object:
  9282. {
  9283. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  9284. return m_it.object_iterator->second;
  9285. }
  9286. case value_t::array:
  9287. {
  9288. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  9289. return *m_it.array_iterator;
  9290. }
  9291. case value_t::null:
  9292. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9293. default:
  9294. {
  9295. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9296. {
  9297. return *m_object;
  9298. }
  9299. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9300. }
  9301. }
  9302. }
  9303. /*!
  9304. @brief dereference the iterator
  9305. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9306. */
  9307. pointer operator->() const
  9308. {
  9309. JSON_ASSERT(m_object != nullptr);
  9310. switch (m_object->m_type)
  9311. {
  9312. case value_t::object:
  9313. {
  9314. JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end());
  9315. return &(m_it.object_iterator->second);
  9316. }
  9317. case value_t::array:
  9318. {
  9319. JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end());
  9320. return &*m_it.array_iterator;
  9321. }
  9322. default:
  9323. {
  9324. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin()))
  9325. {
  9326. return m_object;
  9327. }
  9328. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9329. }
  9330. }
  9331. }
  9332. /*!
  9333. @brief post-increment (it++)
  9334. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9335. */
  9336. iter_impl const operator++(int)
  9337. {
  9338. auto result = *this;
  9339. ++(*this);
  9340. return result;
  9341. }
  9342. /*!
  9343. @brief pre-increment (++it)
  9344. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9345. */
  9346. iter_impl& operator++()
  9347. {
  9348. JSON_ASSERT(m_object != nullptr);
  9349. switch (m_object->m_type)
  9350. {
  9351. case value_t::object:
  9352. {
  9353. std::advance(m_it.object_iterator, 1);
  9354. break;
  9355. }
  9356. case value_t::array:
  9357. {
  9358. std::advance(m_it.array_iterator, 1);
  9359. break;
  9360. }
  9361. default:
  9362. {
  9363. ++m_it.primitive_iterator;
  9364. break;
  9365. }
  9366. }
  9367. return *this;
  9368. }
  9369. /*!
  9370. @brief post-decrement (it--)
  9371. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9372. */
  9373. iter_impl const operator--(int)
  9374. {
  9375. auto result = *this;
  9376. --(*this);
  9377. return result;
  9378. }
  9379. /*!
  9380. @brief pre-decrement (--it)
  9381. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9382. */
  9383. iter_impl& operator--()
  9384. {
  9385. JSON_ASSERT(m_object != nullptr);
  9386. switch (m_object->m_type)
  9387. {
  9388. case value_t::object:
  9389. {
  9390. std::advance(m_it.object_iterator, -1);
  9391. break;
  9392. }
  9393. case value_t::array:
  9394. {
  9395. std::advance(m_it.array_iterator, -1);
  9396. break;
  9397. }
  9398. default:
  9399. {
  9400. --m_it.primitive_iterator;
  9401. break;
  9402. }
  9403. }
  9404. return *this;
  9405. }
  9406. /*!
  9407. @brief comparison: equal
  9408. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9409. */
  9410. bool operator==(const iter_impl& other) const
  9411. {
  9412. // if objects are not the same, the comparison is undefined
  9413. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9414. {
  9415. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9416. }
  9417. JSON_ASSERT(m_object != nullptr);
  9418. switch (m_object->m_type)
  9419. {
  9420. case value_t::object:
  9421. return (m_it.object_iterator == other.m_it.object_iterator);
  9422. case value_t::array:
  9423. return (m_it.array_iterator == other.m_it.array_iterator);
  9424. default:
  9425. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  9426. }
  9427. }
  9428. /*!
  9429. @brief comparison: not equal
  9430. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9431. */
  9432. bool operator!=(const iter_impl& other) const
  9433. {
  9434. return !operator==(other);
  9435. }
  9436. /*!
  9437. @brief comparison: smaller
  9438. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9439. */
  9440. bool operator<(const iter_impl& other) const
  9441. {
  9442. // if objects are not the same, the comparison is undefined
  9443. if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object))
  9444. {
  9445. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  9446. }
  9447. JSON_ASSERT(m_object != nullptr);
  9448. switch (m_object->m_type)
  9449. {
  9450. case value_t::object:
  9451. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  9452. case value_t::array:
  9453. return (m_it.array_iterator < other.m_it.array_iterator);
  9454. default:
  9455. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  9456. }
  9457. }
  9458. /*!
  9459. @brief comparison: less than or equal
  9460. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9461. */
  9462. bool operator<=(const iter_impl& other) const
  9463. {
  9464. return !other.operator < (*this);
  9465. }
  9466. /*!
  9467. @brief comparison: greater than
  9468. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9469. */
  9470. bool operator>(const iter_impl& other) const
  9471. {
  9472. return !operator<=(other);
  9473. }
  9474. /*!
  9475. @brief comparison: greater than or equal
  9476. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9477. */
  9478. bool operator>=(const iter_impl& other) const
  9479. {
  9480. return !operator<(other);
  9481. }
  9482. /*!
  9483. @brief add to iterator
  9484. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9485. */
  9486. iter_impl& operator+=(difference_type i)
  9487. {
  9488. JSON_ASSERT(m_object != nullptr);
  9489. switch (m_object->m_type)
  9490. {
  9491. case value_t::object:
  9492. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9493. case value_t::array:
  9494. {
  9495. std::advance(m_it.array_iterator, i);
  9496. break;
  9497. }
  9498. default:
  9499. {
  9500. m_it.primitive_iterator += i;
  9501. break;
  9502. }
  9503. }
  9504. return *this;
  9505. }
  9506. /*!
  9507. @brief subtract from iterator
  9508. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9509. */
  9510. iter_impl& operator-=(difference_type i)
  9511. {
  9512. return operator+=(-i);
  9513. }
  9514. /*!
  9515. @brief add to iterator
  9516. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9517. */
  9518. iter_impl operator+(difference_type i) const
  9519. {
  9520. auto result = *this;
  9521. result += i;
  9522. return result;
  9523. }
  9524. /*!
  9525. @brief addition of distance and iterator
  9526. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9527. */
  9528. friend iter_impl operator+(difference_type i, const iter_impl& it)
  9529. {
  9530. auto result = it;
  9531. result += i;
  9532. return result;
  9533. }
  9534. /*!
  9535. @brief subtract from iterator
  9536. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9537. */
  9538. iter_impl operator-(difference_type i) const
  9539. {
  9540. auto result = *this;
  9541. result -= i;
  9542. return result;
  9543. }
  9544. /*!
  9545. @brief return difference
  9546. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9547. */
  9548. difference_type operator-(const iter_impl& other) const
  9549. {
  9550. JSON_ASSERT(m_object != nullptr);
  9551. switch (m_object->m_type)
  9552. {
  9553. case value_t::object:
  9554. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  9555. case value_t::array:
  9556. return m_it.array_iterator - other.m_it.array_iterator;
  9557. default:
  9558. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  9559. }
  9560. }
  9561. /*!
  9562. @brief access to successor
  9563. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9564. */
  9565. reference operator[](difference_type n) const
  9566. {
  9567. JSON_ASSERT(m_object != nullptr);
  9568. switch (m_object->m_type)
  9569. {
  9570. case value_t::object:
  9571. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  9572. case value_t::array:
  9573. return *std::next(m_it.array_iterator, n);
  9574. case value_t::null:
  9575. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9576. default:
  9577. {
  9578. if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n))
  9579. {
  9580. return *m_object;
  9581. }
  9582. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  9583. }
  9584. }
  9585. }
  9586. /*!
  9587. @brief return the key of an object iterator
  9588. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9589. */
  9590. const typename object_t::key_type& key() const
  9591. {
  9592. JSON_ASSERT(m_object != nullptr);
  9593. if (JSON_HEDLEY_LIKELY(m_object->is_object()))
  9594. {
  9595. return m_it.object_iterator->first;
  9596. }
  9597. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  9598. }
  9599. /*!
  9600. @brief return the value of an iterator
  9601. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  9602. */
  9603. reference value() const
  9604. {
  9605. return operator*();
  9606. }
  9607. private:
  9608. /// associated JSON instance
  9609. pointer m_object = nullptr;
  9610. /// the actual iterator of the associated instance
  9611. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  9612. };
  9613. } // namespace detail
  9614. } // namespace nlohmann
  9615. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  9616. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  9617. #include <cstddef> // ptrdiff_t
  9618. #include <iterator> // reverse_iterator
  9619. #include <utility> // declval
  9620. namespace nlohmann
  9621. {
  9622. namespace detail
  9623. {
  9624. //////////////////////
  9625. // reverse_iterator //
  9626. //////////////////////
  9627. /*!
  9628. @brief a template for a reverse iterator class
  9629. @tparam Base the base iterator type to reverse. Valid types are @ref
  9630. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  9631. create @ref const_reverse_iterator).
  9632. @requirement The class satisfies the following concept requirements:
  9633. -
  9634. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  9635. The iterator that can be moved can be moved in both directions (i.e.
  9636. incremented and decremented).
  9637. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  9638. It is possible to write to the pointed-to element (only if @a Base is
  9639. @ref iterator).
  9640. @since version 1.0.0
  9641. */
  9642. template<typename Base>
  9643. class json_reverse_iterator : public std::reverse_iterator<Base>
  9644. {
  9645. public:
  9646. using difference_type = std::ptrdiff_t;
  9647. /// shortcut to the reverse iterator adapter
  9648. using base_iterator = std::reverse_iterator<Base>;
  9649. /// the reference type for the pointed-to element
  9650. using reference = typename Base::reference;
  9651. /// create reverse iterator from iterator
  9652. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  9653. : base_iterator(it) {}
  9654. /// create reverse iterator from base class
  9655. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  9656. /// post-increment (it++)
  9657. json_reverse_iterator const operator++(int)
  9658. {
  9659. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  9660. }
  9661. /// pre-increment (++it)
  9662. json_reverse_iterator& operator++()
  9663. {
  9664. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  9665. }
  9666. /// post-decrement (it--)
  9667. json_reverse_iterator const operator--(int)
  9668. {
  9669. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  9670. }
  9671. /// pre-decrement (--it)
  9672. json_reverse_iterator& operator--()
  9673. {
  9674. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  9675. }
  9676. /// add to iterator
  9677. json_reverse_iterator& operator+=(difference_type i)
  9678. {
  9679. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  9680. }
  9681. /// add to iterator
  9682. json_reverse_iterator operator+(difference_type i) const
  9683. {
  9684. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  9685. }
  9686. /// subtract from iterator
  9687. json_reverse_iterator operator-(difference_type i) const
  9688. {
  9689. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  9690. }
  9691. /// return difference
  9692. difference_type operator-(const json_reverse_iterator& other) const
  9693. {
  9694. return base_iterator(*this) - base_iterator(other);
  9695. }
  9696. /// access to successor
  9697. reference operator[](difference_type n) const
  9698. {
  9699. return *(this->operator+(n));
  9700. }
  9701. /// return the key of an object iterator
  9702. auto key() const -> decltype(std::declval<Base>().key())
  9703. {
  9704. auto it = --this->base();
  9705. return it.key();
  9706. }
  9707. /// return the value of an iterator
  9708. reference value() const
  9709. {
  9710. auto it = --this->base();
  9711. return it.operator * ();
  9712. }
  9713. };
  9714. } // namespace detail
  9715. } // namespace nlohmann
  9716. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  9717. // #include <nlohmann/detail/json_pointer.hpp>
  9718. #include <algorithm> // all_of
  9719. #include <cctype> // isdigit
  9720. #include <limits> // max
  9721. #include <numeric> // accumulate
  9722. #include <string> // string
  9723. #include <utility> // move
  9724. #include <vector> // vector
  9725. // #include <nlohmann/detail/exceptions.hpp>
  9726. // #include <nlohmann/detail/macro_scope.hpp>
  9727. // #include <nlohmann/detail/value_t.hpp>
  9728. namespace nlohmann
  9729. {
  9730. template<typename BasicJsonType>
  9731. class json_pointer
  9732. {
  9733. // allow basic_json to access private members
  9734. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9735. friend class basic_json;
  9736. public:
  9737. /*!
  9738. @brief create JSON pointer
  9739. Create a JSON pointer according to the syntax described in
  9740. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9741. @param[in] s string representing the JSON pointer; if omitted, the empty
  9742. string is assumed which references the whole JSON value
  9743. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  9744. not begin with a slash (`/`); see example below
  9745. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  9746. not followed by `0` (representing `~`) or `1` (representing `/`); see
  9747. example below
  9748. @liveexample{The example shows the construction several valid JSON pointers
  9749. as well as the exceptional behavior.,json_pointer}
  9750. @since version 2.0.0
  9751. */
  9752. explicit json_pointer(const std::string& s = "")
  9753. : reference_tokens(split(s))
  9754. {}
  9755. /*!
  9756. @brief return a string representation of the JSON pointer
  9757. @invariant For each JSON pointer `ptr`, it holds:
  9758. @code {.cpp}
  9759. ptr == json_pointer(ptr.to_string());
  9760. @endcode
  9761. @return a string representation of the JSON pointer
  9762. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  9763. @since version 2.0.0
  9764. */
  9765. std::string to_string() const
  9766. {
  9767. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  9768. std::string{},
  9769. [](const std::string & a, const std::string & b)
  9770. {
  9771. return a + "/" + escape(b);
  9772. });
  9773. }
  9774. /// @copydoc to_string()
  9775. operator std::string() const
  9776. {
  9777. return to_string();
  9778. }
  9779. /*!
  9780. @brief append another JSON pointer at the end of this JSON pointer
  9781. @param[in] ptr JSON pointer to append
  9782. @return JSON pointer with @a ptr appended
  9783. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9784. @complexity Linear in the length of @a ptr.
  9785. @sa @ref operator/=(std::string) to append a reference token
  9786. @sa @ref operator/=(std::size_t) to append an array index
  9787. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  9788. @since version 3.6.0
  9789. */
  9790. json_pointer& operator/=(const json_pointer& ptr)
  9791. {
  9792. reference_tokens.insert(reference_tokens.end(),
  9793. ptr.reference_tokens.begin(),
  9794. ptr.reference_tokens.end());
  9795. return *this;
  9796. }
  9797. /*!
  9798. @brief append an unescaped reference token at the end of this JSON pointer
  9799. @param[in] token reference token to append
  9800. @return JSON pointer with @a token appended without escaping @a token
  9801. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9802. @complexity Amortized constant.
  9803. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9804. @sa @ref operator/=(std::size_t) to append an array index
  9805. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  9806. @since version 3.6.0
  9807. */
  9808. json_pointer& operator/=(std::string token)
  9809. {
  9810. push_back(std::move(token));
  9811. return *this;
  9812. }
  9813. /*!
  9814. @brief append an array index at the end of this JSON pointer
  9815. @param[in] array_idx array index to append
  9816. @return JSON pointer with @a array_idx appended
  9817. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  9818. @complexity Amortized constant.
  9819. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9820. @sa @ref operator/=(std::string) to append a reference token
  9821. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  9822. @since version 3.6.0
  9823. */
  9824. json_pointer& operator/=(std::size_t array_idx)
  9825. {
  9826. return *this /= std::to_string(array_idx);
  9827. }
  9828. /*!
  9829. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  9830. @param[in] lhs JSON pointer
  9831. @param[in] rhs JSON pointer
  9832. @return a new JSON pointer with @a rhs appended to @a lhs
  9833. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9834. @complexity Linear in the length of @a lhs and @a rhs.
  9835. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  9836. @since version 3.6.0
  9837. */
  9838. friend json_pointer operator/(const json_pointer& lhs,
  9839. const json_pointer& rhs)
  9840. {
  9841. return json_pointer(lhs) /= rhs;
  9842. }
  9843. /*!
  9844. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  9845. @param[in] ptr JSON pointer
  9846. @param[in] token reference token
  9847. @return a new JSON pointer with unescaped @a token appended to @a ptr
  9848. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9849. @complexity Linear in the length of @a ptr.
  9850. @sa @ref operator/=(std::string) to append a reference token
  9851. @since version 3.6.0
  9852. */
  9853. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  9854. {
  9855. return json_pointer(ptr) /= std::move(token);
  9856. }
  9857. /*!
  9858. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  9859. @param[in] ptr JSON pointer
  9860. @param[in] array_idx array index
  9861. @return a new JSON pointer with @a array_idx appended to @a ptr
  9862. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  9863. @complexity Linear in the length of @a ptr.
  9864. @sa @ref operator/=(std::size_t) to append an array index
  9865. @since version 3.6.0
  9866. */
  9867. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx)
  9868. {
  9869. return json_pointer(ptr) /= array_idx;
  9870. }
  9871. /*!
  9872. @brief returns the parent of this JSON pointer
  9873. @return parent of this JSON pointer; in case this JSON pointer is the root,
  9874. the root itself is returned
  9875. @complexity Linear in the length of the JSON pointer.
  9876. @liveexample{The example shows the result of `parent_pointer` for different
  9877. JSON Pointers.,json_pointer__parent_pointer}
  9878. @since version 3.6.0
  9879. */
  9880. json_pointer parent_pointer() const
  9881. {
  9882. if (empty())
  9883. {
  9884. return *this;
  9885. }
  9886. json_pointer res = *this;
  9887. res.pop_back();
  9888. return res;
  9889. }
  9890. /*!
  9891. @brief remove last reference token
  9892. @pre not `empty()`
  9893. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  9894. @complexity Constant.
  9895. @throw out_of_range.405 if JSON pointer has no parent
  9896. @since version 3.6.0
  9897. */
  9898. void pop_back()
  9899. {
  9900. if (JSON_HEDLEY_UNLIKELY(empty()))
  9901. {
  9902. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9903. }
  9904. reference_tokens.pop_back();
  9905. }
  9906. /*!
  9907. @brief return last reference token
  9908. @pre not `empty()`
  9909. @return last reference token
  9910. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  9911. @complexity Constant.
  9912. @throw out_of_range.405 if JSON pointer has no parent
  9913. @since version 3.6.0
  9914. */
  9915. const std::string& back() const
  9916. {
  9917. if (JSON_HEDLEY_UNLIKELY(empty()))
  9918. {
  9919. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9920. }
  9921. return reference_tokens.back();
  9922. }
  9923. /*!
  9924. @brief append an unescaped token at the end of the reference pointer
  9925. @param[in] token token to add
  9926. @complexity Amortized constant.
  9927. @liveexample{The example shows the result of `push_back` for different
  9928. JSON Pointers.,json_pointer__push_back}
  9929. @since version 3.6.0
  9930. */
  9931. void push_back(const std::string& token)
  9932. {
  9933. reference_tokens.push_back(token);
  9934. }
  9935. /// @copydoc push_back(const std::string&)
  9936. void push_back(std::string&& token)
  9937. {
  9938. reference_tokens.push_back(std::move(token));
  9939. }
  9940. /*!
  9941. @brief return whether pointer points to the root document
  9942. @return true iff the JSON pointer points to the root document
  9943. @complexity Constant.
  9944. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9945. @liveexample{The example shows the result of `empty` for different JSON
  9946. Pointers.,json_pointer__empty}
  9947. @since version 3.6.0
  9948. */
  9949. bool empty() const noexcept
  9950. {
  9951. return reference_tokens.empty();
  9952. }
  9953. private:
  9954. /*!
  9955. @param[in] s reference token to be converted into an array index
  9956. @return integer representation of @a s
  9957. @throw parse_error.106 if an array index begins with '0'
  9958. @throw parse_error.109 if an array index begins not with a digit
  9959. @throw out_of_range.404 if string @a s could not be converted to an integer
  9960. @throw out_of_range.410 if an array index exceeds size_type
  9961. */
  9962. static typename BasicJsonType::size_type array_index(const std::string& s)
  9963. {
  9964. using size_type = typename BasicJsonType::size_type;
  9965. // error condition (cf. RFC 6901, Sect. 4)
  9966. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0'))
  9967. {
  9968. JSON_THROW(detail::parse_error::create(106, 0,
  9969. "array index '" + s +
  9970. "' must not begin with '0'"));
  9971. }
  9972. // error condition (cf. RFC 6901, Sect. 4)
  9973. if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
  9974. {
  9975. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number"));
  9976. }
  9977. std::size_t processed_chars = 0;
  9978. unsigned long long res = 0;
  9979. JSON_TRY
  9980. {
  9981. res = std::stoull(s, &processed_chars);
  9982. }
  9983. JSON_CATCH(std::out_of_range&)
  9984. {
  9985. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9986. }
  9987. // check if the string was completely read
  9988. if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size()))
  9989. {
  9990. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9991. }
  9992. // only triggered on special platforms (like 32bit), see also
  9993. // https://github.com/nlohmann/json/pull/2203
  9994. if (res >= static_cast<unsigned long long>((std::numeric_limits<size_type>::max)()))
  9995. {
  9996. JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type")); // LCOV_EXCL_LINE
  9997. }
  9998. return static_cast<size_type>(res);
  9999. }
  10000. json_pointer top() const
  10001. {
  10002. if (JSON_HEDLEY_UNLIKELY(empty()))
  10003. {
  10004. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  10005. }
  10006. json_pointer result = *this;
  10007. result.reference_tokens = {reference_tokens[0]};
  10008. return result;
  10009. }
  10010. /*!
  10011. @brief create and return a reference to the pointed to value
  10012. @complexity Linear in the number of reference tokens.
  10013. @throw parse_error.109 if array index is not a number
  10014. @throw type_error.313 if value cannot be unflattened
  10015. */
  10016. BasicJsonType& get_and_create(BasicJsonType& j) const
  10017. {
  10018. auto result = &j;
  10019. // in case no reference tokens exist, return a reference to the JSON value
  10020. // j which will be overwritten by a primitive value
  10021. for (const auto& reference_token : reference_tokens)
  10022. {
  10023. switch (result->type())
  10024. {
  10025. case detail::value_t::null:
  10026. {
  10027. if (reference_token == "0")
  10028. {
  10029. // start a new array if reference token is 0
  10030. result = &result->operator[](0);
  10031. }
  10032. else
  10033. {
  10034. // start a new object otherwise
  10035. result = &result->operator[](reference_token);
  10036. }
  10037. break;
  10038. }
  10039. case detail::value_t::object:
  10040. {
  10041. // create an entry in the object
  10042. result = &result->operator[](reference_token);
  10043. break;
  10044. }
  10045. case detail::value_t::array:
  10046. {
  10047. // create an entry in the array
  10048. result = &result->operator[](array_index(reference_token));
  10049. break;
  10050. }
  10051. /*
  10052. The following code is only reached if there exists a reference
  10053. token _and_ the current value is primitive. In this case, we have
  10054. an error situation, because primitive values may only occur as
  10055. single value; that is, with an empty list of reference tokens.
  10056. */
  10057. default:
  10058. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  10059. }
  10060. }
  10061. return *result;
  10062. }
  10063. /*!
  10064. @brief return a reference to the pointed to value
  10065. @note This version does not throw if a value is not present, but tries to
  10066. create nested values instead. For instance, calling this function
  10067. with pointer `"/this/that"` on a null value is equivalent to calling
  10068. `operator[]("this").operator[]("that")` on that value, effectively
  10069. changing the null value to an object.
  10070. @param[in] ptr a JSON value
  10071. @return reference to the JSON value pointed to by the JSON pointer
  10072. @complexity Linear in the length of the JSON pointer.
  10073. @throw parse_error.106 if an array index begins with '0'
  10074. @throw parse_error.109 if an array index was not a number
  10075. @throw out_of_range.404 if the JSON pointer can not be resolved
  10076. */
  10077. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  10078. {
  10079. for (const auto& reference_token : reference_tokens)
  10080. {
  10081. // convert null values to arrays or objects before continuing
  10082. if (ptr->is_null())
  10083. {
  10084. // check if reference token is a number
  10085. const bool nums =
  10086. std::all_of(reference_token.begin(), reference_token.end(),
  10087. [](const unsigned char x)
  10088. {
  10089. return std::isdigit(x);
  10090. });
  10091. // change value to array for numbers or "-" or to object otherwise
  10092. *ptr = (nums || reference_token == "-")
  10093. ? detail::value_t::array
  10094. : detail::value_t::object;
  10095. }
  10096. switch (ptr->type())
  10097. {
  10098. case detail::value_t::object:
  10099. {
  10100. // use unchecked object access
  10101. ptr = &ptr->operator[](reference_token);
  10102. break;
  10103. }
  10104. case detail::value_t::array:
  10105. {
  10106. if (reference_token == "-")
  10107. {
  10108. // explicitly treat "-" as index beyond the end
  10109. ptr = &ptr->operator[](ptr->m_value.array->size());
  10110. }
  10111. else
  10112. {
  10113. // convert array index to number; unchecked access
  10114. ptr = &ptr->operator[](array_index(reference_token));
  10115. }
  10116. break;
  10117. }
  10118. default:
  10119. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10120. }
  10121. }
  10122. return *ptr;
  10123. }
  10124. /*!
  10125. @throw parse_error.106 if an array index begins with '0'
  10126. @throw parse_error.109 if an array index was not a number
  10127. @throw out_of_range.402 if the array index '-' is used
  10128. @throw out_of_range.404 if the JSON pointer can not be resolved
  10129. */
  10130. BasicJsonType& get_checked(BasicJsonType* ptr) const
  10131. {
  10132. for (const auto& reference_token : reference_tokens)
  10133. {
  10134. switch (ptr->type())
  10135. {
  10136. case detail::value_t::object:
  10137. {
  10138. // note: at performs range check
  10139. ptr = &ptr->at(reference_token);
  10140. break;
  10141. }
  10142. case detail::value_t::array:
  10143. {
  10144. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10145. {
  10146. // "-" always fails the range check
  10147. JSON_THROW(detail::out_of_range::create(402,
  10148. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10149. ") is out of range"));
  10150. }
  10151. // note: at performs range check
  10152. ptr = &ptr->at(array_index(reference_token));
  10153. break;
  10154. }
  10155. default:
  10156. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10157. }
  10158. }
  10159. return *ptr;
  10160. }
  10161. /*!
  10162. @brief return a const reference to the pointed to value
  10163. @param[in] ptr a JSON value
  10164. @return const reference to the JSON value pointed to by the JSON
  10165. pointer
  10166. @throw parse_error.106 if an array index begins with '0'
  10167. @throw parse_error.109 if an array index was not a number
  10168. @throw out_of_range.402 if the array index '-' is used
  10169. @throw out_of_range.404 if the JSON pointer can not be resolved
  10170. */
  10171. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  10172. {
  10173. for (const auto& reference_token : reference_tokens)
  10174. {
  10175. switch (ptr->type())
  10176. {
  10177. case detail::value_t::object:
  10178. {
  10179. // use unchecked object access
  10180. ptr = &ptr->operator[](reference_token);
  10181. break;
  10182. }
  10183. case detail::value_t::array:
  10184. {
  10185. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10186. {
  10187. // "-" cannot be used for const access
  10188. JSON_THROW(detail::out_of_range::create(402,
  10189. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10190. ") is out of range"));
  10191. }
  10192. // use unchecked array access
  10193. ptr = &ptr->operator[](array_index(reference_token));
  10194. break;
  10195. }
  10196. default:
  10197. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10198. }
  10199. }
  10200. return *ptr;
  10201. }
  10202. /*!
  10203. @throw parse_error.106 if an array index begins with '0'
  10204. @throw parse_error.109 if an array index was not a number
  10205. @throw out_of_range.402 if the array index '-' is used
  10206. @throw out_of_range.404 if the JSON pointer can not be resolved
  10207. */
  10208. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  10209. {
  10210. for (const auto& reference_token : reference_tokens)
  10211. {
  10212. switch (ptr->type())
  10213. {
  10214. case detail::value_t::object:
  10215. {
  10216. // note: at performs range check
  10217. ptr = &ptr->at(reference_token);
  10218. break;
  10219. }
  10220. case detail::value_t::array:
  10221. {
  10222. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10223. {
  10224. // "-" always fails the range check
  10225. JSON_THROW(detail::out_of_range::create(402,
  10226. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  10227. ") is out of range"));
  10228. }
  10229. // note: at performs range check
  10230. ptr = &ptr->at(array_index(reference_token));
  10231. break;
  10232. }
  10233. default:
  10234. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10235. }
  10236. }
  10237. return *ptr;
  10238. }
  10239. /*!
  10240. @throw parse_error.106 if an array index begins with '0'
  10241. @throw parse_error.109 if an array index was not a number
  10242. */
  10243. bool contains(const BasicJsonType* ptr) const
  10244. {
  10245. for (const auto& reference_token : reference_tokens)
  10246. {
  10247. switch (ptr->type())
  10248. {
  10249. case detail::value_t::object:
  10250. {
  10251. if (!ptr->contains(reference_token))
  10252. {
  10253. // we did not find the key in the object
  10254. return false;
  10255. }
  10256. ptr = &ptr->operator[](reference_token);
  10257. break;
  10258. }
  10259. case detail::value_t::array:
  10260. {
  10261. if (JSON_HEDLEY_UNLIKELY(reference_token == "-"))
  10262. {
  10263. // "-" always fails the range check
  10264. return false;
  10265. }
  10266. if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
  10267. {
  10268. // invalid char
  10269. return false;
  10270. }
  10271. if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1))
  10272. {
  10273. if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9')))
  10274. {
  10275. // first char should be between '1' and '9'
  10276. return false;
  10277. }
  10278. for (std::size_t i = 1; i < reference_token.size(); i++)
  10279. {
  10280. if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9')))
  10281. {
  10282. // other char should be between '0' and '9'
  10283. return false;
  10284. }
  10285. }
  10286. }
  10287. const auto idx = array_index(reference_token);
  10288. if (idx >= ptr->size())
  10289. {
  10290. // index out of range
  10291. return false;
  10292. }
  10293. ptr = &ptr->operator[](idx);
  10294. break;
  10295. }
  10296. default:
  10297. {
  10298. // we do not expect primitive values if there is still a
  10299. // reference token to process
  10300. return false;
  10301. }
  10302. }
  10303. }
  10304. // no reference token left means we found a primitive value
  10305. return true;
  10306. }
  10307. /*!
  10308. @brief split the string input to reference tokens
  10309. @note This function is only called by the json_pointer constructor.
  10310. All exceptions below are documented there.
  10311. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10312. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10313. */
  10314. static std::vector<std::string> split(const std::string& reference_string)
  10315. {
  10316. std::vector<std::string> result;
  10317. // special case: empty reference string -> no reference tokens
  10318. if (reference_string.empty())
  10319. {
  10320. return result;
  10321. }
  10322. // check if nonempty reference string begins with slash
  10323. if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/'))
  10324. {
  10325. JSON_THROW(detail::parse_error::create(107, 1,
  10326. "JSON pointer must be empty or begin with '/' - was: '" +
  10327. reference_string + "'"));
  10328. }
  10329. // extract the reference tokens:
  10330. // - slash: position of the last read slash (or end of string)
  10331. // - start: position after the previous slash
  10332. for (
  10333. // search for the first slash after the first character
  10334. std::size_t slash = reference_string.find_first_of('/', 1),
  10335. // set the beginning of the first reference token
  10336. start = 1;
  10337. // we can stop if start == 0 (if slash == std::string::npos)
  10338. start != 0;
  10339. // set the beginning of the next reference token
  10340. // (will eventually be 0 if slash == std::string::npos)
  10341. start = (slash == std::string::npos) ? 0 : slash + 1,
  10342. // find next slash
  10343. slash = reference_string.find_first_of('/', start))
  10344. {
  10345. // use the text between the beginning of the reference token
  10346. // (start) and the last slash (slash).
  10347. auto reference_token = reference_string.substr(start, slash - start);
  10348. // check reference tokens are properly escaped
  10349. for (std::size_t pos = reference_token.find_first_of('~');
  10350. pos != std::string::npos;
  10351. pos = reference_token.find_first_of('~', pos + 1))
  10352. {
  10353. JSON_ASSERT(reference_token[pos] == '~');
  10354. // ~ must be followed by 0 or 1
  10355. if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 ||
  10356. (reference_token[pos + 1] != '0' &&
  10357. reference_token[pos + 1] != '1')))
  10358. {
  10359. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  10360. }
  10361. }
  10362. // finally, store the reference token
  10363. unescape(reference_token);
  10364. result.push_back(reference_token);
  10365. }
  10366. return result;
  10367. }
  10368. /*!
  10369. @brief replace all occurrences of a substring by another string
  10370. @param[in,out] s the string to manipulate; changed so that all
  10371. occurrences of @a f are replaced with @a t
  10372. @param[in] f the substring to replace with @a t
  10373. @param[in] t the string to replace @a f
  10374. @pre The search string @a f must not be empty. **This precondition is
  10375. enforced with an assertion.**
  10376. @since version 2.0.0
  10377. */
  10378. static void replace_substring(std::string& s, const std::string& f,
  10379. const std::string& t)
  10380. {
  10381. JSON_ASSERT(!f.empty());
  10382. for (auto pos = s.find(f); // find first occurrence of f
  10383. pos != std::string::npos; // make sure f was found
  10384. s.replace(pos, f.size(), t), // replace with t, and
  10385. pos = s.find(f, pos + t.size())) // find next occurrence of f
  10386. {}
  10387. }
  10388. /// escape "~" to "~0" and "/" to "~1"
  10389. static std::string escape(std::string s)
  10390. {
  10391. replace_substring(s, "~", "~0");
  10392. replace_substring(s, "/", "~1");
  10393. return s;
  10394. }
  10395. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  10396. static void unescape(std::string& s)
  10397. {
  10398. replace_substring(s, "~1", "/");
  10399. replace_substring(s, "~0", "~");
  10400. }
  10401. /*!
  10402. @param[in] reference_string the reference string to the current value
  10403. @param[in] value the value to consider
  10404. @param[in,out] result the result object to insert values to
  10405. @note Empty objects or arrays are flattened to `null`.
  10406. */
  10407. static void flatten(const std::string& reference_string,
  10408. const BasicJsonType& value,
  10409. BasicJsonType& result)
  10410. {
  10411. switch (value.type())
  10412. {
  10413. case detail::value_t::array:
  10414. {
  10415. if (value.m_value.array->empty())
  10416. {
  10417. // flatten empty array as null
  10418. result[reference_string] = nullptr;
  10419. }
  10420. else
  10421. {
  10422. // iterate array and use index as reference string
  10423. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  10424. {
  10425. flatten(reference_string + "/" + std::to_string(i),
  10426. value.m_value.array->operator[](i), result);
  10427. }
  10428. }
  10429. break;
  10430. }
  10431. case detail::value_t::object:
  10432. {
  10433. if (value.m_value.object->empty())
  10434. {
  10435. // flatten empty object as null
  10436. result[reference_string] = nullptr;
  10437. }
  10438. else
  10439. {
  10440. // iterate object and use keys as reference string
  10441. for (const auto& element : *value.m_value.object)
  10442. {
  10443. flatten(reference_string + "/" + escape(element.first), element.second, result);
  10444. }
  10445. }
  10446. break;
  10447. }
  10448. default:
  10449. {
  10450. // add primitive value with its reference string
  10451. result[reference_string] = value;
  10452. break;
  10453. }
  10454. }
  10455. }
  10456. /*!
  10457. @param[in] value flattened JSON
  10458. @return unflattened JSON
  10459. @throw parse_error.109 if array index is not a number
  10460. @throw type_error.314 if value is not an object
  10461. @throw type_error.315 if object values are not primitive
  10462. @throw type_error.313 if value cannot be unflattened
  10463. */
  10464. static BasicJsonType
  10465. unflatten(const BasicJsonType& value)
  10466. {
  10467. if (JSON_HEDLEY_UNLIKELY(!value.is_object()))
  10468. {
  10469. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  10470. }
  10471. BasicJsonType result;
  10472. // iterate the JSON object values
  10473. for (const auto& element : *value.m_value.object)
  10474. {
  10475. if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive()))
  10476. {
  10477. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  10478. }
  10479. // assign value to reference pointed to by JSON pointer; Note that if
  10480. // the JSON pointer is "" (i.e., points to the whole value), function
  10481. // get_and_create returns a reference to result itself. An assignment
  10482. // will then create a primitive value.
  10483. json_pointer(element.first).get_and_create(result) = element.second;
  10484. }
  10485. return result;
  10486. }
  10487. /*!
  10488. @brief compares two JSON pointers for equality
  10489. @param[in] lhs JSON pointer to compare
  10490. @param[in] rhs JSON pointer to compare
  10491. @return whether @a lhs is equal to @a rhs
  10492. @complexity Linear in the length of the JSON pointer
  10493. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10494. */
  10495. friend bool operator==(json_pointer const& lhs,
  10496. json_pointer const& rhs) noexcept
  10497. {
  10498. return lhs.reference_tokens == rhs.reference_tokens;
  10499. }
  10500. /*!
  10501. @brief compares two JSON pointers for inequality
  10502. @param[in] lhs JSON pointer to compare
  10503. @param[in] rhs JSON pointer to compare
  10504. @return whether @a lhs is not equal @a rhs
  10505. @complexity Linear in the length of the JSON pointer
  10506. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10507. */
  10508. friend bool operator!=(json_pointer const& lhs,
  10509. json_pointer const& rhs) noexcept
  10510. {
  10511. return !(lhs == rhs);
  10512. }
  10513. /// the reference tokens
  10514. std::vector<std::string> reference_tokens;
  10515. };
  10516. } // namespace nlohmann
  10517. // #include <nlohmann/detail/json_ref.hpp>
  10518. #include <initializer_list>
  10519. #include <utility>
  10520. // #include <nlohmann/detail/meta/type_traits.hpp>
  10521. namespace nlohmann
  10522. {
  10523. namespace detail
  10524. {
  10525. template<typename BasicJsonType>
  10526. class json_ref
  10527. {
  10528. public:
  10529. using value_type = BasicJsonType;
  10530. json_ref(value_type&& value)
  10531. : owned_value(std::move(value))
  10532. , value_ref(&owned_value)
  10533. , is_rvalue(true)
  10534. {}
  10535. json_ref(const value_type& value)
  10536. : value_ref(const_cast<value_type*>(&value))
  10537. , is_rvalue(false)
  10538. {}
  10539. json_ref(std::initializer_list<json_ref> init)
  10540. : owned_value(init)
  10541. , value_ref(&owned_value)
  10542. , is_rvalue(true)
  10543. {}
  10544. template <
  10545. class... Args,
  10546. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  10547. json_ref(Args && ... args)
  10548. : owned_value(std::forward<Args>(args)...)
  10549. , value_ref(&owned_value)
  10550. , is_rvalue(true)
  10551. {}
  10552. // class should be movable only
  10553. json_ref(json_ref&&) = default;
  10554. json_ref(const json_ref&) = delete;
  10555. json_ref& operator=(const json_ref&) = delete;
  10556. json_ref& operator=(json_ref&&) = delete;
  10557. ~json_ref() = default;
  10558. value_type moved_or_copied() const
  10559. {
  10560. if (is_rvalue)
  10561. {
  10562. return std::move(*value_ref);
  10563. }
  10564. return *value_ref;
  10565. }
  10566. value_type const& operator*() const
  10567. {
  10568. return *static_cast<value_type const*>(value_ref);
  10569. }
  10570. value_type const* operator->() const
  10571. {
  10572. return static_cast<value_type const*>(value_ref);
  10573. }
  10574. private:
  10575. mutable value_type owned_value = nullptr;
  10576. value_type* value_ref = nullptr;
  10577. const bool is_rvalue = true;
  10578. };
  10579. } // namespace detail
  10580. } // namespace nlohmann
  10581. // #include <nlohmann/detail/macro_scope.hpp>
  10582. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10583. // #include <nlohmann/detail/meta/type_traits.hpp>
  10584. // #include <nlohmann/detail/output/binary_writer.hpp>
  10585. #include <algorithm> // reverse
  10586. #include <array> // array
  10587. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  10588. #include <cstring> // memcpy
  10589. #include <limits> // numeric_limits
  10590. #include <string> // string
  10591. #include <cmath> // isnan, isinf
  10592. // #include <nlohmann/detail/input/binary_reader.hpp>
  10593. // #include <nlohmann/detail/macro_scope.hpp>
  10594. // #include <nlohmann/detail/output/output_adapters.hpp>
  10595. #include <algorithm> // copy
  10596. #include <cstddef> // size_t
  10597. #include <ios> // streamsize
  10598. #include <iterator> // back_inserter
  10599. #include <memory> // shared_ptr, make_shared
  10600. #include <ostream> // basic_ostream
  10601. #include <string> // basic_string
  10602. #include <vector> // vector
  10603. // #include <nlohmann/detail/macro_scope.hpp>
  10604. namespace nlohmann
  10605. {
  10606. namespace detail
  10607. {
  10608. /// abstract output adapter interface
  10609. template<typename CharType> struct output_adapter_protocol
  10610. {
  10611. virtual void write_character(CharType c) = 0;
  10612. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  10613. virtual ~output_adapter_protocol() = default;
  10614. };
  10615. /// a type to simplify interfaces
  10616. template<typename CharType>
  10617. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  10618. /// output adapter for byte vectors
  10619. template<typename CharType>
  10620. class output_vector_adapter : public output_adapter_protocol<CharType>
  10621. {
  10622. public:
  10623. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  10624. : v(vec)
  10625. {}
  10626. void write_character(CharType c) override
  10627. {
  10628. v.push_back(c);
  10629. }
  10630. JSON_HEDLEY_NON_NULL(2)
  10631. void write_characters(const CharType* s, std::size_t length) override
  10632. {
  10633. std::copy(s, s + length, std::back_inserter(v));
  10634. }
  10635. private:
  10636. std::vector<CharType>& v;
  10637. };
  10638. /// output adapter for output streams
  10639. template<typename CharType>
  10640. class output_stream_adapter : public output_adapter_protocol<CharType>
  10641. {
  10642. public:
  10643. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  10644. : stream(s)
  10645. {}
  10646. void write_character(CharType c) override
  10647. {
  10648. stream.put(c);
  10649. }
  10650. JSON_HEDLEY_NON_NULL(2)
  10651. void write_characters(const CharType* s, std::size_t length) override
  10652. {
  10653. stream.write(s, static_cast<std::streamsize>(length));
  10654. }
  10655. private:
  10656. std::basic_ostream<CharType>& stream;
  10657. };
  10658. /// output adapter for basic_string
  10659. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10660. class output_string_adapter : public output_adapter_protocol<CharType>
  10661. {
  10662. public:
  10663. explicit output_string_adapter(StringType& s) noexcept
  10664. : str(s)
  10665. {}
  10666. void write_character(CharType c) override
  10667. {
  10668. str.push_back(c);
  10669. }
  10670. JSON_HEDLEY_NON_NULL(2)
  10671. void write_characters(const CharType* s, std::size_t length) override
  10672. {
  10673. str.append(s, length);
  10674. }
  10675. private:
  10676. StringType& str;
  10677. };
  10678. template<typename CharType, typename StringType = std::basic_string<CharType>>
  10679. class output_adapter
  10680. {
  10681. public:
  10682. output_adapter(std::vector<CharType>& vec)
  10683. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  10684. output_adapter(std::basic_ostream<CharType>& s)
  10685. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  10686. output_adapter(StringType& s)
  10687. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  10688. operator output_adapter_t<CharType>()
  10689. {
  10690. return oa;
  10691. }
  10692. private:
  10693. output_adapter_t<CharType> oa = nullptr;
  10694. };
  10695. } // namespace detail
  10696. } // namespace nlohmann
  10697. namespace nlohmann
  10698. {
  10699. namespace detail
  10700. {
  10701. ///////////////////
  10702. // binary writer //
  10703. ///////////////////
  10704. /*!
  10705. @brief serialization to CBOR and MessagePack values
  10706. */
  10707. template<typename BasicJsonType, typename CharType>
  10708. class binary_writer
  10709. {
  10710. using string_t = typename BasicJsonType::string_t;
  10711. using binary_t = typename BasicJsonType::binary_t;
  10712. using number_float_t = typename BasicJsonType::number_float_t;
  10713. public:
  10714. /*!
  10715. @brief create a binary writer
  10716. @param[in] adapter output adapter to write to
  10717. */
  10718. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  10719. {
  10720. JSON_ASSERT(oa);
  10721. }
  10722. /*!
  10723. @param[in] j JSON value to serialize
  10724. @pre j.type() == value_t::object
  10725. */
  10726. void write_bson(const BasicJsonType& j)
  10727. {
  10728. switch (j.type())
  10729. {
  10730. case value_t::object:
  10731. {
  10732. write_bson_object(*j.m_value.object);
  10733. break;
  10734. }
  10735. default:
  10736. {
  10737. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  10738. }
  10739. }
  10740. }
  10741. /*!
  10742. @param[in] j JSON value to serialize
  10743. */
  10744. void write_cbor(const BasicJsonType& j)
  10745. {
  10746. switch (j.type())
  10747. {
  10748. case value_t::null:
  10749. {
  10750. oa->write_character(to_char_type(0xF6));
  10751. break;
  10752. }
  10753. case value_t::boolean:
  10754. {
  10755. oa->write_character(j.m_value.boolean
  10756. ? to_char_type(0xF5)
  10757. : to_char_type(0xF4));
  10758. break;
  10759. }
  10760. case value_t::number_integer:
  10761. {
  10762. if (j.m_value.number_integer >= 0)
  10763. {
  10764. // CBOR does not differentiate between positive signed
  10765. // integers and unsigned integers. Therefore, we used the
  10766. // code from the value_t::number_unsigned case here.
  10767. if (j.m_value.number_integer <= 0x17)
  10768. {
  10769. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10770. }
  10771. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  10772. {
  10773. oa->write_character(to_char_type(0x18));
  10774. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  10775. }
  10776. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  10777. {
  10778. oa->write_character(to_char_type(0x19));
  10779. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  10780. }
  10781. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  10782. {
  10783. oa->write_character(to_char_type(0x1A));
  10784. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  10785. }
  10786. else
  10787. {
  10788. oa->write_character(to_char_type(0x1B));
  10789. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  10790. }
  10791. }
  10792. else
  10793. {
  10794. // The conversions below encode the sign in the first
  10795. // byte, and the value is converted to a positive number.
  10796. const auto positive_number = -1 - j.m_value.number_integer;
  10797. if (j.m_value.number_integer >= -24)
  10798. {
  10799. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  10800. }
  10801. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  10802. {
  10803. oa->write_character(to_char_type(0x38));
  10804. write_number(static_cast<std::uint8_t>(positive_number));
  10805. }
  10806. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  10807. {
  10808. oa->write_character(to_char_type(0x39));
  10809. write_number(static_cast<std::uint16_t>(positive_number));
  10810. }
  10811. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  10812. {
  10813. oa->write_character(to_char_type(0x3A));
  10814. write_number(static_cast<std::uint32_t>(positive_number));
  10815. }
  10816. else
  10817. {
  10818. oa->write_character(to_char_type(0x3B));
  10819. write_number(static_cast<std::uint64_t>(positive_number));
  10820. }
  10821. }
  10822. break;
  10823. }
  10824. case value_t::number_unsigned:
  10825. {
  10826. if (j.m_value.number_unsigned <= 0x17)
  10827. {
  10828. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10829. }
  10830. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  10831. {
  10832. oa->write_character(to_char_type(0x18));
  10833. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  10834. }
  10835. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  10836. {
  10837. oa->write_character(to_char_type(0x19));
  10838. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  10839. }
  10840. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  10841. {
  10842. oa->write_character(to_char_type(0x1A));
  10843. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  10844. }
  10845. else
  10846. {
  10847. oa->write_character(to_char_type(0x1B));
  10848. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  10849. }
  10850. break;
  10851. }
  10852. case value_t::number_float:
  10853. {
  10854. if (std::isnan(j.m_value.number_float))
  10855. {
  10856. // NaN is 0xf97e00 in CBOR
  10857. oa->write_character(to_char_type(0xF9));
  10858. oa->write_character(to_char_type(0x7E));
  10859. oa->write_character(to_char_type(0x00));
  10860. }
  10861. else if (std::isinf(j.m_value.number_float))
  10862. {
  10863. // Infinity is 0xf97c00, -Infinity is 0xf9fc00
  10864. oa->write_character(to_char_type(0xf9));
  10865. oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC));
  10866. oa->write_character(to_char_type(0x00));
  10867. }
  10868. else
  10869. {
  10870. write_compact_float(j.m_value.number_float, detail::input_format_t::cbor);
  10871. }
  10872. break;
  10873. }
  10874. case value_t::string:
  10875. {
  10876. // step 1: write control byte and the string length
  10877. const auto N = j.m_value.string->size();
  10878. if (N <= 0x17)
  10879. {
  10880. write_number(static_cast<std::uint8_t>(0x60 + N));
  10881. }
  10882. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10883. {
  10884. oa->write_character(to_char_type(0x78));
  10885. write_number(static_cast<std::uint8_t>(N));
  10886. }
  10887. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10888. {
  10889. oa->write_character(to_char_type(0x79));
  10890. write_number(static_cast<std::uint16_t>(N));
  10891. }
  10892. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10893. {
  10894. oa->write_character(to_char_type(0x7A));
  10895. write_number(static_cast<std::uint32_t>(N));
  10896. }
  10897. // LCOV_EXCL_START
  10898. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10899. {
  10900. oa->write_character(to_char_type(0x7B));
  10901. write_number(static_cast<std::uint64_t>(N));
  10902. }
  10903. // LCOV_EXCL_STOP
  10904. // step 2: write the string
  10905. oa->write_characters(
  10906. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  10907. j.m_value.string->size());
  10908. break;
  10909. }
  10910. case value_t::array:
  10911. {
  10912. // step 1: write control byte and the array size
  10913. const auto N = j.m_value.array->size();
  10914. if (N <= 0x17)
  10915. {
  10916. write_number(static_cast<std::uint8_t>(0x80 + N));
  10917. }
  10918. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10919. {
  10920. oa->write_character(to_char_type(0x98));
  10921. write_number(static_cast<std::uint8_t>(N));
  10922. }
  10923. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10924. {
  10925. oa->write_character(to_char_type(0x99));
  10926. write_number(static_cast<std::uint16_t>(N));
  10927. }
  10928. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10929. {
  10930. oa->write_character(to_char_type(0x9A));
  10931. write_number(static_cast<std::uint32_t>(N));
  10932. }
  10933. // LCOV_EXCL_START
  10934. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10935. {
  10936. oa->write_character(to_char_type(0x9B));
  10937. write_number(static_cast<std::uint64_t>(N));
  10938. }
  10939. // LCOV_EXCL_STOP
  10940. // step 2: write each element
  10941. for (const auto& el : *j.m_value.array)
  10942. {
  10943. write_cbor(el);
  10944. }
  10945. break;
  10946. }
  10947. case value_t::binary:
  10948. {
  10949. // step 1: write control byte and the binary array size
  10950. const auto N = j.m_value.binary->size();
  10951. if (N <= 0x17)
  10952. {
  10953. write_number(static_cast<std::uint8_t>(0x40 + N));
  10954. }
  10955. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10956. {
  10957. oa->write_character(to_char_type(0x58));
  10958. write_number(static_cast<std::uint8_t>(N));
  10959. }
  10960. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10961. {
  10962. oa->write_character(to_char_type(0x59));
  10963. write_number(static_cast<std::uint16_t>(N));
  10964. }
  10965. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  10966. {
  10967. oa->write_character(to_char_type(0x5A));
  10968. write_number(static_cast<std::uint32_t>(N));
  10969. }
  10970. // LCOV_EXCL_START
  10971. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  10972. {
  10973. oa->write_character(to_char_type(0x5B));
  10974. write_number(static_cast<std::uint64_t>(N));
  10975. }
  10976. // LCOV_EXCL_STOP
  10977. // step 2: write each element
  10978. oa->write_characters(
  10979. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  10980. N);
  10981. break;
  10982. }
  10983. case value_t::object:
  10984. {
  10985. // step 1: write control byte and the object size
  10986. const auto N = j.m_value.object->size();
  10987. if (N <= 0x17)
  10988. {
  10989. write_number(static_cast<std::uint8_t>(0xA0 + N));
  10990. }
  10991. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  10992. {
  10993. oa->write_character(to_char_type(0xB8));
  10994. write_number(static_cast<std::uint8_t>(N));
  10995. }
  10996. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  10997. {
  10998. oa->write_character(to_char_type(0xB9));
  10999. write_number(static_cast<std::uint16_t>(N));
  11000. }
  11001. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11002. {
  11003. oa->write_character(to_char_type(0xBA));
  11004. write_number(static_cast<std::uint32_t>(N));
  11005. }
  11006. // LCOV_EXCL_START
  11007. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  11008. {
  11009. oa->write_character(to_char_type(0xBB));
  11010. write_number(static_cast<std::uint64_t>(N));
  11011. }
  11012. // LCOV_EXCL_STOP
  11013. // step 2: write each element
  11014. for (const auto& el : *j.m_value.object)
  11015. {
  11016. write_cbor(el.first);
  11017. write_cbor(el.second);
  11018. }
  11019. break;
  11020. }
  11021. default:
  11022. break;
  11023. }
  11024. }
  11025. /*!
  11026. @param[in] j JSON value to serialize
  11027. */
  11028. void write_msgpack(const BasicJsonType& j)
  11029. {
  11030. switch (j.type())
  11031. {
  11032. case value_t::null: // nil
  11033. {
  11034. oa->write_character(to_char_type(0xC0));
  11035. break;
  11036. }
  11037. case value_t::boolean: // true and false
  11038. {
  11039. oa->write_character(j.m_value.boolean
  11040. ? to_char_type(0xC3)
  11041. : to_char_type(0xC2));
  11042. break;
  11043. }
  11044. case value_t::number_integer:
  11045. {
  11046. if (j.m_value.number_integer >= 0)
  11047. {
  11048. // MessagePack does not differentiate between positive
  11049. // signed integers and unsigned integers. Therefore, we used
  11050. // the code from the value_t::number_unsigned case here.
  11051. if (j.m_value.number_unsigned < 128)
  11052. {
  11053. // positive fixnum
  11054. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11055. }
  11056. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11057. {
  11058. // uint 8
  11059. oa->write_character(to_char_type(0xCC));
  11060. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11061. }
  11062. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11063. {
  11064. // uint 16
  11065. oa->write_character(to_char_type(0xCD));
  11066. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11067. }
  11068. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11069. {
  11070. // uint 32
  11071. oa->write_character(to_char_type(0xCE));
  11072. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11073. }
  11074. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  11075. {
  11076. // uint 64
  11077. oa->write_character(to_char_type(0xCF));
  11078. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11079. }
  11080. }
  11081. else
  11082. {
  11083. if (j.m_value.number_integer >= -32)
  11084. {
  11085. // negative fixnum
  11086. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  11087. }
  11088. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() &&
  11089. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  11090. {
  11091. // int 8
  11092. oa->write_character(to_char_type(0xD0));
  11093. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  11094. }
  11095. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() &&
  11096. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  11097. {
  11098. // int 16
  11099. oa->write_character(to_char_type(0xD1));
  11100. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  11101. }
  11102. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() &&
  11103. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  11104. {
  11105. // int 32
  11106. oa->write_character(to_char_type(0xD2));
  11107. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  11108. }
  11109. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() &&
  11110. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  11111. {
  11112. // int 64
  11113. oa->write_character(to_char_type(0xD3));
  11114. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  11115. }
  11116. }
  11117. break;
  11118. }
  11119. case value_t::number_unsigned:
  11120. {
  11121. if (j.m_value.number_unsigned < 128)
  11122. {
  11123. // positive fixnum
  11124. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11125. }
  11126. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  11127. {
  11128. // uint 8
  11129. oa->write_character(to_char_type(0xCC));
  11130. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  11131. }
  11132. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  11133. {
  11134. // uint 16
  11135. oa->write_character(to_char_type(0xCD));
  11136. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  11137. }
  11138. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  11139. {
  11140. // uint 32
  11141. oa->write_character(to_char_type(0xCE));
  11142. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  11143. }
  11144. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  11145. {
  11146. // uint 64
  11147. oa->write_character(to_char_type(0xCF));
  11148. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  11149. }
  11150. break;
  11151. }
  11152. case value_t::number_float:
  11153. {
  11154. write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack);
  11155. break;
  11156. }
  11157. case value_t::string:
  11158. {
  11159. // step 1: write control byte and the string length
  11160. const auto N = j.m_value.string->size();
  11161. if (N <= 31)
  11162. {
  11163. // fixstr
  11164. write_number(static_cast<std::uint8_t>(0xA0 | N));
  11165. }
  11166. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11167. {
  11168. // str 8
  11169. oa->write_character(to_char_type(0xD9));
  11170. write_number(static_cast<std::uint8_t>(N));
  11171. }
  11172. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11173. {
  11174. // str 16
  11175. oa->write_character(to_char_type(0xDA));
  11176. write_number(static_cast<std::uint16_t>(N));
  11177. }
  11178. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11179. {
  11180. // str 32
  11181. oa->write_character(to_char_type(0xDB));
  11182. write_number(static_cast<std::uint32_t>(N));
  11183. }
  11184. // step 2: write the string
  11185. oa->write_characters(
  11186. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11187. j.m_value.string->size());
  11188. break;
  11189. }
  11190. case value_t::array:
  11191. {
  11192. // step 1: write control byte and the array size
  11193. const auto N = j.m_value.array->size();
  11194. if (N <= 15)
  11195. {
  11196. // fixarray
  11197. write_number(static_cast<std::uint8_t>(0x90 | N));
  11198. }
  11199. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11200. {
  11201. // array 16
  11202. oa->write_character(to_char_type(0xDC));
  11203. write_number(static_cast<std::uint16_t>(N));
  11204. }
  11205. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11206. {
  11207. // array 32
  11208. oa->write_character(to_char_type(0xDD));
  11209. write_number(static_cast<std::uint32_t>(N));
  11210. }
  11211. // step 2: write each element
  11212. for (const auto& el : *j.m_value.array)
  11213. {
  11214. write_msgpack(el);
  11215. }
  11216. break;
  11217. }
  11218. case value_t::binary:
  11219. {
  11220. // step 0: determine if the binary type has a set subtype to
  11221. // determine whether or not to use the ext or fixext types
  11222. const bool use_ext = j.m_value.binary->has_subtype();
  11223. // step 1: write control byte and the byte string length
  11224. const auto N = j.m_value.binary->size();
  11225. if (N <= (std::numeric_limits<std::uint8_t>::max)())
  11226. {
  11227. std::uint8_t output_type{};
  11228. bool fixed = true;
  11229. if (use_ext)
  11230. {
  11231. switch (N)
  11232. {
  11233. case 1:
  11234. output_type = 0xD4; // fixext 1
  11235. break;
  11236. case 2:
  11237. output_type = 0xD5; // fixext 2
  11238. break;
  11239. case 4:
  11240. output_type = 0xD6; // fixext 4
  11241. break;
  11242. case 8:
  11243. output_type = 0xD7; // fixext 8
  11244. break;
  11245. case 16:
  11246. output_type = 0xD8; // fixext 16
  11247. break;
  11248. default:
  11249. output_type = 0xC7; // ext 8
  11250. fixed = false;
  11251. break;
  11252. }
  11253. }
  11254. else
  11255. {
  11256. output_type = 0xC4; // bin 8
  11257. fixed = false;
  11258. }
  11259. oa->write_character(to_char_type(output_type));
  11260. if (!fixed)
  11261. {
  11262. write_number(static_cast<std::uint8_t>(N));
  11263. }
  11264. }
  11265. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11266. {
  11267. std::uint8_t output_type = use_ext
  11268. ? 0xC8 // ext 16
  11269. : 0xC5; // bin 16
  11270. oa->write_character(to_char_type(output_type));
  11271. write_number(static_cast<std::uint16_t>(N));
  11272. }
  11273. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11274. {
  11275. std::uint8_t output_type = use_ext
  11276. ? 0xC9 // ext 32
  11277. : 0xC6; // bin 32
  11278. oa->write_character(to_char_type(output_type));
  11279. write_number(static_cast<std::uint32_t>(N));
  11280. }
  11281. // step 1.5: if this is an ext type, write the subtype
  11282. if (use_ext)
  11283. {
  11284. write_number(static_cast<std::int8_t>(j.m_value.binary->subtype()));
  11285. }
  11286. // step 2: write the byte string
  11287. oa->write_characters(
  11288. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11289. N);
  11290. break;
  11291. }
  11292. case value_t::object:
  11293. {
  11294. // step 1: write control byte and the object size
  11295. const auto N = j.m_value.object->size();
  11296. if (N <= 15)
  11297. {
  11298. // fixmap
  11299. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  11300. }
  11301. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  11302. {
  11303. // map 16
  11304. oa->write_character(to_char_type(0xDE));
  11305. write_number(static_cast<std::uint16_t>(N));
  11306. }
  11307. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  11308. {
  11309. // map 32
  11310. oa->write_character(to_char_type(0xDF));
  11311. write_number(static_cast<std::uint32_t>(N));
  11312. }
  11313. // step 2: write each element
  11314. for (const auto& el : *j.m_value.object)
  11315. {
  11316. write_msgpack(el.first);
  11317. write_msgpack(el.second);
  11318. }
  11319. break;
  11320. }
  11321. default:
  11322. break;
  11323. }
  11324. }
  11325. /*!
  11326. @param[in] j JSON value to serialize
  11327. @param[in] use_count whether to use '#' prefixes (optimized format)
  11328. @param[in] use_type whether to use '$' prefixes (optimized format)
  11329. @param[in] add_prefix whether prefixes need to be used for this value
  11330. */
  11331. void write_ubjson(const BasicJsonType& j, const bool use_count,
  11332. const bool use_type, const bool add_prefix = true)
  11333. {
  11334. switch (j.type())
  11335. {
  11336. case value_t::null:
  11337. {
  11338. if (add_prefix)
  11339. {
  11340. oa->write_character(to_char_type('Z'));
  11341. }
  11342. break;
  11343. }
  11344. case value_t::boolean:
  11345. {
  11346. if (add_prefix)
  11347. {
  11348. oa->write_character(j.m_value.boolean
  11349. ? to_char_type('T')
  11350. : to_char_type('F'));
  11351. }
  11352. break;
  11353. }
  11354. case value_t::number_integer:
  11355. {
  11356. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  11357. break;
  11358. }
  11359. case value_t::number_unsigned:
  11360. {
  11361. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  11362. break;
  11363. }
  11364. case value_t::number_float:
  11365. {
  11366. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  11367. break;
  11368. }
  11369. case value_t::string:
  11370. {
  11371. if (add_prefix)
  11372. {
  11373. oa->write_character(to_char_type('S'));
  11374. }
  11375. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  11376. oa->write_characters(
  11377. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  11378. j.m_value.string->size());
  11379. break;
  11380. }
  11381. case value_t::array:
  11382. {
  11383. if (add_prefix)
  11384. {
  11385. oa->write_character(to_char_type('['));
  11386. }
  11387. bool prefix_required = true;
  11388. if (use_type && !j.m_value.array->empty())
  11389. {
  11390. JSON_ASSERT(use_count);
  11391. const CharType first_prefix = ubjson_prefix(j.front());
  11392. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  11393. [this, first_prefix](const BasicJsonType & v)
  11394. {
  11395. return ubjson_prefix(v) == first_prefix;
  11396. });
  11397. if (same_prefix)
  11398. {
  11399. prefix_required = false;
  11400. oa->write_character(to_char_type('$'));
  11401. oa->write_character(first_prefix);
  11402. }
  11403. }
  11404. if (use_count)
  11405. {
  11406. oa->write_character(to_char_type('#'));
  11407. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  11408. }
  11409. for (const auto& el : *j.m_value.array)
  11410. {
  11411. write_ubjson(el, use_count, use_type, prefix_required);
  11412. }
  11413. if (!use_count)
  11414. {
  11415. oa->write_character(to_char_type(']'));
  11416. }
  11417. break;
  11418. }
  11419. case value_t::binary:
  11420. {
  11421. if (add_prefix)
  11422. {
  11423. oa->write_character(to_char_type('['));
  11424. }
  11425. if (use_type && !j.m_value.binary->empty())
  11426. {
  11427. JSON_ASSERT(use_count);
  11428. oa->write_character(to_char_type('$'));
  11429. oa->write_character('U');
  11430. }
  11431. if (use_count)
  11432. {
  11433. oa->write_character(to_char_type('#'));
  11434. write_number_with_ubjson_prefix(j.m_value.binary->size(), true);
  11435. }
  11436. if (use_type)
  11437. {
  11438. oa->write_characters(
  11439. reinterpret_cast<const CharType*>(j.m_value.binary->data()),
  11440. j.m_value.binary->size());
  11441. }
  11442. else
  11443. {
  11444. for (size_t i = 0; i < j.m_value.binary->size(); ++i)
  11445. {
  11446. oa->write_character(to_char_type('U'));
  11447. oa->write_character(j.m_value.binary->data()[i]);
  11448. }
  11449. }
  11450. if (!use_count)
  11451. {
  11452. oa->write_character(to_char_type(']'));
  11453. }
  11454. break;
  11455. }
  11456. case value_t::object:
  11457. {
  11458. if (add_prefix)
  11459. {
  11460. oa->write_character(to_char_type('{'));
  11461. }
  11462. bool prefix_required = true;
  11463. if (use_type && !j.m_value.object->empty())
  11464. {
  11465. JSON_ASSERT(use_count);
  11466. const CharType first_prefix = ubjson_prefix(j.front());
  11467. const bool same_prefix = std::all_of(j.begin(), j.end(),
  11468. [this, first_prefix](const BasicJsonType & v)
  11469. {
  11470. return ubjson_prefix(v) == first_prefix;
  11471. });
  11472. if (same_prefix)
  11473. {
  11474. prefix_required = false;
  11475. oa->write_character(to_char_type('$'));
  11476. oa->write_character(first_prefix);
  11477. }
  11478. }
  11479. if (use_count)
  11480. {
  11481. oa->write_character(to_char_type('#'));
  11482. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  11483. }
  11484. for (const auto& el : *j.m_value.object)
  11485. {
  11486. write_number_with_ubjson_prefix(el.first.size(), true);
  11487. oa->write_characters(
  11488. reinterpret_cast<const CharType*>(el.first.c_str()),
  11489. el.first.size());
  11490. write_ubjson(el.second, use_count, use_type, prefix_required);
  11491. }
  11492. if (!use_count)
  11493. {
  11494. oa->write_character(to_char_type('}'));
  11495. }
  11496. break;
  11497. }
  11498. default:
  11499. break;
  11500. }
  11501. }
  11502. private:
  11503. //////////
  11504. // BSON //
  11505. //////////
  11506. /*!
  11507. @return The size of a BSON document entry header, including the id marker
  11508. and the entry name size (and its null-terminator).
  11509. */
  11510. static std::size_t calc_bson_entry_header_size(const string_t& name)
  11511. {
  11512. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  11513. if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos))
  11514. {
  11515. JSON_THROW(out_of_range::create(409,
  11516. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  11517. }
  11518. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  11519. }
  11520. /*!
  11521. @brief Writes the given @a element_type and @a name to the output adapter
  11522. */
  11523. void write_bson_entry_header(const string_t& name,
  11524. const std::uint8_t element_type)
  11525. {
  11526. oa->write_character(to_char_type(element_type)); // boolean
  11527. oa->write_characters(
  11528. reinterpret_cast<const CharType*>(name.c_str()),
  11529. name.size() + 1u);
  11530. }
  11531. /*!
  11532. @brief Writes a BSON element with key @a name and boolean value @a value
  11533. */
  11534. void write_bson_boolean(const string_t& name,
  11535. const bool value)
  11536. {
  11537. write_bson_entry_header(name, 0x08);
  11538. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  11539. }
  11540. /*!
  11541. @brief Writes a BSON element with key @a name and double value @a value
  11542. */
  11543. void write_bson_double(const string_t& name,
  11544. const double value)
  11545. {
  11546. write_bson_entry_header(name, 0x01);
  11547. write_number<double, true>(value);
  11548. }
  11549. /*!
  11550. @return The size of the BSON-encoded string in @a value
  11551. */
  11552. static std::size_t calc_bson_string_size(const string_t& value)
  11553. {
  11554. return sizeof(std::int32_t) + value.size() + 1ul;
  11555. }
  11556. /*!
  11557. @brief Writes a BSON element with key @a name and string value @a value
  11558. */
  11559. void write_bson_string(const string_t& name,
  11560. const string_t& value)
  11561. {
  11562. write_bson_entry_header(name, 0x02);
  11563. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  11564. oa->write_characters(
  11565. reinterpret_cast<const CharType*>(value.c_str()),
  11566. value.size() + 1);
  11567. }
  11568. /*!
  11569. @brief Writes a BSON element with key @a name and null value
  11570. */
  11571. void write_bson_null(const string_t& name)
  11572. {
  11573. write_bson_entry_header(name, 0x0A);
  11574. }
  11575. /*!
  11576. @return The size of the BSON-encoded integer @a value
  11577. */
  11578. static std::size_t calc_bson_integer_size(const std::int64_t value)
  11579. {
  11580. return (std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)()
  11581. ? sizeof(std::int32_t)
  11582. : sizeof(std::int64_t);
  11583. }
  11584. /*!
  11585. @brief Writes a BSON element with key @a name and integer @a value
  11586. */
  11587. void write_bson_integer(const string_t& name,
  11588. const std::int64_t value)
  11589. {
  11590. if ((std::numeric_limits<std::int32_t>::min)() <= value && value <= (std::numeric_limits<std::int32_t>::max)())
  11591. {
  11592. write_bson_entry_header(name, 0x10); // int32
  11593. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11594. }
  11595. else
  11596. {
  11597. write_bson_entry_header(name, 0x12); // int64
  11598. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11599. }
  11600. }
  11601. /*!
  11602. @return The size of the BSON-encoded unsigned integer in @a j
  11603. */
  11604. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  11605. {
  11606. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11607. ? sizeof(std::int32_t)
  11608. : sizeof(std::int64_t);
  11609. }
  11610. /*!
  11611. @brief Writes a BSON element with key @a name and unsigned @a value
  11612. */
  11613. void write_bson_unsigned(const string_t& name,
  11614. const std::uint64_t value)
  11615. {
  11616. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11617. {
  11618. write_bson_entry_header(name, 0x10 /* int32 */);
  11619. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  11620. }
  11621. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11622. {
  11623. write_bson_entry_header(name, 0x12 /* int64 */);
  11624. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  11625. }
  11626. else
  11627. {
  11628. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  11629. }
  11630. }
  11631. /*!
  11632. @brief Writes a BSON element with key @a name and object @a value
  11633. */
  11634. void write_bson_object_entry(const string_t& name,
  11635. const typename BasicJsonType::object_t& value)
  11636. {
  11637. write_bson_entry_header(name, 0x03); // object
  11638. write_bson_object(value);
  11639. }
  11640. /*!
  11641. @return The size of the BSON-encoded array @a value
  11642. */
  11643. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  11644. {
  11645. std::size_t array_index = 0ul;
  11646. const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el)
  11647. {
  11648. return result + calc_bson_element_size(std::to_string(array_index++), el);
  11649. });
  11650. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  11651. }
  11652. /*!
  11653. @return The size of the BSON-encoded binary array @a value
  11654. */
  11655. static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value)
  11656. {
  11657. return sizeof(std::int32_t) + value.size() + 1ul;
  11658. }
  11659. /*!
  11660. @brief Writes a BSON element with key @a name and array @a value
  11661. */
  11662. void write_bson_array(const string_t& name,
  11663. const typename BasicJsonType::array_t& value)
  11664. {
  11665. write_bson_entry_header(name, 0x04); // array
  11666. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  11667. std::size_t array_index = 0ul;
  11668. for (const auto& el : value)
  11669. {
  11670. write_bson_element(std::to_string(array_index++), el);
  11671. }
  11672. oa->write_character(to_char_type(0x00));
  11673. }
  11674. /*!
  11675. @brief Writes a BSON element with key @a name and binary value @a value
  11676. */
  11677. void write_bson_binary(const string_t& name,
  11678. const binary_t& value)
  11679. {
  11680. write_bson_entry_header(name, 0x05);
  11681. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size()));
  11682. write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00));
  11683. oa->write_characters(reinterpret_cast<const CharType*>(value.data()), value.size());
  11684. }
  11685. /*!
  11686. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  11687. @return The calculated size for the BSON document entry for @a j with the given @a name.
  11688. */
  11689. static std::size_t calc_bson_element_size(const string_t& name,
  11690. const BasicJsonType& j)
  11691. {
  11692. const auto header_size = calc_bson_entry_header_size(name);
  11693. switch (j.type())
  11694. {
  11695. case value_t::object:
  11696. return header_size + calc_bson_object_size(*j.m_value.object);
  11697. case value_t::array:
  11698. return header_size + calc_bson_array_size(*j.m_value.array);
  11699. case value_t::binary:
  11700. return header_size + calc_bson_binary_size(*j.m_value.binary);
  11701. case value_t::boolean:
  11702. return header_size + 1ul;
  11703. case value_t::number_float:
  11704. return header_size + 8ul;
  11705. case value_t::number_integer:
  11706. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  11707. case value_t::number_unsigned:
  11708. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  11709. case value_t::string:
  11710. return header_size + calc_bson_string_size(*j.m_value.string);
  11711. case value_t::null:
  11712. return header_size + 0ul;
  11713. // LCOV_EXCL_START
  11714. default:
  11715. JSON_ASSERT(false);
  11716. return 0ul;
  11717. // LCOV_EXCL_STOP
  11718. }
  11719. }
  11720. /*!
  11721. @brief Serializes the JSON value @a j to BSON and associates it with the
  11722. key @a name.
  11723. @param name The name to associate with the JSON entity @a j within the
  11724. current BSON document
  11725. @return The size of the BSON entry
  11726. */
  11727. void write_bson_element(const string_t& name,
  11728. const BasicJsonType& j)
  11729. {
  11730. switch (j.type())
  11731. {
  11732. case value_t::object:
  11733. return write_bson_object_entry(name, *j.m_value.object);
  11734. case value_t::array:
  11735. return write_bson_array(name, *j.m_value.array);
  11736. case value_t::binary:
  11737. return write_bson_binary(name, *j.m_value.binary);
  11738. case value_t::boolean:
  11739. return write_bson_boolean(name, j.m_value.boolean);
  11740. case value_t::number_float:
  11741. return write_bson_double(name, j.m_value.number_float);
  11742. case value_t::number_integer:
  11743. return write_bson_integer(name, j.m_value.number_integer);
  11744. case value_t::number_unsigned:
  11745. return write_bson_unsigned(name, j.m_value.number_unsigned);
  11746. case value_t::string:
  11747. return write_bson_string(name, *j.m_value.string);
  11748. case value_t::null:
  11749. return write_bson_null(name);
  11750. // LCOV_EXCL_START
  11751. default:
  11752. JSON_ASSERT(false);
  11753. return;
  11754. // LCOV_EXCL_STOP
  11755. }
  11756. }
  11757. /*!
  11758. @brief Calculates the size of the BSON serialization of the given
  11759. JSON-object @a j.
  11760. @param[in] j JSON value to serialize
  11761. @pre j.type() == value_t::object
  11762. */
  11763. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  11764. {
  11765. std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0),
  11766. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  11767. {
  11768. return result += calc_bson_element_size(el.first, el.second);
  11769. });
  11770. return sizeof(std::int32_t) + document_size + 1ul;
  11771. }
  11772. /*!
  11773. @param[in] j JSON value to serialize
  11774. @pre j.type() == value_t::object
  11775. */
  11776. void write_bson_object(const typename BasicJsonType::object_t& value)
  11777. {
  11778. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  11779. for (const auto& el : value)
  11780. {
  11781. write_bson_element(el.first, el.second);
  11782. }
  11783. oa->write_character(to_char_type(0x00));
  11784. }
  11785. //////////
  11786. // CBOR //
  11787. //////////
  11788. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  11789. {
  11790. return to_char_type(0xFA); // Single-Precision Float
  11791. }
  11792. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  11793. {
  11794. return to_char_type(0xFB); // Double-Precision Float
  11795. }
  11796. /////////////
  11797. // MsgPack //
  11798. /////////////
  11799. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  11800. {
  11801. return to_char_type(0xCA); // float 32
  11802. }
  11803. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  11804. {
  11805. return to_char_type(0xCB); // float 64
  11806. }
  11807. ////////////
  11808. // UBJSON //
  11809. ////////////
  11810. // UBJSON: write number (floating point)
  11811. template<typename NumberType, typename std::enable_if<
  11812. std::is_floating_point<NumberType>::value, int>::type = 0>
  11813. void write_number_with_ubjson_prefix(const NumberType n,
  11814. const bool add_prefix)
  11815. {
  11816. if (add_prefix)
  11817. {
  11818. oa->write_character(get_ubjson_float_prefix(n));
  11819. }
  11820. write_number(n);
  11821. }
  11822. // UBJSON: write number (unsigned integer)
  11823. template<typename NumberType, typename std::enable_if<
  11824. std::is_unsigned<NumberType>::value, int>::type = 0>
  11825. void write_number_with_ubjson_prefix(const NumberType n,
  11826. const bool add_prefix)
  11827. {
  11828. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11829. {
  11830. if (add_prefix)
  11831. {
  11832. oa->write_character(to_char_type('i')); // int8
  11833. }
  11834. write_number(static_cast<std::uint8_t>(n));
  11835. }
  11836. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  11837. {
  11838. if (add_prefix)
  11839. {
  11840. oa->write_character(to_char_type('U')); // uint8
  11841. }
  11842. write_number(static_cast<std::uint8_t>(n));
  11843. }
  11844. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11845. {
  11846. if (add_prefix)
  11847. {
  11848. oa->write_character(to_char_type('I')); // int16
  11849. }
  11850. write_number(static_cast<std::int16_t>(n));
  11851. }
  11852. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11853. {
  11854. if (add_prefix)
  11855. {
  11856. oa->write_character(to_char_type('l')); // int32
  11857. }
  11858. write_number(static_cast<std::int32_t>(n));
  11859. }
  11860. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  11861. {
  11862. if (add_prefix)
  11863. {
  11864. oa->write_character(to_char_type('L')); // int64
  11865. }
  11866. write_number(static_cast<std::int64_t>(n));
  11867. }
  11868. else
  11869. {
  11870. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11871. }
  11872. }
  11873. // UBJSON: write number (signed integer)
  11874. template < typename NumberType, typename std::enable_if <
  11875. std::is_signed<NumberType>::value&&
  11876. !std::is_floating_point<NumberType>::value, int >::type = 0 >
  11877. void write_number_with_ubjson_prefix(const NumberType n,
  11878. const bool add_prefix)
  11879. {
  11880. if ((std::numeric_limits<std::int8_t>::min)() <= n && n <= (std::numeric_limits<std::int8_t>::max)())
  11881. {
  11882. if (add_prefix)
  11883. {
  11884. oa->write_character(to_char_type('i')); // int8
  11885. }
  11886. write_number(static_cast<std::int8_t>(n));
  11887. }
  11888. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n && n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  11889. {
  11890. if (add_prefix)
  11891. {
  11892. oa->write_character(to_char_type('U')); // uint8
  11893. }
  11894. write_number(static_cast<std::uint8_t>(n));
  11895. }
  11896. else if ((std::numeric_limits<std::int16_t>::min)() <= n && n <= (std::numeric_limits<std::int16_t>::max)())
  11897. {
  11898. if (add_prefix)
  11899. {
  11900. oa->write_character(to_char_type('I')); // int16
  11901. }
  11902. write_number(static_cast<std::int16_t>(n));
  11903. }
  11904. else if ((std::numeric_limits<std::int32_t>::min)() <= n && n <= (std::numeric_limits<std::int32_t>::max)())
  11905. {
  11906. if (add_prefix)
  11907. {
  11908. oa->write_character(to_char_type('l')); // int32
  11909. }
  11910. write_number(static_cast<std::int32_t>(n));
  11911. }
  11912. else if ((std::numeric_limits<std::int64_t>::min)() <= n && n <= (std::numeric_limits<std::int64_t>::max)())
  11913. {
  11914. if (add_prefix)
  11915. {
  11916. oa->write_character(to_char_type('L')); // int64
  11917. }
  11918. write_number(static_cast<std::int64_t>(n));
  11919. }
  11920. // LCOV_EXCL_START
  11921. else
  11922. {
  11923. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  11924. }
  11925. // LCOV_EXCL_STOP
  11926. }
  11927. /*!
  11928. @brief determine the type prefix of container values
  11929. @note This function does not need to be 100% accurate when it comes to
  11930. integer limits. In case a number exceeds the limits of int64_t,
  11931. this will be detected by a later call to function
  11932. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  11933. value that does not fit the previous limits.
  11934. */
  11935. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  11936. {
  11937. switch (j.type())
  11938. {
  11939. case value_t::null:
  11940. return 'Z';
  11941. case value_t::boolean:
  11942. return j.m_value.boolean ? 'T' : 'F';
  11943. case value_t::number_integer:
  11944. {
  11945. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  11946. {
  11947. return 'i';
  11948. }
  11949. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  11950. {
  11951. return 'U';
  11952. }
  11953. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  11954. {
  11955. return 'I';
  11956. }
  11957. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  11958. {
  11959. return 'l';
  11960. }
  11961. // no check and assume int64_t (see note above)
  11962. return 'L';
  11963. }
  11964. case value_t::number_unsigned:
  11965. {
  11966. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  11967. {
  11968. return 'i';
  11969. }
  11970. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::uint8_t>::max)()))
  11971. {
  11972. return 'U';
  11973. }
  11974. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  11975. {
  11976. return 'I';
  11977. }
  11978. if (j.m_value.number_unsigned <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  11979. {
  11980. return 'l';
  11981. }
  11982. // no check and assume int64_t (see note above)
  11983. return 'L';
  11984. }
  11985. case value_t::number_float:
  11986. return get_ubjson_float_prefix(j.m_value.number_float);
  11987. case value_t::string:
  11988. return 'S';
  11989. case value_t::array: // fallthrough
  11990. case value_t::binary:
  11991. return '[';
  11992. case value_t::object:
  11993. return '{';
  11994. default: // discarded values
  11995. return 'N';
  11996. }
  11997. }
  11998. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  11999. {
  12000. return 'd'; // float 32
  12001. }
  12002. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  12003. {
  12004. return 'D'; // float 64
  12005. }
  12006. ///////////////////////
  12007. // Utility functions //
  12008. ///////////////////////
  12009. /*
  12010. @brief write a number to output input
  12011. @param[in] n number of type @a NumberType
  12012. @tparam NumberType the type of the number
  12013. @tparam OutputIsLittleEndian Set to true if output data is
  12014. required to be little endian
  12015. @note This function needs to respect the system's endianess, because bytes
  12016. in CBOR, MessagePack, and UBJSON are stored in network order (big
  12017. endian) and therefore need reordering on little endian systems.
  12018. */
  12019. template<typename NumberType, bool OutputIsLittleEndian = false>
  12020. void write_number(const NumberType n)
  12021. {
  12022. // step 1: write number to array of length NumberType
  12023. std::array<CharType, sizeof(NumberType)> vec;
  12024. std::memcpy(vec.data(), &n, sizeof(NumberType));
  12025. // step 2: write array to output (with possible reordering)
  12026. if (is_little_endian != OutputIsLittleEndian)
  12027. {
  12028. // reverse byte order prior to conversion if necessary
  12029. std::reverse(vec.begin(), vec.end());
  12030. }
  12031. oa->write_characters(vec.data(), sizeof(NumberType));
  12032. }
  12033. void write_compact_float(const number_float_t n, detail::input_format_t format)
  12034. {
  12035. if (static_cast<double>(n) >= static_cast<double>(std::numeric_limits<float>::lowest()) &&
  12036. static_cast<double>(n) <= static_cast<double>((std::numeric_limits<float>::max)()) &&
  12037. static_cast<double>(static_cast<float>(n)) == static_cast<double>(n))
  12038. {
  12039. oa->write_character(format == detail::input_format_t::cbor
  12040. ? get_cbor_float_prefix(static_cast<float>(n))
  12041. : get_msgpack_float_prefix(static_cast<float>(n)));
  12042. write_number(static_cast<float>(n));
  12043. }
  12044. else
  12045. {
  12046. oa->write_character(format == detail::input_format_t::cbor
  12047. ? get_cbor_float_prefix(n)
  12048. : get_msgpack_float_prefix(n));
  12049. write_number(n);
  12050. }
  12051. }
  12052. public:
  12053. // The following to_char_type functions are implement the conversion
  12054. // between uint8_t and CharType. In case CharType is not unsigned,
  12055. // such a conversion is required to allow values greater than 128.
  12056. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  12057. template < typename C = CharType,
  12058. enable_if_t < std::is_signed<C>::value && std::is_signed<char>::value > * = nullptr >
  12059. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  12060. {
  12061. return *reinterpret_cast<char*>(&x);
  12062. }
  12063. template < typename C = CharType,
  12064. enable_if_t < std::is_signed<C>::value && std::is_unsigned<char>::value > * = nullptr >
  12065. static CharType to_char_type(std::uint8_t x) noexcept
  12066. {
  12067. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  12068. static_assert(std::is_trivial<CharType>::value, "CharType must be trivial");
  12069. CharType result;
  12070. std::memcpy(&result, &x, sizeof(x));
  12071. return result;
  12072. }
  12073. template<typename C = CharType,
  12074. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  12075. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  12076. {
  12077. return x;
  12078. }
  12079. template < typename InputCharType, typename C = CharType,
  12080. enable_if_t <
  12081. std::is_signed<C>::value &&
  12082. std::is_signed<char>::value &&
  12083. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  12084. > * = nullptr >
  12085. static constexpr CharType to_char_type(InputCharType x) noexcept
  12086. {
  12087. return x;
  12088. }
  12089. private:
  12090. /// whether we can assume little endianess
  12091. const bool is_little_endian = little_endianess();
  12092. /// the output
  12093. output_adapter_t<CharType> oa = nullptr;
  12094. };
  12095. } // namespace detail
  12096. } // namespace nlohmann
  12097. // #include <nlohmann/detail/output/output_adapters.hpp>
  12098. // #include <nlohmann/detail/output/serializer.hpp>
  12099. #include <algorithm> // reverse, remove, fill, find, none_of
  12100. #include <array> // array
  12101. #include <clocale> // localeconv, lconv
  12102. #include <cmath> // labs, isfinite, isnan, signbit
  12103. #include <cstddef> // size_t, ptrdiff_t
  12104. #include <cstdint> // uint8_t
  12105. #include <cstdio> // snprintf
  12106. #include <limits> // numeric_limits
  12107. #include <string> // string, char_traits
  12108. #include <type_traits> // is_same
  12109. #include <utility> // move
  12110. // #include <nlohmann/detail/conversions/to_chars.hpp>
  12111. #include <array> // array
  12112. #include <cmath> // signbit, isfinite
  12113. #include <cstdint> // intN_t, uintN_t
  12114. #include <cstring> // memcpy, memmove
  12115. #include <limits> // numeric_limits
  12116. #include <type_traits> // conditional
  12117. // #include <nlohmann/detail/macro_scope.hpp>
  12118. namespace nlohmann
  12119. {
  12120. namespace detail
  12121. {
  12122. /*!
  12123. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  12124. conversion.
  12125. This implementation is a slightly modified version of the reference
  12126. implementation which may be obtained from
  12127. http://florian.loitsch.com/publications (bench.tar.gz).
  12128. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  12129. For a detailed description of the algorithm see:
  12130. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  12131. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  12132. Language Design and Implementation, PLDI 2010
  12133. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  12134. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  12135. Design and Implementation, PLDI 1996
  12136. */
  12137. namespace dtoa_impl
  12138. {
  12139. template<typename Target, typename Source>
  12140. Target reinterpret_bits(const Source source)
  12141. {
  12142. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  12143. Target target;
  12144. std::memcpy(&target, &source, sizeof(Source));
  12145. return target;
  12146. }
  12147. struct diyfp // f * 2^e
  12148. {
  12149. static constexpr int kPrecision = 64; // = q
  12150. std::uint64_t f = 0;
  12151. int e = 0;
  12152. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  12153. /*!
  12154. @brief returns x - y
  12155. @pre x.e == y.e and x.f >= y.f
  12156. */
  12157. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  12158. {
  12159. JSON_ASSERT(x.e == y.e);
  12160. JSON_ASSERT(x.f >= y.f);
  12161. return {x.f - y.f, x.e};
  12162. }
  12163. /*!
  12164. @brief returns x * y
  12165. @note The result is rounded. (Only the upper q bits are returned.)
  12166. */
  12167. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  12168. {
  12169. static_assert(kPrecision == 64, "internal error");
  12170. // Computes:
  12171. // f = round((x.f * y.f) / 2^q)
  12172. // e = x.e + y.e + q
  12173. // Emulate the 64-bit * 64-bit multiplication:
  12174. //
  12175. // p = u * v
  12176. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  12177. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  12178. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  12179. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  12180. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  12181. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  12182. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  12183. //
  12184. // (Since Q might be larger than 2^32 - 1)
  12185. //
  12186. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  12187. //
  12188. // (Q_hi + H does not overflow a 64-bit int)
  12189. //
  12190. // = p_lo + 2^64 p_hi
  12191. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  12192. const std::uint64_t u_hi = x.f >> 32u;
  12193. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  12194. const std::uint64_t v_hi = y.f >> 32u;
  12195. const std::uint64_t p0 = u_lo * v_lo;
  12196. const std::uint64_t p1 = u_lo * v_hi;
  12197. const std::uint64_t p2 = u_hi * v_lo;
  12198. const std::uint64_t p3 = u_hi * v_hi;
  12199. const std::uint64_t p0_hi = p0 >> 32u;
  12200. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  12201. const std::uint64_t p1_hi = p1 >> 32u;
  12202. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  12203. const std::uint64_t p2_hi = p2 >> 32u;
  12204. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  12205. // The full product might now be computed as
  12206. //
  12207. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  12208. // p_lo = p0_lo + (Q << 32)
  12209. //
  12210. // But in this particular case here, the full p_lo is not required.
  12211. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  12212. // Q_hi + 1 does not overflow).
  12213. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  12214. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  12215. return {h, x.e + y.e + 64};
  12216. }
  12217. /*!
  12218. @brief normalize x such that the significand is >= 2^(q-1)
  12219. @pre x.f != 0
  12220. */
  12221. static diyfp normalize(diyfp x) noexcept
  12222. {
  12223. JSON_ASSERT(x.f != 0);
  12224. while ((x.f >> 63u) == 0)
  12225. {
  12226. x.f <<= 1u;
  12227. x.e--;
  12228. }
  12229. return x;
  12230. }
  12231. /*!
  12232. @brief normalize x such that the result has the exponent E
  12233. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  12234. */
  12235. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  12236. {
  12237. const int delta = x.e - target_exponent;
  12238. JSON_ASSERT(delta >= 0);
  12239. JSON_ASSERT(((x.f << delta) >> delta) == x.f);
  12240. return {x.f << delta, target_exponent};
  12241. }
  12242. };
  12243. struct boundaries
  12244. {
  12245. diyfp w;
  12246. diyfp minus;
  12247. diyfp plus;
  12248. };
  12249. /*!
  12250. Compute the (normalized) diyfp representing the input number 'value' and its
  12251. boundaries.
  12252. @pre value must be finite and positive
  12253. */
  12254. template<typename FloatType>
  12255. boundaries compute_boundaries(FloatType value)
  12256. {
  12257. JSON_ASSERT(std::isfinite(value));
  12258. JSON_ASSERT(value > 0);
  12259. // Convert the IEEE representation into a diyfp.
  12260. //
  12261. // If v is denormal:
  12262. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  12263. // If v is normalized:
  12264. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  12265. static_assert(std::numeric_limits<FloatType>::is_iec559,
  12266. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  12267. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  12268. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  12269. constexpr int kMinExp = 1 - kBias;
  12270. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  12271. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  12272. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  12273. const std::uint64_t E = bits >> (kPrecision - 1);
  12274. const std::uint64_t F = bits & (kHiddenBit - 1);
  12275. const bool is_denormal = E == 0;
  12276. const diyfp v = is_denormal
  12277. ? diyfp(F, kMinExp)
  12278. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  12279. // Compute the boundaries m- and m+ of the floating-point value
  12280. // v = f * 2^e.
  12281. //
  12282. // Determine v- and v+, the floating-point predecessor and successor if v,
  12283. // respectively.
  12284. //
  12285. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  12286. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  12287. //
  12288. // v+ = v + 2^e
  12289. //
  12290. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  12291. // between m- and m+ round to v, regardless of how the input rounding
  12292. // algorithm breaks ties.
  12293. //
  12294. // ---+-------------+-------------+-------------+-------------+--- (A)
  12295. // v- m- v m+ v+
  12296. //
  12297. // -----------------+------+------+-------------+-------------+--- (B)
  12298. // v- m- v m+ v+
  12299. const bool lower_boundary_is_closer = F == 0 && E > 1;
  12300. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  12301. const diyfp m_minus = lower_boundary_is_closer
  12302. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  12303. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  12304. // Determine the normalized w+ = m+.
  12305. const diyfp w_plus = diyfp::normalize(m_plus);
  12306. // Determine w- = m- such that e_(w-) = e_(w+).
  12307. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  12308. return {diyfp::normalize(v), w_minus, w_plus};
  12309. }
  12310. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  12311. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  12312. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  12313. //
  12314. // alpha <= e = e_c + e_w + q <= gamma
  12315. //
  12316. // or
  12317. //
  12318. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  12319. // <= f_c * f_w * 2^gamma
  12320. //
  12321. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  12322. //
  12323. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  12324. //
  12325. // or
  12326. //
  12327. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  12328. //
  12329. // The choice of (alpha,gamma) determines the size of the table and the form of
  12330. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  12331. // in practice:
  12332. //
  12333. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  12334. // processed independently: An integral part p1, and a fractional part p2:
  12335. //
  12336. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  12337. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  12338. // = p1 + p2 * 2^e
  12339. //
  12340. // The conversion of p1 into decimal form requires a series of divisions and
  12341. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  12342. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  12343. // achieved by choosing
  12344. //
  12345. // -e >= 32 or e <= -32 := gamma
  12346. //
  12347. // In order to convert the fractional part
  12348. //
  12349. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12350. //
  12351. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  12352. // d[-i] are extracted in order:
  12353. //
  12354. // (10 * p2) div 2^-e = d[-1]
  12355. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  12356. //
  12357. // The multiplication by 10 must not overflow. It is sufficient to choose
  12358. //
  12359. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  12360. //
  12361. // Since p2 = f mod 2^-e < 2^-e,
  12362. //
  12363. // -e <= 60 or e >= -60 := alpha
  12364. constexpr int kAlpha = -60;
  12365. constexpr int kGamma = -32;
  12366. struct cached_power // c = f * 2^e ~= 10^k
  12367. {
  12368. std::uint64_t f;
  12369. int e;
  12370. int k;
  12371. };
  12372. /*!
  12373. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  12374. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  12375. satisfies (Definition 3.2 from [1])
  12376. alpha <= e_c + e + q <= gamma.
  12377. */
  12378. inline cached_power get_cached_power_for_binary_exponent(int e)
  12379. {
  12380. // Now
  12381. //
  12382. // alpha <= e_c + e + q <= gamma (1)
  12383. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  12384. //
  12385. // and since the c's are normalized, 2^(q-1) <= f_c,
  12386. //
  12387. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  12388. // ==> 2^(alpha - e - 1) <= c
  12389. //
  12390. // If c were an exact power of ten, i.e. c = 10^k, one may determine k as
  12391. //
  12392. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  12393. // = ceil( (alpha - e - 1) * log_10(2) )
  12394. //
  12395. // From the paper:
  12396. // "In theory the result of the procedure could be wrong since c is rounded,
  12397. // and the computation itself is approximated [...]. In practice, however,
  12398. // this simple function is sufficient."
  12399. //
  12400. // For IEEE double precision floating-point numbers converted into
  12401. // normalized diyfp's w = f * 2^e, with q = 64,
  12402. //
  12403. // e >= -1022 (min IEEE exponent)
  12404. // -52 (p - 1)
  12405. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  12406. // -11 (normalize the diyfp)
  12407. // = -1137
  12408. //
  12409. // and
  12410. //
  12411. // e <= +1023 (max IEEE exponent)
  12412. // -52 (p - 1)
  12413. // -11 (normalize the diyfp)
  12414. // = 960
  12415. //
  12416. // This binary exponent range [-1137,960] results in a decimal exponent
  12417. // range [-307,324]. One does not need to store a cached power for each
  12418. // k in this range. For each such k it suffices to find a cached power
  12419. // such that the exponent of the product lies in [alpha,gamma].
  12420. // This implies that the difference of the decimal exponents of adjacent
  12421. // table entries must be less than or equal to
  12422. //
  12423. // floor( (gamma - alpha) * log_10(2) ) = 8.
  12424. //
  12425. // (A smaller distance gamma-alpha would require a larger table.)
  12426. // NB:
  12427. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  12428. constexpr int kCachedPowersMinDecExp = -300;
  12429. constexpr int kCachedPowersDecStep = 8;
  12430. static constexpr std::array<cached_power, 79> kCachedPowers =
  12431. {
  12432. {
  12433. { 0xAB70FE17C79AC6CA, -1060, -300 },
  12434. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  12435. { 0xBE5691EF416BD60C, -1007, -284 },
  12436. { 0x8DD01FAD907FFC3C, -980, -276 },
  12437. { 0xD3515C2831559A83, -954, -268 },
  12438. { 0x9D71AC8FADA6C9B5, -927, -260 },
  12439. { 0xEA9C227723EE8BCB, -901, -252 },
  12440. { 0xAECC49914078536D, -874, -244 },
  12441. { 0x823C12795DB6CE57, -847, -236 },
  12442. { 0xC21094364DFB5637, -821, -228 },
  12443. { 0x9096EA6F3848984F, -794, -220 },
  12444. { 0xD77485CB25823AC7, -768, -212 },
  12445. { 0xA086CFCD97BF97F4, -741, -204 },
  12446. { 0xEF340A98172AACE5, -715, -196 },
  12447. { 0xB23867FB2A35B28E, -688, -188 },
  12448. { 0x84C8D4DFD2C63F3B, -661, -180 },
  12449. { 0xC5DD44271AD3CDBA, -635, -172 },
  12450. { 0x936B9FCEBB25C996, -608, -164 },
  12451. { 0xDBAC6C247D62A584, -582, -156 },
  12452. { 0xA3AB66580D5FDAF6, -555, -148 },
  12453. { 0xF3E2F893DEC3F126, -529, -140 },
  12454. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  12455. { 0x87625F056C7C4A8B, -475, -124 },
  12456. { 0xC9BCFF6034C13053, -449, -116 },
  12457. { 0x964E858C91BA2655, -422, -108 },
  12458. { 0xDFF9772470297EBD, -396, -100 },
  12459. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  12460. { 0xF8A95FCF88747D94, -343, -84 },
  12461. { 0xB94470938FA89BCF, -316, -76 },
  12462. { 0x8A08F0F8BF0F156B, -289, -68 },
  12463. { 0xCDB02555653131B6, -263, -60 },
  12464. { 0x993FE2C6D07B7FAC, -236, -52 },
  12465. { 0xE45C10C42A2B3B06, -210, -44 },
  12466. { 0xAA242499697392D3, -183, -36 },
  12467. { 0xFD87B5F28300CA0E, -157, -28 },
  12468. { 0xBCE5086492111AEB, -130, -20 },
  12469. { 0x8CBCCC096F5088CC, -103, -12 },
  12470. { 0xD1B71758E219652C, -77, -4 },
  12471. { 0x9C40000000000000, -50, 4 },
  12472. { 0xE8D4A51000000000, -24, 12 },
  12473. { 0xAD78EBC5AC620000, 3, 20 },
  12474. { 0x813F3978F8940984, 30, 28 },
  12475. { 0xC097CE7BC90715B3, 56, 36 },
  12476. { 0x8F7E32CE7BEA5C70, 83, 44 },
  12477. { 0xD5D238A4ABE98068, 109, 52 },
  12478. { 0x9F4F2726179A2245, 136, 60 },
  12479. { 0xED63A231D4C4FB27, 162, 68 },
  12480. { 0xB0DE65388CC8ADA8, 189, 76 },
  12481. { 0x83C7088E1AAB65DB, 216, 84 },
  12482. { 0xC45D1DF942711D9A, 242, 92 },
  12483. { 0x924D692CA61BE758, 269, 100 },
  12484. { 0xDA01EE641A708DEA, 295, 108 },
  12485. { 0xA26DA3999AEF774A, 322, 116 },
  12486. { 0xF209787BB47D6B85, 348, 124 },
  12487. { 0xB454E4A179DD1877, 375, 132 },
  12488. { 0x865B86925B9BC5C2, 402, 140 },
  12489. { 0xC83553C5C8965D3D, 428, 148 },
  12490. { 0x952AB45CFA97A0B3, 455, 156 },
  12491. { 0xDE469FBD99A05FE3, 481, 164 },
  12492. { 0xA59BC234DB398C25, 508, 172 },
  12493. { 0xF6C69A72A3989F5C, 534, 180 },
  12494. { 0xB7DCBF5354E9BECE, 561, 188 },
  12495. { 0x88FCF317F22241E2, 588, 196 },
  12496. { 0xCC20CE9BD35C78A5, 614, 204 },
  12497. { 0x98165AF37B2153DF, 641, 212 },
  12498. { 0xE2A0B5DC971F303A, 667, 220 },
  12499. { 0xA8D9D1535CE3B396, 694, 228 },
  12500. { 0xFB9B7CD9A4A7443C, 720, 236 },
  12501. { 0xBB764C4CA7A44410, 747, 244 },
  12502. { 0x8BAB8EEFB6409C1A, 774, 252 },
  12503. { 0xD01FEF10A657842C, 800, 260 },
  12504. { 0x9B10A4E5E9913129, 827, 268 },
  12505. { 0xE7109BFBA19C0C9D, 853, 276 },
  12506. { 0xAC2820D9623BF429, 880, 284 },
  12507. { 0x80444B5E7AA7CF85, 907, 292 },
  12508. { 0xBF21E44003ACDD2D, 933, 300 },
  12509. { 0x8E679C2F5E44FF8F, 960, 308 },
  12510. { 0xD433179D9C8CB841, 986, 316 },
  12511. { 0x9E19DB92B4E31BA9, 1013, 324 },
  12512. }
  12513. };
  12514. // This computation gives exactly the same results for k as
  12515. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  12516. // for |e| <= 1500, but doesn't require floating-point operations.
  12517. // NB: log_10(2) ~= 78913 / 2^18
  12518. JSON_ASSERT(e >= -1500);
  12519. JSON_ASSERT(e <= 1500);
  12520. const int f = kAlpha - e - 1;
  12521. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  12522. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  12523. JSON_ASSERT(index >= 0);
  12524. JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size());
  12525. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  12526. JSON_ASSERT(kAlpha <= cached.e + e + 64);
  12527. JSON_ASSERT(kGamma >= cached.e + e + 64);
  12528. return cached;
  12529. }
  12530. /*!
  12531. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  12532. For n == 0, returns 1 and sets pow10 := 1.
  12533. */
  12534. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  12535. {
  12536. // LCOV_EXCL_START
  12537. if (n >= 1000000000)
  12538. {
  12539. pow10 = 1000000000;
  12540. return 10;
  12541. }
  12542. // LCOV_EXCL_STOP
  12543. else if (n >= 100000000)
  12544. {
  12545. pow10 = 100000000;
  12546. return 9;
  12547. }
  12548. else if (n >= 10000000)
  12549. {
  12550. pow10 = 10000000;
  12551. return 8;
  12552. }
  12553. else if (n >= 1000000)
  12554. {
  12555. pow10 = 1000000;
  12556. return 7;
  12557. }
  12558. else if (n >= 100000)
  12559. {
  12560. pow10 = 100000;
  12561. return 6;
  12562. }
  12563. else if (n >= 10000)
  12564. {
  12565. pow10 = 10000;
  12566. return 5;
  12567. }
  12568. else if (n >= 1000)
  12569. {
  12570. pow10 = 1000;
  12571. return 4;
  12572. }
  12573. else if (n >= 100)
  12574. {
  12575. pow10 = 100;
  12576. return 3;
  12577. }
  12578. else if (n >= 10)
  12579. {
  12580. pow10 = 10;
  12581. return 2;
  12582. }
  12583. else
  12584. {
  12585. pow10 = 1;
  12586. return 1;
  12587. }
  12588. }
  12589. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  12590. std::uint64_t rest, std::uint64_t ten_k)
  12591. {
  12592. JSON_ASSERT(len >= 1);
  12593. JSON_ASSERT(dist <= delta);
  12594. JSON_ASSERT(rest <= delta);
  12595. JSON_ASSERT(ten_k > 0);
  12596. // <--------------------------- delta ---->
  12597. // <---- dist --------->
  12598. // --------------[------------------+-------------------]--------------
  12599. // M- w M+
  12600. //
  12601. // ten_k
  12602. // <------>
  12603. // <---- rest ---->
  12604. // --------------[------------------+----+--------------]--------------
  12605. // w V
  12606. // = buf * 10^k
  12607. //
  12608. // ten_k represents a unit-in-the-last-place in the decimal representation
  12609. // stored in buf.
  12610. // Decrement buf by ten_k while this takes buf closer to w.
  12611. // The tests are written in this order to avoid overflow in unsigned
  12612. // integer arithmetic.
  12613. while (rest < dist
  12614. && delta - rest >= ten_k
  12615. && (rest + ten_k < dist || dist - rest > rest + ten_k - dist))
  12616. {
  12617. JSON_ASSERT(buf[len - 1] != '0');
  12618. buf[len - 1]--;
  12619. rest += ten_k;
  12620. }
  12621. }
  12622. /*!
  12623. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  12624. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  12625. */
  12626. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  12627. diyfp M_minus, diyfp w, diyfp M_plus)
  12628. {
  12629. static_assert(kAlpha >= -60, "internal error");
  12630. static_assert(kGamma <= -32, "internal error");
  12631. // Generates the digits (and the exponent) of a decimal floating-point
  12632. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  12633. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  12634. //
  12635. // <--------------------------- delta ---->
  12636. // <---- dist --------->
  12637. // --------------[------------------+-------------------]--------------
  12638. // M- w M+
  12639. //
  12640. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  12641. // V is in [M-,M+].
  12642. JSON_ASSERT(M_plus.e >= kAlpha);
  12643. JSON_ASSERT(M_plus.e <= kGamma);
  12644. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  12645. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  12646. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  12647. //
  12648. // M+ = f * 2^e
  12649. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  12650. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  12651. // = p1 + p2 * 2^e
  12652. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  12653. 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.)
  12654. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  12655. // 1)
  12656. //
  12657. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  12658. JSON_ASSERT(p1 > 0);
  12659. std::uint32_t pow10;
  12660. const int k = find_largest_pow10(p1, pow10);
  12661. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  12662. //
  12663. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  12664. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  12665. //
  12666. // M+ = p1 + p2 * 2^e
  12667. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  12668. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  12669. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  12670. //
  12671. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  12672. //
  12673. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  12674. //
  12675. // but stop as soon as
  12676. //
  12677. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  12678. int n = k;
  12679. while (n > 0)
  12680. {
  12681. // Invariants:
  12682. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  12683. // pow10 = 10^(n-1) <= p1 < 10^n
  12684. //
  12685. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  12686. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  12687. //
  12688. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  12689. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  12690. //
  12691. JSON_ASSERT(d <= 9);
  12692. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12693. //
  12694. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  12695. //
  12696. p1 = r;
  12697. n--;
  12698. //
  12699. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  12700. // pow10 = 10^n
  12701. //
  12702. // Now check if enough digits have been generated.
  12703. // Compute
  12704. //
  12705. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  12706. //
  12707. // Note:
  12708. // Since rest and delta share the same exponent e, it suffices to
  12709. // compare the significands.
  12710. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  12711. if (rest <= delta)
  12712. {
  12713. // V = buffer * 10^n, with M- <= V <= M+.
  12714. decimal_exponent += n;
  12715. // We may now just stop. But instead look if the buffer could be
  12716. // decremented to bring V closer to w.
  12717. //
  12718. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  12719. // The rounding procedure works with diyfp's with an implicit
  12720. // exponent of e.
  12721. //
  12722. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  12723. //
  12724. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  12725. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  12726. return;
  12727. }
  12728. pow10 /= 10;
  12729. //
  12730. // pow10 = 10^(n-1) <= p1 < 10^n
  12731. // Invariants restored.
  12732. }
  12733. // 2)
  12734. //
  12735. // The digits of the integral part have been generated:
  12736. //
  12737. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  12738. // = buffer + p2 * 2^e
  12739. //
  12740. // Now generate the digits of the fractional part p2 * 2^e.
  12741. //
  12742. // Note:
  12743. // No decimal point is generated: the exponent is adjusted instead.
  12744. //
  12745. // p2 actually represents the fraction
  12746. //
  12747. // p2 * 2^e
  12748. // = p2 / 2^-e
  12749. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  12750. //
  12751. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  12752. //
  12753. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  12754. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  12755. //
  12756. // using
  12757. //
  12758. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  12759. // = ( d) * 2^-e + ( r)
  12760. //
  12761. // or
  12762. // 10^m * p2 * 2^e = d + r * 2^e
  12763. //
  12764. // i.e.
  12765. //
  12766. // M+ = buffer + p2 * 2^e
  12767. // = buffer + 10^-m * (d + r * 2^e)
  12768. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  12769. //
  12770. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  12771. JSON_ASSERT(p2 > delta);
  12772. int m = 0;
  12773. for (;;)
  12774. {
  12775. // Invariant:
  12776. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  12777. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  12778. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  12779. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  12780. //
  12781. JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  12782. p2 *= 10;
  12783. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  12784. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  12785. //
  12786. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  12787. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  12788. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12789. //
  12790. JSON_ASSERT(d <= 9);
  12791. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  12792. //
  12793. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  12794. //
  12795. p2 = r;
  12796. m++;
  12797. //
  12798. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  12799. // Invariant restored.
  12800. // Check if enough digits have been generated.
  12801. //
  12802. // 10^-m * p2 * 2^e <= delta * 2^e
  12803. // p2 * 2^e <= 10^m * delta * 2^e
  12804. // p2 <= 10^m * delta
  12805. delta *= 10;
  12806. dist *= 10;
  12807. if (p2 <= delta)
  12808. {
  12809. break;
  12810. }
  12811. }
  12812. // V = buffer * 10^-m, with M- <= V <= M+.
  12813. decimal_exponent -= m;
  12814. // 1 ulp in the decimal representation is now 10^-m.
  12815. // Since delta and dist are now scaled by 10^m, we need to do the
  12816. // same with ulp in order to keep the units in sync.
  12817. //
  12818. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  12819. //
  12820. const std::uint64_t ten_m = one.f;
  12821. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  12822. // By construction this algorithm generates the shortest possible decimal
  12823. // number (Loitsch, Theorem 6.2) which rounds back to w.
  12824. // For an input number of precision p, at least
  12825. //
  12826. // N = 1 + ceil(p * log_10(2))
  12827. //
  12828. // decimal digits are sufficient to identify all binary floating-point
  12829. // numbers (Matula, "In-and-Out conversions").
  12830. // This implies that the algorithm does not produce more than N decimal
  12831. // digits.
  12832. //
  12833. // N = 17 for p = 53 (IEEE double precision)
  12834. // N = 9 for p = 24 (IEEE single precision)
  12835. }
  12836. /*!
  12837. v = buf * 10^decimal_exponent
  12838. len is the length of the buffer (number of decimal digits)
  12839. The buffer must be large enough, i.e. >= max_digits10.
  12840. */
  12841. JSON_HEDLEY_NON_NULL(1)
  12842. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  12843. diyfp m_minus, diyfp v, diyfp m_plus)
  12844. {
  12845. JSON_ASSERT(m_plus.e == m_minus.e);
  12846. JSON_ASSERT(m_plus.e == v.e);
  12847. // --------(-----------------------+-----------------------)-------- (A)
  12848. // m- v m+
  12849. //
  12850. // --------------------(-----------+-----------------------)-------- (B)
  12851. // m- v m+
  12852. //
  12853. // First scale v (and m- and m+) such that the exponent is in the range
  12854. // [alpha, gamma].
  12855. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  12856. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  12857. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  12858. const diyfp w = diyfp::mul(v, c_minus_k);
  12859. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  12860. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  12861. // ----(---+---)---------------(---+---)---------------(---+---)----
  12862. // w- w w+
  12863. // = c*m- = c*v = c*m+
  12864. //
  12865. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  12866. // w+ are now off by a small amount.
  12867. // In fact:
  12868. //
  12869. // w - v * 10^k < 1 ulp
  12870. //
  12871. // To account for this inaccuracy, add resp. subtract 1 ulp.
  12872. //
  12873. // --------+---[---------------(---+---)---------------]---+--------
  12874. // w- M- w M+ w+
  12875. //
  12876. // Now any number in [M-, M+] (bounds included) will round to w when input,
  12877. // regardless of how the input rounding algorithm breaks ties.
  12878. //
  12879. // And digit_gen generates the shortest possible such number in [M-, M+].
  12880. // Note that this does not mean that Grisu2 always generates the shortest
  12881. // possible number in the interval (m-, m+).
  12882. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  12883. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  12884. decimal_exponent = -cached.k; // = -(-k) = k
  12885. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  12886. }
  12887. /*!
  12888. v = buf * 10^decimal_exponent
  12889. len is the length of the buffer (number of decimal digits)
  12890. The buffer must be large enough, i.e. >= max_digits10.
  12891. */
  12892. template<typename FloatType>
  12893. JSON_HEDLEY_NON_NULL(1)
  12894. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  12895. {
  12896. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  12897. "internal error: not enough precision");
  12898. JSON_ASSERT(std::isfinite(value));
  12899. JSON_ASSERT(value > 0);
  12900. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  12901. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  12902. // decimal representations are not exactly "short".
  12903. //
  12904. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  12905. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  12906. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  12907. // does.
  12908. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  12909. // representation using the corresponding std::from_chars function recovers value exactly". That
  12910. // indicates that single precision floating-point numbers should be recovered using
  12911. // 'std::strtof'.
  12912. //
  12913. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  12914. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  12915. // value is off by 1 ulp.
  12916. #if 0
  12917. const boundaries w = compute_boundaries(static_cast<double>(value));
  12918. #else
  12919. const boundaries w = compute_boundaries(value);
  12920. #endif
  12921. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  12922. }
  12923. /*!
  12924. @brief appends a decimal representation of e to buf
  12925. @return a pointer to the element following the exponent.
  12926. @pre -1000 < e < 1000
  12927. */
  12928. JSON_HEDLEY_NON_NULL(1)
  12929. JSON_HEDLEY_RETURNS_NON_NULL
  12930. inline char* append_exponent(char* buf, int e)
  12931. {
  12932. JSON_ASSERT(e > -1000);
  12933. JSON_ASSERT(e < 1000);
  12934. if (e < 0)
  12935. {
  12936. e = -e;
  12937. *buf++ = '-';
  12938. }
  12939. else
  12940. {
  12941. *buf++ = '+';
  12942. }
  12943. auto k = static_cast<std::uint32_t>(e);
  12944. if (k < 10)
  12945. {
  12946. // Always print at least two digits in the exponent.
  12947. // This is for compatibility with printf("%g").
  12948. *buf++ = '0';
  12949. *buf++ = static_cast<char>('0' + k);
  12950. }
  12951. else if (k < 100)
  12952. {
  12953. *buf++ = static_cast<char>('0' + k / 10);
  12954. k %= 10;
  12955. *buf++ = static_cast<char>('0' + k);
  12956. }
  12957. else
  12958. {
  12959. *buf++ = static_cast<char>('0' + k / 100);
  12960. k %= 100;
  12961. *buf++ = static_cast<char>('0' + k / 10);
  12962. k %= 10;
  12963. *buf++ = static_cast<char>('0' + k);
  12964. }
  12965. return buf;
  12966. }
  12967. /*!
  12968. @brief prettify v = buf * 10^decimal_exponent
  12969. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  12970. notation. Otherwise it will be printed in exponential notation.
  12971. @pre min_exp < 0
  12972. @pre max_exp > 0
  12973. */
  12974. JSON_HEDLEY_NON_NULL(1)
  12975. JSON_HEDLEY_RETURNS_NON_NULL
  12976. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  12977. int min_exp, int max_exp)
  12978. {
  12979. JSON_ASSERT(min_exp < 0);
  12980. JSON_ASSERT(max_exp > 0);
  12981. const int k = len;
  12982. const int n = len + decimal_exponent;
  12983. // v = buf * 10^(n-k)
  12984. // k is the length of the buffer (number of decimal digits)
  12985. // n is the position of the decimal point relative to the start of the buffer.
  12986. if (k <= n && n <= max_exp)
  12987. {
  12988. // digits[000]
  12989. // len <= max_exp + 2
  12990. std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k));
  12991. // Make it look like a floating-point number (#362, #378)
  12992. buf[n + 0] = '.';
  12993. buf[n + 1] = '0';
  12994. return buf + (static_cast<size_t>(n) + 2);
  12995. }
  12996. if (0 < n && n <= max_exp)
  12997. {
  12998. // dig.its
  12999. // len <= max_digits10 + 1
  13000. JSON_ASSERT(k > n);
  13001. std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n));
  13002. buf[n] = '.';
  13003. return buf + (static_cast<size_t>(k) + 1U);
  13004. }
  13005. if (min_exp < n && n <= 0)
  13006. {
  13007. // 0.[000]digits
  13008. // len <= 2 + (-min_exp - 1) + max_digits10
  13009. std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k));
  13010. buf[0] = '0';
  13011. buf[1] = '.';
  13012. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  13013. return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k));
  13014. }
  13015. if (k == 1)
  13016. {
  13017. // dE+123
  13018. // len <= 1 + 5
  13019. buf += 1;
  13020. }
  13021. else
  13022. {
  13023. // d.igitsE+123
  13024. // len <= max_digits10 + 1 + 5
  13025. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1);
  13026. buf[1] = '.';
  13027. buf += 1 + static_cast<size_t>(k);
  13028. }
  13029. *buf++ = 'e';
  13030. return append_exponent(buf, n - 1);
  13031. }
  13032. } // namespace dtoa_impl
  13033. /*!
  13034. @brief generates a decimal representation of the floating-point number value in [first, last).
  13035. The format of the resulting decimal representation is similar to printf's %g
  13036. format. Returns an iterator pointing past-the-end of the decimal representation.
  13037. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  13038. @note The buffer must be large enough.
  13039. @note The result is NOT null-terminated.
  13040. */
  13041. template<typename FloatType>
  13042. JSON_HEDLEY_NON_NULL(1, 2)
  13043. JSON_HEDLEY_RETURNS_NON_NULL
  13044. char* to_chars(char* first, const char* last, FloatType value)
  13045. {
  13046. static_cast<void>(last); // maybe unused - fix warning
  13047. JSON_ASSERT(std::isfinite(value));
  13048. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  13049. if (std::signbit(value))
  13050. {
  13051. value = -value;
  13052. *first++ = '-';
  13053. }
  13054. if (value == 0) // +-0
  13055. {
  13056. *first++ = '0';
  13057. // Make it look like a floating-point number (#362, #378)
  13058. *first++ = '.';
  13059. *first++ = '0';
  13060. return first;
  13061. }
  13062. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10);
  13063. // Compute v = buffer * 10^decimal_exponent.
  13064. // The decimal digits are stored in the buffer, which needs to be interpreted
  13065. // as an unsigned decimal integer.
  13066. // len is the length of the buffer, i.e. the number of decimal digits.
  13067. int len = 0;
  13068. int decimal_exponent = 0;
  13069. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  13070. JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10);
  13071. // Format the buffer like printf("%.*g", prec, value)
  13072. constexpr int kMinExp = -4;
  13073. // Use digits10 here to increase compatibility with version 2.
  13074. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  13075. JSON_ASSERT(last - first >= kMaxExp + 2);
  13076. JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  13077. JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  13078. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  13079. }
  13080. } // namespace detail
  13081. } // namespace nlohmann
  13082. // #include <nlohmann/detail/exceptions.hpp>
  13083. // #include <nlohmann/detail/macro_scope.hpp>
  13084. // #include <nlohmann/detail/meta/cpp_future.hpp>
  13085. // #include <nlohmann/detail/output/binary_writer.hpp>
  13086. // #include <nlohmann/detail/output/output_adapters.hpp>
  13087. // #include <nlohmann/detail/value_t.hpp>
  13088. namespace nlohmann
  13089. {
  13090. namespace detail
  13091. {
  13092. ///////////////////
  13093. // serialization //
  13094. ///////////////////
  13095. /// how to treat decoding errors
  13096. enum class error_handler_t
  13097. {
  13098. strict, ///< throw a type_error exception in case of invalid UTF-8
  13099. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  13100. ignore ///< ignore invalid UTF-8 sequences
  13101. };
  13102. template<typename BasicJsonType>
  13103. class serializer
  13104. {
  13105. using string_t = typename BasicJsonType::string_t;
  13106. using number_float_t = typename BasicJsonType::number_float_t;
  13107. using number_integer_t = typename BasicJsonType::number_integer_t;
  13108. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  13109. using binary_char_t = typename BasicJsonType::binary_t::value_type;
  13110. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  13111. static constexpr std::uint8_t UTF8_REJECT = 1;
  13112. public:
  13113. /*!
  13114. @param[in] s output stream to serialize to
  13115. @param[in] ichar indentation character to use
  13116. @param[in] error_handler_ how to react on decoding errors
  13117. */
  13118. serializer(output_adapter_t<char> s, const char ichar,
  13119. error_handler_t error_handler_ = error_handler_t::strict)
  13120. : o(std::move(s))
  13121. , loc(std::localeconv())
  13122. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->thousands_sep)))
  13123. , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits<char>::to_char_type(* (loc->decimal_point)))
  13124. , indent_char(ichar)
  13125. , indent_string(512, indent_char)
  13126. , error_handler(error_handler_)
  13127. {}
  13128. // delete because of pointer members
  13129. serializer(const serializer&) = delete;
  13130. serializer& operator=(const serializer&) = delete;
  13131. serializer(serializer&&) = delete;
  13132. serializer& operator=(serializer&&) = delete;
  13133. ~serializer() = default;
  13134. /*!
  13135. @brief internal implementation of the serialization function
  13136. This function is called by the public member function dump and organizes
  13137. the serialization internally. The indentation level is propagated as
  13138. additional parameter. In case of arrays and objects, the function is
  13139. called recursively.
  13140. - strings and object keys are escaped using `escape_string()`
  13141. - integer numbers are converted implicitly via `operator<<`
  13142. - floating-point numbers are converted to a string using `"%g"` format
  13143. - binary values are serialized as objects containing the subtype and the
  13144. byte array
  13145. @param[in] val value to serialize
  13146. @param[in] pretty_print whether the output shall be pretty-printed
  13147. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  13148. in the output are escaped with `\uXXXX` sequences, and the result consists
  13149. of ASCII characters only.
  13150. @param[in] indent_step the indent level
  13151. @param[in] current_indent the current indent level (only used internally)
  13152. */
  13153. void dump(const BasicJsonType& val,
  13154. const bool pretty_print,
  13155. const bool ensure_ascii,
  13156. const unsigned int indent_step,
  13157. const unsigned int current_indent = 0)
  13158. {
  13159. switch (val.m_type)
  13160. {
  13161. case value_t::object:
  13162. {
  13163. if (val.m_value.object->empty())
  13164. {
  13165. o->write_characters("{}", 2);
  13166. return;
  13167. }
  13168. if (pretty_print)
  13169. {
  13170. o->write_characters("{\n", 2);
  13171. // variable to hold indentation for recursive calls
  13172. const auto new_indent = current_indent + indent_step;
  13173. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13174. {
  13175. indent_string.resize(indent_string.size() * 2, ' ');
  13176. }
  13177. // first n-1 elements
  13178. auto i = val.m_value.object->cbegin();
  13179. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13180. {
  13181. o->write_characters(indent_string.c_str(), new_indent);
  13182. o->write_character('\"');
  13183. dump_escaped(i->first, ensure_ascii);
  13184. o->write_characters("\": ", 3);
  13185. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13186. o->write_characters(",\n", 2);
  13187. }
  13188. // last element
  13189. JSON_ASSERT(i != val.m_value.object->cend());
  13190. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  13191. o->write_characters(indent_string.c_str(), new_indent);
  13192. o->write_character('\"');
  13193. dump_escaped(i->first, ensure_ascii);
  13194. o->write_characters("\": ", 3);
  13195. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  13196. o->write_character('\n');
  13197. o->write_characters(indent_string.c_str(), current_indent);
  13198. o->write_character('}');
  13199. }
  13200. else
  13201. {
  13202. o->write_character('{');
  13203. // first n-1 elements
  13204. auto i = val.m_value.object->cbegin();
  13205. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  13206. {
  13207. o->write_character('\"');
  13208. dump_escaped(i->first, ensure_ascii);
  13209. o->write_characters("\":", 2);
  13210. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13211. o->write_character(',');
  13212. }
  13213. // last element
  13214. JSON_ASSERT(i != val.m_value.object->cend());
  13215. JSON_ASSERT(std::next(i) == val.m_value.object->cend());
  13216. o->write_character('\"');
  13217. dump_escaped(i->first, ensure_ascii);
  13218. o->write_characters("\":", 2);
  13219. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  13220. o->write_character('}');
  13221. }
  13222. return;
  13223. }
  13224. case value_t::array:
  13225. {
  13226. if (val.m_value.array->empty())
  13227. {
  13228. o->write_characters("[]", 2);
  13229. return;
  13230. }
  13231. if (pretty_print)
  13232. {
  13233. o->write_characters("[\n", 2);
  13234. // variable to hold indentation for recursive calls
  13235. const auto new_indent = current_indent + indent_step;
  13236. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13237. {
  13238. indent_string.resize(indent_string.size() * 2, ' ');
  13239. }
  13240. // first n-1 elements
  13241. for (auto i = val.m_value.array->cbegin();
  13242. i != val.m_value.array->cend() - 1; ++i)
  13243. {
  13244. o->write_characters(indent_string.c_str(), new_indent);
  13245. dump(*i, true, ensure_ascii, indent_step, new_indent);
  13246. o->write_characters(",\n", 2);
  13247. }
  13248. // last element
  13249. JSON_ASSERT(!val.m_value.array->empty());
  13250. o->write_characters(indent_string.c_str(), new_indent);
  13251. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  13252. o->write_character('\n');
  13253. o->write_characters(indent_string.c_str(), current_indent);
  13254. o->write_character(']');
  13255. }
  13256. else
  13257. {
  13258. o->write_character('[');
  13259. // first n-1 elements
  13260. for (auto i = val.m_value.array->cbegin();
  13261. i != val.m_value.array->cend() - 1; ++i)
  13262. {
  13263. dump(*i, false, ensure_ascii, indent_step, current_indent);
  13264. o->write_character(',');
  13265. }
  13266. // last element
  13267. JSON_ASSERT(!val.m_value.array->empty());
  13268. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  13269. o->write_character(']');
  13270. }
  13271. return;
  13272. }
  13273. case value_t::string:
  13274. {
  13275. o->write_character('\"');
  13276. dump_escaped(*val.m_value.string, ensure_ascii);
  13277. o->write_character('\"');
  13278. return;
  13279. }
  13280. case value_t::binary:
  13281. {
  13282. if (pretty_print)
  13283. {
  13284. o->write_characters("{\n", 2);
  13285. // variable to hold indentation for recursive calls
  13286. const auto new_indent = current_indent + indent_step;
  13287. if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent))
  13288. {
  13289. indent_string.resize(indent_string.size() * 2, ' ');
  13290. }
  13291. o->write_characters(indent_string.c_str(), new_indent);
  13292. o->write_characters("\"bytes\": [", 10);
  13293. if (!val.m_value.binary->empty())
  13294. {
  13295. for (auto i = val.m_value.binary->cbegin();
  13296. i != val.m_value.binary->cend() - 1; ++i)
  13297. {
  13298. dump_integer(*i);
  13299. o->write_characters(", ", 2);
  13300. }
  13301. dump_integer(val.m_value.binary->back());
  13302. }
  13303. o->write_characters("],\n", 3);
  13304. o->write_characters(indent_string.c_str(), new_indent);
  13305. o->write_characters("\"subtype\": ", 11);
  13306. if (val.m_value.binary->has_subtype())
  13307. {
  13308. dump_integer(val.m_value.binary->subtype());
  13309. }
  13310. else
  13311. {
  13312. o->write_characters("null", 4);
  13313. }
  13314. o->write_character('\n');
  13315. o->write_characters(indent_string.c_str(), current_indent);
  13316. o->write_character('}');
  13317. }
  13318. else
  13319. {
  13320. o->write_characters("{\"bytes\":[", 10);
  13321. if (!val.m_value.binary->empty())
  13322. {
  13323. for (auto i = val.m_value.binary->cbegin();
  13324. i != val.m_value.binary->cend() - 1; ++i)
  13325. {
  13326. dump_integer(*i);
  13327. o->write_character(',');
  13328. }
  13329. dump_integer(val.m_value.binary->back());
  13330. }
  13331. o->write_characters("],\"subtype\":", 12);
  13332. if (val.m_value.binary->has_subtype())
  13333. {
  13334. dump_integer(val.m_value.binary->subtype());
  13335. o->write_character('}');
  13336. }
  13337. else
  13338. {
  13339. o->write_characters("null}", 5);
  13340. }
  13341. }
  13342. return;
  13343. }
  13344. case value_t::boolean:
  13345. {
  13346. if (val.m_value.boolean)
  13347. {
  13348. o->write_characters("true", 4);
  13349. }
  13350. else
  13351. {
  13352. o->write_characters("false", 5);
  13353. }
  13354. return;
  13355. }
  13356. case value_t::number_integer:
  13357. {
  13358. dump_integer(val.m_value.number_integer);
  13359. return;
  13360. }
  13361. case value_t::number_unsigned:
  13362. {
  13363. dump_integer(val.m_value.number_unsigned);
  13364. return;
  13365. }
  13366. case value_t::number_float:
  13367. {
  13368. dump_float(val.m_value.number_float);
  13369. return;
  13370. }
  13371. case value_t::discarded:
  13372. {
  13373. o->write_characters("<discarded>", 11);
  13374. return;
  13375. }
  13376. case value_t::null:
  13377. {
  13378. o->write_characters("null", 4);
  13379. return;
  13380. }
  13381. default: // LCOV_EXCL_LINE
  13382. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13383. }
  13384. }
  13385. private:
  13386. /*!
  13387. @brief dump escaped string
  13388. Escape a string by replacing certain special characters by a sequence of an
  13389. escape character (backslash) and another character and other control
  13390. characters by a sequence of "\u" followed by a four-digit hex
  13391. representation. The escaped string is written to output stream @a o.
  13392. @param[in] s the string to escape
  13393. @param[in] ensure_ascii whether to escape non-ASCII characters with
  13394. \uXXXX sequences
  13395. @complexity Linear in the length of string @a s.
  13396. */
  13397. void dump_escaped(const string_t& s, const bool ensure_ascii)
  13398. {
  13399. std::uint32_t codepoint;
  13400. std::uint8_t state = UTF8_ACCEPT;
  13401. std::size_t bytes = 0; // number of bytes written to string_buffer
  13402. // number of bytes written at the point of the last valid byte
  13403. std::size_t bytes_after_last_accept = 0;
  13404. std::size_t undumped_chars = 0;
  13405. for (std::size_t i = 0; i < s.size(); ++i)
  13406. {
  13407. const auto byte = static_cast<uint8_t>(s[i]);
  13408. switch (decode(state, codepoint, byte))
  13409. {
  13410. case UTF8_ACCEPT: // decode found a new code point
  13411. {
  13412. switch (codepoint)
  13413. {
  13414. case 0x08: // backspace
  13415. {
  13416. string_buffer[bytes++] = '\\';
  13417. string_buffer[bytes++] = 'b';
  13418. break;
  13419. }
  13420. case 0x09: // horizontal tab
  13421. {
  13422. string_buffer[bytes++] = '\\';
  13423. string_buffer[bytes++] = 't';
  13424. break;
  13425. }
  13426. case 0x0A: // newline
  13427. {
  13428. string_buffer[bytes++] = '\\';
  13429. string_buffer[bytes++] = 'n';
  13430. break;
  13431. }
  13432. case 0x0C: // formfeed
  13433. {
  13434. string_buffer[bytes++] = '\\';
  13435. string_buffer[bytes++] = 'f';
  13436. break;
  13437. }
  13438. case 0x0D: // carriage return
  13439. {
  13440. string_buffer[bytes++] = '\\';
  13441. string_buffer[bytes++] = 'r';
  13442. break;
  13443. }
  13444. case 0x22: // quotation mark
  13445. {
  13446. string_buffer[bytes++] = '\\';
  13447. string_buffer[bytes++] = '\"';
  13448. break;
  13449. }
  13450. case 0x5C: // reverse solidus
  13451. {
  13452. string_buffer[bytes++] = '\\';
  13453. string_buffer[bytes++] = '\\';
  13454. break;
  13455. }
  13456. default:
  13457. {
  13458. // escape control characters (0x00..0x1F) or, if
  13459. // ensure_ascii parameter is used, non-ASCII characters
  13460. if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F)))
  13461. {
  13462. if (codepoint <= 0xFFFF)
  13463. {
  13464. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  13465. static_cast<std::uint16_t>(codepoint));
  13466. bytes += 6;
  13467. }
  13468. else
  13469. {
  13470. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  13471. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  13472. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  13473. bytes += 12;
  13474. }
  13475. }
  13476. else
  13477. {
  13478. // copy byte to buffer (all previous bytes
  13479. // been copied have in default case above)
  13480. string_buffer[bytes++] = s[i];
  13481. }
  13482. break;
  13483. }
  13484. }
  13485. // write buffer and reset index; there must be 13 bytes
  13486. // left, as this is the maximal number of bytes to be
  13487. // written ("\uxxxx\uxxxx\0") for one code point
  13488. if (string_buffer.size() - bytes < 13)
  13489. {
  13490. o->write_characters(string_buffer.data(), bytes);
  13491. bytes = 0;
  13492. }
  13493. // remember the byte position of this accept
  13494. bytes_after_last_accept = bytes;
  13495. undumped_chars = 0;
  13496. break;
  13497. }
  13498. case UTF8_REJECT: // decode found invalid UTF-8 byte
  13499. {
  13500. switch (error_handler)
  13501. {
  13502. case error_handler_t::strict:
  13503. {
  13504. std::string sn(3, '\0');
  13505. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  13506. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  13507. }
  13508. case error_handler_t::ignore:
  13509. case error_handler_t::replace:
  13510. {
  13511. // in case we saw this character the first time, we
  13512. // would like to read it again, because the byte
  13513. // may be OK for itself, but just not OK for the
  13514. // previous sequence
  13515. if (undumped_chars > 0)
  13516. {
  13517. --i;
  13518. }
  13519. // reset length buffer to the last accepted index;
  13520. // thus removing/ignoring the invalid characters
  13521. bytes = bytes_after_last_accept;
  13522. if (error_handler == error_handler_t::replace)
  13523. {
  13524. // add a replacement character
  13525. if (ensure_ascii)
  13526. {
  13527. string_buffer[bytes++] = '\\';
  13528. string_buffer[bytes++] = 'u';
  13529. string_buffer[bytes++] = 'f';
  13530. string_buffer[bytes++] = 'f';
  13531. string_buffer[bytes++] = 'f';
  13532. string_buffer[bytes++] = 'd';
  13533. }
  13534. else
  13535. {
  13536. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  13537. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  13538. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  13539. }
  13540. // write buffer and reset index; there must be 13 bytes
  13541. // left, as this is the maximal number of bytes to be
  13542. // written ("\uxxxx\uxxxx\0") for one code point
  13543. if (string_buffer.size() - bytes < 13)
  13544. {
  13545. o->write_characters(string_buffer.data(), bytes);
  13546. bytes = 0;
  13547. }
  13548. bytes_after_last_accept = bytes;
  13549. }
  13550. undumped_chars = 0;
  13551. // continue processing the string
  13552. state = UTF8_ACCEPT;
  13553. break;
  13554. }
  13555. default: // LCOV_EXCL_LINE
  13556. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13557. }
  13558. break;
  13559. }
  13560. default: // decode found yet incomplete multi-byte code point
  13561. {
  13562. if (!ensure_ascii)
  13563. {
  13564. // code point will not be escaped - copy byte to buffer
  13565. string_buffer[bytes++] = s[i];
  13566. }
  13567. ++undumped_chars;
  13568. break;
  13569. }
  13570. }
  13571. }
  13572. // we finished processing the string
  13573. if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT))
  13574. {
  13575. // write buffer
  13576. if (bytes > 0)
  13577. {
  13578. o->write_characters(string_buffer.data(), bytes);
  13579. }
  13580. }
  13581. else
  13582. {
  13583. // we finish reading, but do not accept: string was incomplete
  13584. switch (error_handler)
  13585. {
  13586. case error_handler_t::strict:
  13587. {
  13588. std::string sn(3, '\0');
  13589. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  13590. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  13591. }
  13592. case error_handler_t::ignore:
  13593. {
  13594. // write all accepted bytes
  13595. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13596. break;
  13597. }
  13598. case error_handler_t::replace:
  13599. {
  13600. // write all accepted bytes
  13601. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  13602. // add a replacement character
  13603. if (ensure_ascii)
  13604. {
  13605. o->write_characters("\\ufffd", 6);
  13606. }
  13607. else
  13608. {
  13609. o->write_characters("\xEF\xBF\xBD", 3);
  13610. }
  13611. break;
  13612. }
  13613. default: // LCOV_EXCL_LINE
  13614. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13615. }
  13616. }
  13617. }
  13618. /*!
  13619. @brief count digits
  13620. Count the number of decimal (base 10) digits for an input unsigned integer.
  13621. @param[in] x unsigned integer number to count its digits
  13622. @return number of decimal digits
  13623. */
  13624. inline unsigned int count_digits(number_unsigned_t x) noexcept
  13625. {
  13626. unsigned int n_digits = 1;
  13627. for (;;)
  13628. {
  13629. if (x < 10)
  13630. {
  13631. return n_digits;
  13632. }
  13633. if (x < 100)
  13634. {
  13635. return n_digits + 1;
  13636. }
  13637. if (x < 1000)
  13638. {
  13639. return n_digits + 2;
  13640. }
  13641. if (x < 10000)
  13642. {
  13643. return n_digits + 3;
  13644. }
  13645. x = x / 10000u;
  13646. n_digits += 4;
  13647. }
  13648. }
  13649. /*!
  13650. @brief dump an integer
  13651. Dump a given integer to output stream @a o. Works internally with
  13652. @a number_buffer.
  13653. @param[in] x integer number (signed or unsigned) to dump
  13654. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  13655. */
  13656. template < typename NumberType, detail::enable_if_t <
  13657. std::is_same<NumberType, number_unsigned_t>::value ||
  13658. std::is_same<NumberType, number_integer_t>::value ||
  13659. std::is_same<NumberType, binary_char_t>::value,
  13660. int > = 0 >
  13661. void dump_integer(NumberType x)
  13662. {
  13663. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  13664. {
  13665. {
  13666. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  13667. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  13668. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  13669. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  13670. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  13671. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  13672. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  13673. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  13674. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  13675. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  13676. }
  13677. };
  13678. // special case for "0"
  13679. if (x == 0)
  13680. {
  13681. o->write_character('0');
  13682. return;
  13683. }
  13684. // use a pointer to fill the buffer
  13685. auto buffer_ptr = number_buffer.begin();
  13686. const bool is_negative = std::is_same<NumberType, number_integer_t>::value && !(x >= 0); // see issue #755
  13687. number_unsigned_t abs_value;
  13688. unsigned int n_chars;
  13689. if (is_negative)
  13690. {
  13691. *buffer_ptr = '-';
  13692. abs_value = remove_sign(static_cast<number_integer_t>(x));
  13693. // account one more byte for the minus sign
  13694. n_chars = 1 + count_digits(abs_value);
  13695. }
  13696. else
  13697. {
  13698. abs_value = static_cast<number_unsigned_t>(x);
  13699. n_chars = count_digits(abs_value);
  13700. }
  13701. // spare 1 byte for '\0'
  13702. JSON_ASSERT(n_chars < number_buffer.size() - 1);
  13703. // jump to the end to generate the string from backward
  13704. // so we later avoid reversing the result
  13705. buffer_ptr += n_chars;
  13706. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  13707. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  13708. while (abs_value >= 100)
  13709. {
  13710. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  13711. abs_value /= 100;
  13712. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13713. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13714. }
  13715. if (abs_value >= 10)
  13716. {
  13717. const auto digits_index = static_cast<unsigned>(abs_value);
  13718. *(--buffer_ptr) = digits_to_99[digits_index][1];
  13719. *(--buffer_ptr) = digits_to_99[digits_index][0];
  13720. }
  13721. else
  13722. {
  13723. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  13724. }
  13725. o->write_characters(number_buffer.data(), n_chars);
  13726. }
  13727. /*!
  13728. @brief dump a floating-point number
  13729. Dump a given floating-point number to output stream @a o. Works internally
  13730. with @a number_buffer.
  13731. @param[in] x floating-point number to dump
  13732. */
  13733. void dump_float(number_float_t x)
  13734. {
  13735. // NaN / inf
  13736. if (!std::isfinite(x))
  13737. {
  13738. o->write_characters("null", 4);
  13739. return;
  13740. }
  13741. // If number_float_t is an IEEE-754 single or double precision number,
  13742. // use the Grisu2 algorithm to produce short numbers which are
  13743. // guaranteed to round-trip, using strtof and strtod, resp.
  13744. //
  13745. // NB: The test below works if <long double> == <double>.
  13746. static constexpr bool is_ieee_single_or_double
  13747. = (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 24 && std::numeric_limits<number_float_t>::max_exponent == 128) ||
  13748. (std::numeric_limits<number_float_t>::is_iec559 && std::numeric_limits<number_float_t>::digits == 53 && std::numeric_limits<number_float_t>::max_exponent == 1024);
  13749. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  13750. }
  13751. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  13752. {
  13753. char* begin = number_buffer.data();
  13754. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  13755. o->write_characters(begin, static_cast<size_t>(end - begin));
  13756. }
  13757. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  13758. {
  13759. // get number of digits for a float -> text -> float round-trip
  13760. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  13761. // the actual conversion
  13762. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  13763. // negative value indicates an error
  13764. JSON_ASSERT(len > 0);
  13765. // check if buffer was large enough
  13766. JSON_ASSERT(static_cast<std::size_t>(len) < number_buffer.size());
  13767. // erase thousands separator
  13768. if (thousands_sep != '\0')
  13769. {
  13770. const auto end = std::remove(number_buffer.begin(),
  13771. number_buffer.begin() + len, thousands_sep);
  13772. std::fill(end, number_buffer.end(), '\0');
  13773. JSON_ASSERT((end - number_buffer.begin()) <= len);
  13774. len = (end - number_buffer.begin());
  13775. }
  13776. // convert decimal point to '.'
  13777. if (decimal_point != '\0' && decimal_point != '.')
  13778. {
  13779. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  13780. if (dec_pos != number_buffer.end())
  13781. {
  13782. *dec_pos = '.';
  13783. }
  13784. }
  13785. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  13786. // determine if need to append ".0"
  13787. const bool value_is_int_like =
  13788. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  13789. [](char c)
  13790. {
  13791. return c == '.' || c == 'e';
  13792. });
  13793. if (value_is_int_like)
  13794. {
  13795. o->write_characters(".0", 2);
  13796. }
  13797. }
  13798. /*!
  13799. @brief check whether a string is UTF-8 encoded
  13800. The function checks each byte of a string whether it is UTF-8 encoded. The
  13801. result of the check is stored in the @a state parameter. The function must
  13802. be called initially with state 0 (accept). State 1 means the string must
  13803. be rejected, because the current byte is not allowed. If the string is
  13804. completely processed, but the state is non-zero, the string ended
  13805. prematurely; that is, the last byte indicated more bytes should have
  13806. followed.
  13807. @param[in,out] state the state of the decoding
  13808. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  13809. @param[in] byte next byte to decode
  13810. @return new state
  13811. @note The function has been edited: a std::array is used.
  13812. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  13813. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  13814. */
  13815. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  13816. {
  13817. static const std::array<std::uint8_t, 400> utf8d =
  13818. {
  13819. {
  13820. 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
  13821. 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
  13822. 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
  13823. 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
  13824. 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
  13825. 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
  13826. 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
  13827. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  13828. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  13829. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  13830. 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
  13831. 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
  13832. 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
  13833. 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
  13834. }
  13835. };
  13836. const std::uint8_t type = utf8d[byte];
  13837. codep = (state != UTF8_ACCEPT)
  13838. ? (byte & 0x3fu) | (codep << 6u)
  13839. : (0xFFu >> type) & (byte);
  13840. std::size_t index = 256u + static_cast<size_t>(state) * 16u + static_cast<size_t>(type);
  13841. JSON_ASSERT(index < 400);
  13842. state = utf8d[index];
  13843. return state;
  13844. }
  13845. /*
  13846. * Overload to make the compiler happy while it is instantiating
  13847. * dump_integer for number_unsigned_t.
  13848. * Must never be called.
  13849. */
  13850. number_unsigned_t remove_sign(number_unsigned_t x)
  13851. {
  13852. JSON_ASSERT(false); // LCOV_EXCL_LINE
  13853. return x; // LCOV_EXCL_LINE
  13854. }
  13855. /*
  13856. * Helper function for dump_integer
  13857. *
  13858. * This function takes a negative signed integer and returns its absolute
  13859. * value as unsigned integer. The plus/minus shuffling is necessary as we can
  13860. * not directly remove the sign of an arbitrary signed integer as the
  13861. * absolute values of INT_MIN and INT_MAX are usually not the same. See
  13862. * #1708 for details.
  13863. */
  13864. inline number_unsigned_t remove_sign(number_integer_t x) noexcept
  13865. {
  13866. JSON_ASSERT(x < 0 && x < (std::numeric_limits<number_integer_t>::max)());
  13867. return static_cast<number_unsigned_t>(-(x + 1)) + 1;
  13868. }
  13869. private:
  13870. /// the output of the serializer
  13871. output_adapter_t<char> o = nullptr;
  13872. /// a (hopefully) large enough character buffer
  13873. std::array<char, 64> number_buffer{{}};
  13874. /// the locale
  13875. const std::lconv* loc = nullptr;
  13876. /// the locale's thousand separator character
  13877. const char thousands_sep = '\0';
  13878. /// the locale's decimal point character
  13879. const char decimal_point = '\0';
  13880. /// string buffer
  13881. std::array<char, 512> string_buffer{{}};
  13882. /// the indentation character
  13883. const char indent_char;
  13884. /// the indentation string
  13885. string_t indent_string;
  13886. /// error_handler how to react on decoding errors
  13887. const error_handler_t error_handler;
  13888. };
  13889. } // namespace detail
  13890. } // namespace nlohmann
  13891. // #include <nlohmann/detail/value_t.hpp>
  13892. // #include <nlohmann/json_fwd.hpp>
  13893. // #include <nlohmann/ordered_map.hpp>
  13894. #include <functional> // less
  13895. #include <memory> // allocator
  13896. #include <utility> // pair
  13897. #include <vector> // vector
  13898. namespace nlohmann
  13899. {
  13900. /// ordered_map: a minimal map-like container that preserves insertion order
  13901. /// for use within nlohmann::basic_json<ordered_map>
  13902. template <class Key, class T, class IgnoredLess = std::less<Key>,
  13903. class Allocator = std::allocator<std::pair<const Key, T>>>
  13904. struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>
  13905. {
  13906. using key_type = Key;
  13907. using mapped_type = T;
  13908. using Container = std::vector<std::pair<const Key, T>, Allocator>;
  13909. using typename Container::iterator;
  13910. using typename Container::size_type;
  13911. using typename Container::value_type;
  13912. // Explicit constructors instead of `using Container::Container`
  13913. // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4)
  13914. ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {}
  13915. template <class It>
  13916. ordered_map(It first, It last, const Allocator& alloc = Allocator())
  13917. : Container{first, last, alloc} {}
  13918. ordered_map(std::initializer_list<T> init, const Allocator& alloc = Allocator() )
  13919. : Container{init, alloc} {}
  13920. std::pair<iterator, bool> emplace(key_type&& key, T&& t)
  13921. {
  13922. for (auto it = this->begin(); it != this->end(); ++it)
  13923. {
  13924. if (it->first == key)
  13925. {
  13926. return {it, false};
  13927. }
  13928. }
  13929. Container::emplace_back(key, t);
  13930. return {--this->end(), true};
  13931. }
  13932. T& operator[](Key&& key)
  13933. {
  13934. return emplace(std::move(key), T{}).first->second;
  13935. }
  13936. size_type erase(const Key& key)
  13937. {
  13938. for (auto it = this->begin(); it != this->end(); ++it)
  13939. {
  13940. if (it->first == key)
  13941. {
  13942. // Since we cannot move const Keys, re-construct them in place
  13943. for (auto next = it; ++next != this->end(); ++it)
  13944. {
  13945. it->~value_type(); // Destroy but keep allocation
  13946. new (&*it) value_type{std::move(*next)};
  13947. }
  13948. Container::pop_back();
  13949. return 1;
  13950. }
  13951. }
  13952. return 0;
  13953. }
  13954. };
  13955. } // namespace nlohmann
  13956. /*!
  13957. @brief namespace for Niels Lohmann
  13958. @see https://github.com/nlohmann
  13959. @since version 1.0.0
  13960. */
  13961. namespace nlohmann
  13962. {
  13963. /*!
  13964. @brief a class to store JSON values
  13965. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  13966. in @ref object_t)
  13967. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  13968. in @ref array_t)
  13969. @tparam StringType type for JSON strings and object keys (`std::string` by
  13970. default; will be used in @ref string_t)
  13971. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  13972. in @ref boolean_t)
  13973. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  13974. default; will be used in @ref number_integer_t)
  13975. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  13976. `uint64_t` by default; will be used in @ref number_unsigned_t)
  13977. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  13978. default; will be used in @ref number_float_t)
  13979. @tparam BinaryType type for packed binary data for compatibility with binary
  13980. serialization formats (`std::vector<std::uint8_t>` by default; will be used in
  13981. @ref binary_t)
  13982. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  13983. default)
  13984. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  13985. and `from_json()` (@ref adl_serializer by default)
  13986. @requirement The class satisfies the following concept requirements:
  13987. - Basic
  13988. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  13989. JSON values can be default constructed. The result will be a JSON null
  13990. value.
  13991. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  13992. A JSON value can be constructed from an rvalue argument.
  13993. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  13994. A JSON value can be copy-constructed from an lvalue expression.
  13995. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  13996. A JSON value van be assigned from an rvalue argument.
  13997. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  13998. A JSON value can be copy-assigned from an lvalue expression.
  13999. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  14000. JSON values can be destructed.
  14001. - Layout
  14002. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  14003. JSON values have
  14004. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  14005. All non-static data members are private and standard layout types, the
  14006. class has no virtual functions or (virtual) base classes.
  14007. - Library-wide
  14008. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  14009. JSON values can be compared with `==`, see @ref
  14010. operator==(const_reference,const_reference).
  14011. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  14012. JSON values can be compared with `<`, see @ref
  14013. operator<(const_reference,const_reference).
  14014. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  14015. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  14016. other compatible types, using unqualified function call @ref swap().
  14017. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  14018. JSON values can be compared against `std::nullptr_t` objects which are used
  14019. to model the `null` value.
  14020. - Container
  14021. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  14022. JSON values can be used like STL containers and provide iterator access.
  14023. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  14024. JSON values can be used like STL containers and provide reverse iterator
  14025. access.
  14026. @invariant The member variables @a m_value and @a m_type have the following
  14027. relationship:
  14028. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  14029. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  14030. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  14031. The invariants are checked by member function assert_invariant().
  14032. @internal
  14033. @note ObjectType trick from https://stackoverflow.com/a/9860911
  14034. @endinternal
  14035. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  14036. Format](http://rfc7159.net/rfc7159)
  14037. @since version 1.0.0
  14038. @nosubgrouping
  14039. */
  14040. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  14041. class basic_json
  14042. {
  14043. private:
  14044. template<detail::value_t> friend struct detail::external_constructor;
  14045. friend ::nlohmann::json_pointer<basic_json>;
  14046. template<typename BasicJsonType, typename InputType>
  14047. friend class ::nlohmann::detail::parser;
  14048. friend ::nlohmann::detail::serializer<basic_json>;
  14049. template<typename BasicJsonType>
  14050. friend class ::nlohmann::detail::iter_impl;
  14051. template<typename BasicJsonType, typename CharType>
  14052. friend class ::nlohmann::detail::binary_writer;
  14053. template<typename BasicJsonType, typename InputType, typename SAX>
  14054. friend class ::nlohmann::detail::binary_reader;
  14055. template<typename BasicJsonType>
  14056. friend class ::nlohmann::detail::json_sax_dom_parser;
  14057. template<typename BasicJsonType>
  14058. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  14059. /// workaround type for MSVC
  14060. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  14061. // convenience aliases for types residing in namespace detail;
  14062. using lexer = ::nlohmann::detail::lexer_base<basic_json>;
  14063. template<typename InputAdapterType>
  14064. static ::nlohmann::detail::parser<basic_json, InputAdapterType> parser(
  14065. InputAdapterType adapter,
  14066. detail::parser_callback_t<basic_json>cb = nullptr,
  14067. const bool allow_exceptions = true,
  14068. const bool ignore_comments = false
  14069. )
  14070. {
  14071. return ::nlohmann::detail::parser<basic_json, InputAdapterType>(std::move(adapter),
  14072. std::move(cb), allow_exceptions, ignore_comments);
  14073. }
  14074. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  14075. template<typename BasicJsonType>
  14076. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  14077. template<typename BasicJsonType>
  14078. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  14079. template<typename Iterator>
  14080. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  14081. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  14082. template<typename CharType>
  14083. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  14084. template<typename InputType>
  14085. using binary_reader = ::nlohmann::detail::binary_reader<basic_json, InputType>;
  14086. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  14087. using serializer = ::nlohmann::detail::serializer<basic_json>;
  14088. public:
  14089. using value_t = detail::value_t;
  14090. /// JSON Pointer, see @ref nlohmann::json_pointer
  14091. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  14092. template<typename T, typename SFINAE>
  14093. using json_serializer = JSONSerializer<T, SFINAE>;
  14094. /// how to treat decoding errors
  14095. using error_handler_t = detail::error_handler_t;
  14096. /// helper type for initializer lists of basic_json values
  14097. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  14098. using input_format_t = detail::input_format_t;
  14099. /// SAX interface type, see @ref nlohmann::json_sax
  14100. using json_sax_t = json_sax<basic_json>;
  14101. ////////////////
  14102. // exceptions //
  14103. ////////////////
  14104. /// @name exceptions
  14105. /// Classes to implement user-defined exceptions.
  14106. /// @{
  14107. /// @copydoc detail::exception
  14108. using exception = detail::exception;
  14109. /// @copydoc detail::parse_error
  14110. using parse_error = detail::parse_error;
  14111. /// @copydoc detail::invalid_iterator
  14112. using invalid_iterator = detail::invalid_iterator;
  14113. /// @copydoc detail::type_error
  14114. using type_error = detail::type_error;
  14115. /// @copydoc detail::out_of_range
  14116. using out_of_range = detail::out_of_range;
  14117. /// @copydoc detail::other_error
  14118. using other_error = detail::other_error;
  14119. /// @}
  14120. /////////////////////
  14121. // container types //
  14122. /////////////////////
  14123. /// @name container types
  14124. /// The canonic container types to use @ref basic_json like any other STL
  14125. /// container.
  14126. /// @{
  14127. /// the type of elements in a basic_json container
  14128. using value_type = basic_json;
  14129. /// the type of an element reference
  14130. using reference = value_type&;
  14131. /// the type of an element const reference
  14132. using const_reference = const value_type&;
  14133. /// a type to represent differences between iterators
  14134. using difference_type = std::ptrdiff_t;
  14135. /// a type to represent container sizes
  14136. using size_type = std::size_t;
  14137. /// the allocator type
  14138. using allocator_type = AllocatorType<basic_json>;
  14139. /// the type of an element pointer
  14140. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  14141. /// the type of an element const pointer
  14142. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  14143. /// an iterator for a basic_json container
  14144. using iterator = iter_impl<basic_json>;
  14145. /// a const iterator for a basic_json container
  14146. using const_iterator = iter_impl<const basic_json>;
  14147. /// a reverse iterator for a basic_json container
  14148. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  14149. /// a const reverse iterator for a basic_json container
  14150. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  14151. /// @}
  14152. /*!
  14153. @brief returns the allocator associated with the container
  14154. */
  14155. static allocator_type get_allocator()
  14156. {
  14157. return allocator_type();
  14158. }
  14159. /*!
  14160. @brief returns version information on the library
  14161. This function returns a JSON object with information about the library,
  14162. including the version number and information on the platform and compiler.
  14163. @return JSON object holding version information
  14164. key | description
  14165. ----------- | ---------------
  14166. `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).
  14167. `copyright` | The copyright line for the library as string.
  14168. `name` | The name of the library as string.
  14169. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  14170. `url` | The URL of the project as string.
  14171. `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).
  14172. @liveexample{The following code shows an example output of the `meta()`
  14173. function.,meta}
  14174. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14175. changes to any JSON value.
  14176. @complexity Constant.
  14177. @since 2.1.0
  14178. */
  14179. JSON_HEDLEY_WARN_UNUSED_RESULT
  14180. static basic_json meta()
  14181. {
  14182. basic_json result;
  14183. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  14184. result["name"] = "JSON for Modern C++";
  14185. result["url"] = "https://github.com/nlohmann/json";
  14186. result["version"]["string"] =
  14187. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  14188. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  14189. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  14190. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  14191. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  14192. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  14193. #ifdef _WIN32
  14194. result["platform"] = "win32";
  14195. #elif defined __linux__
  14196. result["platform"] = "linux";
  14197. #elif defined __APPLE__
  14198. result["platform"] = "apple";
  14199. #elif defined __unix__
  14200. result["platform"] = "unix";
  14201. #else
  14202. result["platform"] = "unknown";
  14203. #endif
  14204. #if defined(__ICC) || defined(__INTEL_COMPILER)
  14205. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  14206. #elif defined(__clang__)
  14207. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  14208. #elif defined(__GNUC__) || defined(__GNUG__)
  14209. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  14210. #elif defined(__HP_cc) || defined(__HP_aCC)
  14211. result["compiler"] = "hp"
  14212. #elif defined(__IBMCPP__)
  14213. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  14214. #elif defined(_MSC_VER)
  14215. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  14216. #elif defined(__PGI)
  14217. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  14218. #elif defined(__SUNPRO_CC)
  14219. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  14220. #else
  14221. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  14222. #endif
  14223. #ifdef __cplusplus
  14224. result["compiler"]["c++"] = std::to_string(__cplusplus);
  14225. #else
  14226. result["compiler"]["c++"] = "unknown";
  14227. #endif
  14228. return result;
  14229. }
  14230. ///////////////////////////
  14231. // JSON value data types //
  14232. ///////////////////////////
  14233. /// @name JSON value data types
  14234. /// The data types to store a JSON value. These types are derived from
  14235. /// the template arguments passed to class @ref basic_json.
  14236. /// @{
  14237. #if defined(JSON_HAS_CPP_14)
  14238. // Use transparent comparator if possible, combined with perfect forwarding
  14239. // on find() and count() calls prevents unnecessary string construction.
  14240. using object_comparator_t = std::less<>;
  14241. #else
  14242. using object_comparator_t = std::less<StringType>;
  14243. #endif
  14244. /*!
  14245. @brief a type for an object
  14246. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  14247. > An object is an unordered collection of zero or more name/value pairs,
  14248. > where a name is a string and a value is a string, number, boolean, null,
  14249. > object, or array.
  14250. To store objects in C++, a type is defined by the template parameters
  14251. described below.
  14252. @tparam ObjectType the container to store objects (e.g., `std::map` or
  14253. `std::unordered_map`)
  14254. @tparam StringType the type of the keys or names (e.g., `std::string`).
  14255. The comparison function `std::less<StringType>` is used to order elements
  14256. inside the container.
  14257. @tparam AllocatorType the allocator to use for objects (e.g.,
  14258. `std::allocator`)
  14259. #### Default type
  14260. With the default values for @a ObjectType (`std::map`), @a StringType
  14261. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  14262. value for @a object_t is:
  14263. @code {.cpp}
  14264. std::map<
  14265. std::string, // key_type
  14266. basic_json, // value_type
  14267. std::less<std::string>, // key_compare
  14268. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  14269. >
  14270. @endcode
  14271. #### Behavior
  14272. The choice of @a object_t influences the behavior of the JSON class. With
  14273. the default type, objects have the following behavior:
  14274. - When all names are unique, objects will be interoperable in the sense
  14275. that all software implementations receiving that object will agree on
  14276. the name-value mappings.
  14277. - When the names within an object are not unique, it is unspecified which
  14278. one of the values for a given key will be chosen. For instance,
  14279. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  14280. `{"key": 2}`.
  14281. - Internally, name/value pairs are stored in lexicographical order of the
  14282. names. Objects will also be serialized (see @ref dump) in this order.
  14283. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  14284. and serialized as `{"a": 2, "b": 1}`.
  14285. - When comparing objects, the order of the name/value pairs is irrelevant.
  14286. This makes objects interoperable in the sense that they will not be
  14287. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  14288. `{"a": 2, "b": 1}` will be treated as equal.
  14289. #### Limits
  14290. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14291. > An implementation may set limits on the maximum depth of nesting.
  14292. In this class, the object's limit of nesting is not explicitly constrained.
  14293. However, a maximum depth of nesting may be introduced by the compiler or
  14294. runtime environment. A theoretical limit can be queried by calling the
  14295. @ref max_size function of a JSON object.
  14296. #### Storage
  14297. Objects are stored as pointers in a @ref basic_json type. That is, for any
  14298. access to object values, a pointer of type `object_t*` must be
  14299. dereferenced.
  14300. @sa @ref array_t -- type for an array value
  14301. @since version 1.0.0
  14302. @note The order name/value pairs are added to the object is *not*
  14303. preserved by the library. Therefore, iterating an object may return
  14304. name/value pairs in a different order than they were originally stored. In
  14305. fact, keys will be traversed in alphabetical order as `std::map` with
  14306. `std::less` is used by default. Please note this behavior conforms to [RFC
  14307. 7159](http://rfc7159.net/rfc7159), because any order implements the
  14308. specified "unordered" nature of JSON objects.
  14309. */
  14310. using object_t = ObjectType<StringType,
  14311. basic_json,
  14312. object_comparator_t,
  14313. AllocatorType<std::pair<const StringType,
  14314. basic_json>>>;
  14315. /*!
  14316. @brief a type for an array
  14317. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  14318. > An array is an ordered sequence of zero or more values.
  14319. To store objects in C++, a type is defined by the template parameters
  14320. explained below.
  14321. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  14322. `std::list`)
  14323. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  14324. #### Default type
  14325. With the default values for @a ArrayType (`std::vector`) and @a
  14326. AllocatorType (`std::allocator`), the default value for @a array_t is:
  14327. @code {.cpp}
  14328. std::vector<
  14329. basic_json, // value_type
  14330. std::allocator<basic_json> // allocator_type
  14331. >
  14332. @endcode
  14333. #### Limits
  14334. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14335. > An implementation may set limits on the maximum depth of nesting.
  14336. In this class, the array's limit of nesting is not explicitly constrained.
  14337. However, a maximum depth of nesting may be introduced by the compiler or
  14338. runtime environment. A theoretical limit can be queried by calling the
  14339. @ref max_size function of a JSON array.
  14340. #### Storage
  14341. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  14342. access to array values, a pointer of type `array_t*` must be dereferenced.
  14343. @sa @ref object_t -- type for an object value
  14344. @since version 1.0.0
  14345. */
  14346. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  14347. /*!
  14348. @brief a type for a string
  14349. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  14350. > A string is a sequence of zero or more Unicode characters.
  14351. To store objects in C++, a type is defined by the template parameter
  14352. described below. Unicode values are split by the JSON class into
  14353. byte-sized characters during deserialization.
  14354. @tparam StringType the container to store strings (e.g., `std::string`).
  14355. Note this container is used for keys/names in objects, see @ref object_t.
  14356. #### Default type
  14357. With the default values for @a StringType (`std::string`), the default
  14358. value for @a string_t is:
  14359. @code {.cpp}
  14360. std::string
  14361. @endcode
  14362. #### Encoding
  14363. Strings are stored in UTF-8 encoding. Therefore, functions like
  14364. `std::string::size()` or `std::string::length()` return the number of
  14365. bytes in the string rather than the number of characters or glyphs.
  14366. #### String comparison
  14367. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14368. > Software implementations are typically required to test names of object
  14369. > members for equality. Implementations that transform the textual
  14370. > representation into sequences of Unicode code units and then perform the
  14371. > comparison numerically, code unit by code unit, are interoperable in the
  14372. > sense that implementations will agree in all cases on equality or
  14373. > inequality of two strings. For example, implementations that compare
  14374. > strings with escaped characters unconverted may incorrectly find that
  14375. > `"a\\b"` and `"a\u005Cb"` are not equal.
  14376. This implementation is interoperable as it does compare strings code unit
  14377. by code unit.
  14378. #### Storage
  14379. String values are stored as pointers in a @ref basic_json type. That is,
  14380. for any access to string values, a pointer of type `string_t*` must be
  14381. dereferenced.
  14382. @since version 1.0.0
  14383. */
  14384. using string_t = StringType;
  14385. /*!
  14386. @brief a type for a boolean
  14387. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  14388. type which differentiates the two literals `true` and `false`.
  14389. To store objects in C++, a type is defined by the template parameter @a
  14390. BooleanType which chooses the type to use.
  14391. #### Default type
  14392. With the default values for @a BooleanType (`bool`), the default value for
  14393. @a boolean_t is:
  14394. @code {.cpp}
  14395. bool
  14396. @endcode
  14397. #### Storage
  14398. Boolean values are stored directly inside a @ref basic_json type.
  14399. @since version 1.0.0
  14400. */
  14401. using boolean_t = BooleanType;
  14402. /*!
  14403. @brief a type for a number (integer)
  14404. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14405. > The representation of numbers is similar to that used in most
  14406. > programming languages. A number is represented in base 10 using decimal
  14407. > digits. It contains an integer component that may be prefixed with an
  14408. > optional minus sign, which may be followed by a fraction part and/or an
  14409. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14410. > cannot be represented in the grammar below (such as Infinity and NaN)
  14411. > are not permitted.
  14412. This description includes both integer and floating-point numbers.
  14413. However, C++ allows more precise storage if it is known whether the number
  14414. is a signed integer, an unsigned integer or a floating-point number.
  14415. Therefore, three different types, @ref number_integer_t, @ref
  14416. number_unsigned_t and @ref number_float_t are used.
  14417. To store integer numbers in C++, a type is defined by the template
  14418. parameter @a NumberIntegerType which chooses the type to use.
  14419. #### Default type
  14420. With the default values for @a NumberIntegerType (`int64_t`), the default
  14421. value for @a number_integer_t is:
  14422. @code {.cpp}
  14423. int64_t
  14424. @endcode
  14425. #### Default behavior
  14426. - The restrictions about leading zeros is not enforced in C++. Instead,
  14427. leading zeros in integer literals lead to an interpretation as octal
  14428. number. Internally, the value will be stored as decimal number. For
  14429. instance, the C++ integer literal `010` will be serialized to `8`.
  14430. During deserialization, leading zeros yield an error.
  14431. - Not-a-number (NaN) values will be serialized to `null`.
  14432. #### Limits
  14433. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14434. > An implementation may set limits on the range and precision of numbers.
  14435. When the default type is used, the maximal integer number that can be
  14436. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  14437. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  14438. that are out of range will yield over/underflow when used in a
  14439. constructor. During deserialization, too large or small integer numbers
  14440. will be automatically be stored as @ref number_unsigned_t or @ref
  14441. number_float_t.
  14442. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14443. > Note that when such software is used, numbers that are integers and are
  14444. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14445. > that implementations will agree exactly on their numeric values.
  14446. As this range is a subrange of the exactly supported range [INT64_MIN,
  14447. INT64_MAX], this class's integer type is interoperable.
  14448. #### Storage
  14449. Integer number values are stored directly inside a @ref basic_json type.
  14450. @sa @ref number_float_t -- type for number values (floating-point)
  14451. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14452. @since version 1.0.0
  14453. */
  14454. using number_integer_t = NumberIntegerType;
  14455. /*!
  14456. @brief a type for a number (unsigned)
  14457. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14458. > The representation of numbers is similar to that used in most
  14459. > programming languages. A number is represented in base 10 using decimal
  14460. > digits. It contains an integer component that may be prefixed with an
  14461. > optional minus sign, which may be followed by a fraction part and/or an
  14462. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14463. > cannot be represented in the grammar below (such as Infinity and NaN)
  14464. > are not permitted.
  14465. This description includes both integer and floating-point numbers.
  14466. However, C++ allows more precise storage if it is known whether the number
  14467. is a signed integer, an unsigned integer or a floating-point number.
  14468. Therefore, three different types, @ref number_integer_t, @ref
  14469. number_unsigned_t and @ref number_float_t are used.
  14470. To store unsigned integer numbers in C++, a type is defined by the
  14471. template parameter @a NumberUnsignedType which chooses the type to use.
  14472. #### Default type
  14473. With the default values for @a NumberUnsignedType (`uint64_t`), the
  14474. default value for @a number_unsigned_t is:
  14475. @code {.cpp}
  14476. uint64_t
  14477. @endcode
  14478. #### Default behavior
  14479. - The restrictions about leading zeros is not enforced in C++. Instead,
  14480. leading zeros in integer literals lead to an interpretation as octal
  14481. number. Internally, the value will be stored as decimal number. For
  14482. instance, the C++ integer literal `010` will be serialized to `8`.
  14483. During deserialization, leading zeros yield an error.
  14484. - Not-a-number (NaN) values will be serialized to `null`.
  14485. #### Limits
  14486. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  14487. > An implementation may set limits on the range and precision of numbers.
  14488. When the default type is used, the maximal integer number that can be
  14489. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  14490. number that can be stored is `0`. Integer numbers that are out of range
  14491. will yield over/underflow when used in a constructor. During
  14492. deserialization, too large or small integer numbers will be automatically
  14493. be stored as @ref number_integer_t or @ref number_float_t.
  14494. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  14495. > Note that when such software is used, numbers that are integers and are
  14496. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  14497. > that implementations will agree exactly on their numeric values.
  14498. As this range is a subrange (when considered in conjunction with the
  14499. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  14500. this class's integer type is interoperable.
  14501. #### Storage
  14502. Integer number values are stored directly inside a @ref basic_json type.
  14503. @sa @ref number_float_t -- type for number values (floating-point)
  14504. @sa @ref number_integer_t -- type for number values (integer)
  14505. @since version 2.0.0
  14506. */
  14507. using number_unsigned_t = NumberUnsignedType;
  14508. /*!
  14509. @brief a type for a number (floating-point)
  14510. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  14511. > The representation of numbers is similar to that used in most
  14512. > programming languages. A number is represented in base 10 using decimal
  14513. > digits. It contains an integer component that may be prefixed with an
  14514. > optional minus sign, which may be followed by a fraction part and/or an
  14515. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  14516. > cannot be represented in the grammar below (such as Infinity and NaN)
  14517. > are not permitted.
  14518. This description includes both integer and floating-point numbers.
  14519. However, C++ allows more precise storage if it is known whether the number
  14520. is a signed integer, an unsigned integer or a floating-point number.
  14521. Therefore, three different types, @ref number_integer_t, @ref
  14522. number_unsigned_t and @ref number_float_t are used.
  14523. To store floating-point numbers in C++, a type is defined by the template
  14524. parameter @a NumberFloatType which chooses the type to use.
  14525. #### Default type
  14526. With the default values for @a NumberFloatType (`double`), the default
  14527. value for @a number_float_t is:
  14528. @code {.cpp}
  14529. double
  14530. @endcode
  14531. #### Default behavior
  14532. - The restrictions about leading zeros is not enforced in C++. Instead,
  14533. leading zeros in floating-point literals will be ignored. Internally,
  14534. the value will be stored as decimal number. For instance, the C++
  14535. floating-point literal `01.2` will be serialized to `1.2`. During
  14536. deserialization, leading zeros yield an error.
  14537. - Not-a-number (NaN) values will be serialized to `null`.
  14538. #### Limits
  14539. [RFC 7159](http://rfc7159.net/rfc7159) states:
  14540. > This specification allows implementations to set limits on the range and
  14541. > precision of numbers accepted. Since software that implements IEEE
  14542. > 754-2008 binary64 (double precision) numbers is generally available and
  14543. > widely used, good interoperability can be achieved by implementations
  14544. > that expect no more precision or range than these provide, in the sense
  14545. > that implementations will approximate JSON numbers within the expected
  14546. > precision.
  14547. This implementation does exactly follow this approach, as it uses double
  14548. precision floating-point numbers. Note values smaller than
  14549. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  14550. will be stored as NaN internally and be serialized to `null`.
  14551. #### Storage
  14552. Floating-point number values are stored directly inside a @ref basic_json
  14553. type.
  14554. @sa @ref number_integer_t -- type for number values (integer)
  14555. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  14556. @since version 1.0.0
  14557. */
  14558. using number_float_t = NumberFloatType;
  14559. /*!
  14560. @brief a type for a packed binary type
  14561. This type is a type designed to carry binary data that appears in various
  14562. serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and
  14563. BSON's generic binary subtype. This type is NOT a part of standard JSON and
  14564. exists solely for compatibility with these binary types. As such, it is
  14565. simply defined as an ordered sequence of zero or more byte values.
  14566. Additionally, as an implementation detail, the subtype of the binary data is
  14567. carried around as a `std::uint8_t`, which is compatible with both of the
  14568. binary data formats that use binary subtyping, (though the specific
  14569. numbering is incompatible with each other, and it is up to the user to
  14570. translate between them).
  14571. [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type
  14572. as:
  14573. > Major type 2: a byte string. The string's length in bytes is represented
  14574. > following the rules for positive integers (major type 0).
  14575. [MessagePack's documentation on the bin type
  14576. family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family)
  14577. describes this type as:
  14578. > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes
  14579. > in addition to the size of the byte array.
  14580. [BSON's specifications](http://bsonspec.org/spec.html) describe several
  14581. binary types; however, this type is intended to represent the generic binary
  14582. type which has the description:
  14583. > Generic binary subtype - This is the most commonly used binary subtype and
  14584. > should be the 'default' for drivers and tools.
  14585. None of these impose any limitations on the internal representation other
  14586. than the basic unit of storage be some type of array whose parts are
  14587. decomposable into bytes.
  14588. The default representation of this binary format is a
  14589. `std::vector<std::uint8_t>`, which is a very common way to represent a byte
  14590. array in modern C++.
  14591. #### Default type
  14592. The default values for @a BinaryType is `std::vector<std::uint8_t>`
  14593. #### Storage
  14594. Binary Arrays are stored as pointers in a @ref basic_json type. That is,
  14595. for any access to array values, a pointer of the type `binary_t*` must be
  14596. dereferenced.
  14597. #### Notes on subtypes
  14598. - CBOR
  14599. - Binary values are represented as byte strings. No subtypes are
  14600. supported and will be ignored when CBOR is written.
  14601. - MessagePack
  14602. - If a subtype is given and the binary array contains exactly 1, 2, 4, 8,
  14603. or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8)
  14604. is used. For other sizes, the ext family (ext8, ext16, ext32) is used.
  14605. The subtype is then added as singed 8-bit integer.
  14606. - If no subtype is given, the bin family (bin8, bin16, bin32) is used.
  14607. - BSON
  14608. - If a subtype is given, it is used and added as unsigned 8-bit integer.
  14609. - If no subtype is given, the generic binary subtype 0x00 is used.
  14610. @sa @ref binary -- create a binary array
  14611. @since version 3.8.0
  14612. */
  14613. using binary_t = nlohmann::byte_container_with_subtype<BinaryType>;
  14614. /// @}
  14615. private:
  14616. /// helper for exception-safe object creation
  14617. template<typename T, typename... Args>
  14618. JSON_HEDLEY_RETURNS_NON_NULL
  14619. static T* create(Args&& ... args)
  14620. {
  14621. AllocatorType<T> alloc;
  14622. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  14623. auto deleter = [&](T * object)
  14624. {
  14625. AllocatorTraits::deallocate(alloc, object, 1);
  14626. };
  14627. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  14628. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  14629. JSON_ASSERT(object != nullptr);
  14630. return object.release();
  14631. }
  14632. ////////////////////////
  14633. // JSON value storage //
  14634. ////////////////////////
  14635. /*!
  14636. @brief a JSON value
  14637. The actual storage for a JSON value of the @ref basic_json class. This
  14638. union combines the different storage types for the JSON value types
  14639. defined in @ref value_t.
  14640. JSON type | value_t type | used type
  14641. --------- | --------------- | ------------------------
  14642. object | object | pointer to @ref object_t
  14643. array | array | pointer to @ref array_t
  14644. string | string | pointer to @ref string_t
  14645. boolean | boolean | @ref boolean_t
  14646. number | number_integer | @ref number_integer_t
  14647. number | number_unsigned | @ref number_unsigned_t
  14648. number | number_float | @ref number_float_t
  14649. binary | binary | pointer to @ref binary_t
  14650. null | null | *no value is stored*
  14651. @note Variable-length types (objects, arrays, and strings) are stored as
  14652. pointers. The size of the union should not exceed 64 bits if the default
  14653. value types are used.
  14654. @since version 1.0.0
  14655. */
  14656. union json_value
  14657. {
  14658. /// object (stored with pointer to save storage)
  14659. object_t* object;
  14660. /// array (stored with pointer to save storage)
  14661. array_t* array;
  14662. /// string (stored with pointer to save storage)
  14663. string_t* string;
  14664. /// binary (stored with pointer to save storage)
  14665. binary_t* binary;
  14666. /// boolean
  14667. boolean_t boolean;
  14668. /// number (integer)
  14669. number_integer_t number_integer;
  14670. /// number (unsigned integer)
  14671. number_unsigned_t number_unsigned;
  14672. /// number (floating-point)
  14673. number_float_t number_float;
  14674. /// default constructor (for null values)
  14675. json_value() = default;
  14676. /// constructor for booleans
  14677. json_value(boolean_t v) noexcept : boolean(v) {}
  14678. /// constructor for numbers (integer)
  14679. json_value(number_integer_t v) noexcept : number_integer(v) {}
  14680. /// constructor for numbers (unsigned)
  14681. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  14682. /// constructor for numbers (floating-point)
  14683. json_value(number_float_t v) noexcept : number_float(v) {}
  14684. /// constructor for empty values of a given type
  14685. json_value(value_t t)
  14686. {
  14687. switch (t)
  14688. {
  14689. case value_t::object:
  14690. {
  14691. object = create<object_t>();
  14692. break;
  14693. }
  14694. case value_t::array:
  14695. {
  14696. array = create<array_t>();
  14697. break;
  14698. }
  14699. case value_t::string:
  14700. {
  14701. string = create<string_t>("");
  14702. break;
  14703. }
  14704. case value_t::binary:
  14705. {
  14706. binary = create<binary_t>();
  14707. break;
  14708. }
  14709. case value_t::boolean:
  14710. {
  14711. boolean = boolean_t(false);
  14712. break;
  14713. }
  14714. case value_t::number_integer:
  14715. {
  14716. number_integer = number_integer_t(0);
  14717. break;
  14718. }
  14719. case value_t::number_unsigned:
  14720. {
  14721. number_unsigned = number_unsigned_t(0);
  14722. break;
  14723. }
  14724. case value_t::number_float:
  14725. {
  14726. number_float = number_float_t(0.0);
  14727. break;
  14728. }
  14729. case value_t::null:
  14730. {
  14731. object = nullptr; // silence warning, see #821
  14732. break;
  14733. }
  14734. default:
  14735. {
  14736. object = nullptr; // silence warning, see #821
  14737. if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
  14738. {
  14739. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.8.0")); // LCOV_EXCL_LINE
  14740. }
  14741. break;
  14742. }
  14743. }
  14744. }
  14745. /// constructor for strings
  14746. json_value(const string_t& value)
  14747. {
  14748. string = create<string_t>(value);
  14749. }
  14750. /// constructor for rvalue strings
  14751. json_value(string_t&& value)
  14752. {
  14753. string = create<string_t>(std::move(value));
  14754. }
  14755. /// constructor for objects
  14756. json_value(const object_t& value)
  14757. {
  14758. object = create<object_t>(value);
  14759. }
  14760. /// constructor for rvalue objects
  14761. json_value(object_t&& value)
  14762. {
  14763. object = create<object_t>(std::move(value));
  14764. }
  14765. /// constructor for arrays
  14766. json_value(const array_t& value)
  14767. {
  14768. array = create<array_t>(value);
  14769. }
  14770. /// constructor for rvalue arrays
  14771. json_value(array_t&& value)
  14772. {
  14773. array = create<array_t>(std::move(value));
  14774. }
  14775. /// constructor for binary arrays
  14776. json_value(const typename binary_t::container_type& value)
  14777. {
  14778. binary = create<binary_t>(value);
  14779. }
  14780. /// constructor for rvalue binary arrays
  14781. json_value(typename binary_t::container_type&& value)
  14782. {
  14783. binary = create<binary_t>(std::move(value));
  14784. }
  14785. /// constructor for binary arrays (internal type)
  14786. json_value(const binary_t& value)
  14787. {
  14788. binary = create<binary_t>(value);
  14789. }
  14790. /// constructor for rvalue binary arrays (internal type)
  14791. json_value(binary_t&& value)
  14792. {
  14793. binary = create<binary_t>(std::move(value));
  14794. }
  14795. void destroy(value_t t) noexcept
  14796. {
  14797. // flatten the current json_value to a heap-allocated stack
  14798. std::vector<basic_json> stack;
  14799. // move the top-level items to stack
  14800. if (t == value_t::array)
  14801. {
  14802. stack.reserve(array->size());
  14803. std::move(array->begin(), array->end(), std::back_inserter(stack));
  14804. }
  14805. else if (t == value_t::object)
  14806. {
  14807. stack.reserve(object->size());
  14808. for (auto&& it : *object)
  14809. {
  14810. stack.push_back(std::move(it.second));
  14811. }
  14812. }
  14813. while (!stack.empty())
  14814. {
  14815. // move the last item to local variable to be processed
  14816. basic_json current_item(std::move(stack.back()));
  14817. stack.pop_back();
  14818. // if current_item is array/object, move
  14819. // its children to the stack to be processed later
  14820. if (current_item.is_array())
  14821. {
  14822. std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
  14823. std::back_inserter(stack));
  14824. current_item.m_value.array->clear();
  14825. }
  14826. else if (current_item.is_object())
  14827. {
  14828. for (auto&& it : *current_item.m_value.object)
  14829. {
  14830. stack.push_back(std::move(it.second));
  14831. }
  14832. current_item.m_value.object->clear();
  14833. }
  14834. // it's now safe that current_item get destructed
  14835. // since it doesn't have any children
  14836. }
  14837. switch (t)
  14838. {
  14839. case value_t::object:
  14840. {
  14841. AllocatorType<object_t> alloc;
  14842. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  14843. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  14844. break;
  14845. }
  14846. case value_t::array:
  14847. {
  14848. AllocatorType<array_t> alloc;
  14849. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  14850. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  14851. break;
  14852. }
  14853. case value_t::string:
  14854. {
  14855. AllocatorType<string_t> alloc;
  14856. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  14857. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  14858. break;
  14859. }
  14860. case value_t::binary:
  14861. {
  14862. AllocatorType<binary_t> alloc;
  14863. std::allocator_traits<decltype(alloc)>::destroy(alloc, binary);
  14864. std::allocator_traits<decltype(alloc)>::deallocate(alloc, binary, 1);
  14865. break;
  14866. }
  14867. default:
  14868. {
  14869. break;
  14870. }
  14871. }
  14872. }
  14873. };
  14874. /*!
  14875. @brief checks the class invariants
  14876. This function asserts the class invariants. It needs to be called at the
  14877. end of every constructor to make sure that created objects respect the
  14878. invariant. Furthermore, it has to be called each time the type of a JSON
  14879. value is changed, because the invariant expresses a relationship between
  14880. @a m_type and @a m_value.
  14881. */
  14882. void assert_invariant() const noexcept
  14883. {
  14884. JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr);
  14885. JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr);
  14886. JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr);
  14887. JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr);
  14888. }
  14889. public:
  14890. //////////////////////////
  14891. // JSON parser callback //
  14892. //////////////////////////
  14893. /*!
  14894. @brief parser event types
  14895. The parser callback distinguishes the following events:
  14896. - `object_start`: the parser read `{` and started to process a JSON object
  14897. - `key`: the parser read a key of a value in an object
  14898. - `object_end`: the parser read `}` and finished processing a JSON object
  14899. - `array_start`: the parser read `[` and started to process a JSON array
  14900. - `array_end`: the parser read `]` and finished processing a JSON array
  14901. - `value`: the parser finished reading a JSON value
  14902. @image html callback_events.png "Example when certain parse events are triggered"
  14903. @sa @ref parser_callback_t for more information and examples
  14904. */
  14905. using parse_event_t = detail::parse_event_t;
  14906. /*!
  14907. @brief per-element parser callback type
  14908. With a parser callback function, the result of parsing a JSON text can be
  14909. influenced. When passed to @ref parse, it is called on certain events
  14910. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  14911. depth @a depth and context JSON value @a parsed. The return value of the
  14912. callback function is a boolean indicating whether the element that emitted
  14913. the callback shall be kept or not.
  14914. We distinguish six scenarios (determined by the event type) in which the
  14915. callback function can be called. The following table describes the values
  14916. of the parameters @a depth, @a event, and @a parsed.
  14917. parameter @a event | description | parameter @a depth | parameter @a parsed
  14918. ------------------ | ----------- | ------------------ | -------------------
  14919. 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
  14920. 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
  14921. 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
  14922. 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
  14923. 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
  14924. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  14925. @image html callback_events.png "Example when certain parse events are triggered"
  14926. Discarding a value (i.e., returning `false`) has different effects
  14927. depending on the context in which function was called:
  14928. - Discarded values in structured types are skipped. That is, the parser
  14929. will behave as if the discarded value was never read.
  14930. - In case a value outside a structured type is skipped, it is replaced
  14931. with `null`. This case happens if the top-level element is skipped.
  14932. @param[in] depth the depth of the recursion during parsing
  14933. @param[in] event an event of type parse_event_t indicating the context in
  14934. the callback function has been called
  14935. @param[in,out] parsed the current intermediate parse result; note that
  14936. writing to this value has no effect for parse_event_t::key events
  14937. @return Whether the JSON value which called the function during parsing
  14938. should be kept (`true`) or not (`false`). In the latter case, it is either
  14939. skipped completely or replaced by an empty discarded object.
  14940. @sa @ref parse for examples
  14941. @since version 1.0.0
  14942. */
  14943. using parser_callback_t = detail::parser_callback_t<basic_json>;
  14944. //////////////////
  14945. // constructors //
  14946. //////////////////
  14947. /// @name constructors and destructors
  14948. /// Constructors of class @ref basic_json, copy/move constructor, copy
  14949. /// assignment, static functions creating objects, and the destructor.
  14950. /// @{
  14951. /*!
  14952. @brief create an empty value with a given type
  14953. Create an empty JSON value with a given type. The value will be default
  14954. initialized with an empty value which depends on the type:
  14955. Value type | initial value
  14956. ----------- | -------------
  14957. null | `null`
  14958. boolean | `false`
  14959. string | `""`
  14960. number | `0`
  14961. object | `{}`
  14962. array | `[]`
  14963. binary | empty array
  14964. @param[in] v the type of the value to create
  14965. @complexity Constant.
  14966. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14967. changes to any JSON value.
  14968. @liveexample{The following code shows the constructor for different @ref
  14969. value_t values,basic_json__value_t}
  14970. @sa @ref clear() -- restores the postcondition of this constructor
  14971. @since version 1.0.0
  14972. */
  14973. basic_json(const value_t v)
  14974. : m_type(v), m_value(v)
  14975. {
  14976. assert_invariant();
  14977. }
  14978. /*!
  14979. @brief create a null object
  14980. Create a `null` JSON value. It either takes a null pointer as parameter
  14981. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  14982. The passed null pointer itself is not read -- it is only used to choose
  14983. the right constructor.
  14984. @complexity Constant.
  14985. @exceptionsafety No-throw guarantee: this constructor never throws
  14986. exceptions.
  14987. @liveexample{The following code shows the constructor with and without a
  14988. null pointer parameter.,basic_json__nullptr_t}
  14989. @since version 1.0.0
  14990. */
  14991. basic_json(std::nullptr_t = nullptr) noexcept
  14992. : basic_json(value_t::null)
  14993. {
  14994. assert_invariant();
  14995. }
  14996. /*!
  14997. @brief create a JSON value
  14998. This is a "catch all" constructor for all compatible JSON types; that is,
  14999. types for which a `to_json()` method exists. The constructor forwards the
  15000. parameter @a val to that method (to `json_serializer<U>::to_json` method
  15001. with `U = uncvref_t<CompatibleType>`, to be exact).
  15002. Template type @a CompatibleType includes, but is not limited to, the
  15003. following types:
  15004. - **arrays**: @ref array_t and all kinds of compatible containers such as
  15005. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  15006. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  15007. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  15008. which a @ref basic_json value can be constructed.
  15009. - **objects**: @ref object_t and all kinds of compatible associative
  15010. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  15011. and `std::unordered_multimap` with a `key_type` compatible to
  15012. @ref string_t and a `value_type` from which a @ref basic_json value can
  15013. be constructed.
  15014. - **strings**: @ref string_t, string literals, and all compatible string
  15015. containers can be used.
  15016. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  15017. @ref number_float_t, and all convertible number types such as `int`,
  15018. `size_t`, `int64_t`, `float` or `double` can be used.
  15019. - **boolean**: @ref boolean_t / `bool` can be used.
  15020. - **binary**: @ref binary_t / `std::vector<uint8_t>` may be used,
  15021. unfortunately because string literals cannot be distinguished from binary
  15022. character arrays by the C++ type system, all types compatible with `const
  15023. char*` will be directed to the string constructor instead. This is both
  15024. for backwards compatibility, and due to the fact that a binary type is not
  15025. a standard JSON type.
  15026. See the examples below.
  15027. @tparam CompatibleType a type such that:
  15028. - @a CompatibleType is not derived from `std::istream`,
  15029. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  15030. constructors),
  15031. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  15032. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  15033. @ref json_pointer, @ref iterator, etc ...)
  15034. - @ref @ref json_serializer<U> has a
  15035. `to_json(basic_json_t&, CompatibleType&&)` method
  15036. @tparam U = `uncvref_t<CompatibleType>`
  15037. @param[in] val the value to be forwarded to the respective constructor
  15038. @complexity Usually linear in the size of the passed @a val, also
  15039. depending on the implementation of the called `to_json()`
  15040. method.
  15041. @exceptionsafety Depends on the called constructor. For types directly
  15042. supported by the library (i.e., all types for which no `to_json()` function
  15043. was provided), strong guarantee holds: if an exception is thrown, there are
  15044. no changes to any JSON value.
  15045. @liveexample{The following code shows the constructor with several
  15046. compatible types.,basic_json__CompatibleType}
  15047. @since version 2.1.0
  15048. */
  15049. template < typename CompatibleType,
  15050. typename U = detail::uncvref_t<CompatibleType>,
  15051. detail::enable_if_t <
  15052. !detail::is_basic_json<U>::value && detail::is_compatible_type<basic_json_t, U>::value, int > = 0 >
  15053. basic_json(CompatibleType && val) noexcept(noexcept(
  15054. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  15055. std::forward<CompatibleType>(val))))
  15056. {
  15057. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  15058. assert_invariant();
  15059. }
  15060. /*!
  15061. @brief create a JSON value from an existing one
  15062. This is a constructor for existing @ref basic_json types.
  15063. It does not hijack copy/move constructors, since the parameter has different
  15064. template arguments than the current ones.
  15065. The constructor tries to convert the internal @ref m_value of the parameter.
  15066. @tparam BasicJsonType a type such that:
  15067. - @a BasicJsonType is a @ref basic_json type.
  15068. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  15069. @param[in] val the @ref basic_json value to be converted.
  15070. @complexity Usually linear in the size of the passed @a val, also
  15071. depending on the implementation of the called `to_json()`
  15072. method.
  15073. @exceptionsafety Depends on the called constructor. For types directly
  15074. supported by the library (i.e., all types for which no `to_json()` function
  15075. was provided), strong guarantee holds: if an exception is thrown, there are
  15076. no changes to any JSON value.
  15077. @since version 3.2.0
  15078. */
  15079. template < typename BasicJsonType,
  15080. detail::enable_if_t <
  15081. detail::is_basic_json<BasicJsonType>::value&& !std::is_same<basic_json, BasicJsonType>::value, int > = 0 >
  15082. basic_json(const BasicJsonType& val)
  15083. {
  15084. using other_boolean_t = typename BasicJsonType::boolean_t;
  15085. using other_number_float_t = typename BasicJsonType::number_float_t;
  15086. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  15087. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  15088. using other_string_t = typename BasicJsonType::string_t;
  15089. using other_object_t = typename BasicJsonType::object_t;
  15090. using other_array_t = typename BasicJsonType::array_t;
  15091. using other_binary_t = typename BasicJsonType::binary_t;
  15092. switch (val.type())
  15093. {
  15094. case value_t::boolean:
  15095. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  15096. break;
  15097. case value_t::number_float:
  15098. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  15099. break;
  15100. case value_t::number_integer:
  15101. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  15102. break;
  15103. case value_t::number_unsigned:
  15104. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  15105. break;
  15106. case value_t::string:
  15107. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  15108. break;
  15109. case value_t::object:
  15110. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  15111. break;
  15112. case value_t::array:
  15113. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  15114. break;
  15115. case value_t::binary:
  15116. JSONSerializer<other_binary_t>::to_json(*this, val.template get_ref<const other_binary_t&>());
  15117. break;
  15118. case value_t::null:
  15119. *this = nullptr;
  15120. break;
  15121. case value_t::discarded:
  15122. m_type = value_t::discarded;
  15123. break;
  15124. default: // LCOV_EXCL_LINE
  15125. JSON_ASSERT(false); // LCOV_EXCL_LINE
  15126. }
  15127. assert_invariant();
  15128. }
  15129. /*!
  15130. @brief create a container (array or object) from an initializer list
  15131. Creates a JSON value of type array or object from the passed initializer
  15132. list @a init. In case @a type_deduction is `true` (default), the type of
  15133. the JSON value to be created is deducted from the initializer list @a init
  15134. according to the following rules:
  15135. 1. If the list is empty, an empty JSON object value `{}` is created.
  15136. 2. If the list consists of pairs whose first element is a string, a JSON
  15137. object value is created where the first elements of the pairs are
  15138. treated as keys and the second elements are as values.
  15139. 3. In all other cases, an array is created.
  15140. The rules aim to create the best fit between a C++ initializer list and
  15141. JSON values. The rationale is as follows:
  15142. 1. The empty initializer list is written as `{}` which is exactly an empty
  15143. JSON object.
  15144. 2. C++ has no way of describing mapped types other than to list a list of
  15145. pairs. As JSON requires that keys must be of type string, rule 2 is the
  15146. weakest constraint one can pose on initializer lists to interpret them
  15147. as an object.
  15148. 3. In all other cases, the initializer list could not be interpreted as
  15149. JSON object type, so interpreting it as JSON array type is safe.
  15150. With the rules described above, the following JSON values cannot be
  15151. expressed by an initializer list:
  15152. - the empty array (`[]`): use @ref array(initializer_list_t)
  15153. with an empty initializer list in this case
  15154. - arrays whose elements satisfy rule 2: use @ref
  15155. array(initializer_list_t) with the same initializer list
  15156. in this case
  15157. @note When used without parentheses around an empty initializer list, @ref
  15158. basic_json() is called instead of this function, yielding the JSON null
  15159. value.
  15160. @param[in] init initializer list with JSON values
  15161. @param[in] type_deduction internal parameter; when set to `true`, the type
  15162. of the JSON value is deducted from the initializer list @a init; when set
  15163. to `false`, the type provided via @a manual_type is forced. This mode is
  15164. used by the functions @ref array(initializer_list_t) and
  15165. @ref object(initializer_list_t).
  15166. @param[in] manual_type internal parameter; when @a type_deduction is set
  15167. to `false`, the created JSON value will use the provided type (only @ref
  15168. value_t::array and @ref value_t::object are valid); when @a type_deduction
  15169. is set to `true`, this parameter has no effect
  15170. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  15171. `value_t::object`, but @a init contains an element which is not a pair
  15172. whose first element is a string. In this case, the constructor could not
  15173. create an object. If @a type_deduction would have be `true`, an array
  15174. would have been created. See @ref object(initializer_list_t)
  15175. for an example.
  15176. @complexity Linear in the size of the initializer list @a init.
  15177. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15178. changes to any JSON value.
  15179. @liveexample{The example below shows how JSON values are created from
  15180. initializer lists.,basic_json__list_init_t}
  15181. @sa @ref array(initializer_list_t) -- create a JSON array
  15182. value from an initializer list
  15183. @sa @ref object(initializer_list_t) -- create a JSON object
  15184. value from an initializer list
  15185. @since version 1.0.0
  15186. */
  15187. basic_json(initializer_list_t init,
  15188. bool type_deduction = true,
  15189. value_t manual_type = value_t::array)
  15190. {
  15191. // check if each element is an array with two elements whose first
  15192. // element is a string
  15193. bool is_an_object = std::all_of(init.begin(), init.end(),
  15194. [](const detail::json_ref<basic_json>& element_ref)
  15195. {
  15196. return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string();
  15197. });
  15198. // adjust type if type deduction is not wanted
  15199. if (!type_deduction)
  15200. {
  15201. // if array is wanted, do not create an object though possible
  15202. if (manual_type == value_t::array)
  15203. {
  15204. is_an_object = false;
  15205. }
  15206. // if object is wanted but impossible, throw an exception
  15207. if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object))
  15208. {
  15209. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  15210. }
  15211. }
  15212. if (is_an_object)
  15213. {
  15214. // the initializer list is a list of pairs -> create object
  15215. m_type = value_t::object;
  15216. m_value = value_t::object;
  15217. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  15218. {
  15219. auto element = element_ref.moved_or_copied();
  15220. m_value.object->emplace(
  15221. std::move(*((*element.m_value.array)[0].m_value.string)),
  15222. std::move((*element.m_value.array)[1]));
  15223. });
  15224. }
  15225. else
  15226. {
  15227. // the initializer list describes an array -> create array
  15228. m_type = value_t::array;
  15229. m_value.array = create<array_t>(init.begin(), init.end());
  15230. }
  15231. assert_invariant();
  15232. }
  15233. /*!
  15234. @brief explicitly create a binary array (without subtype)
  15235. Creates a JSON binary array value from a given binary container. Binary
  15236. values are part of various binary formats, such as CBOR, MessagePack, and
  15237. BSON. This constructor is used to create a value for serialization to those
  15238. formats.
  15239. @note Note, this function exists because of the difficulty in correctly
  15240. specifying the correct template overload in the standard value ctor, as both
  15241. JSON arrays and JSON binary arrays are backed with some form of a
  15242. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15243. was decided that it would be best to prevent automatic initialization of a
  15244. binary array type, for backwards compatibility and so it does not happen on
  15245. accident.
  15246. @param[in] init container containing bytes to use as binary type
  15247. @return JSON binary array value
  15248. @complexity Linear in the size of @a init.
  15249. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15250. changes to any JSON value.
  15251. @since version 3.8.0
  15252. */
  15253. JSON_HEDLEY_WARN_UNUSED_RESULT
  15254. static basic_json binary(const typename binary_t::container_type& init)
  15255. {
  15256. auto res = basic_json();
  15257. res.m_type = value_t::binary;
  15258. res.m_value = init;
  15259. return res;
  15260. }
  15261. /*!
  15262. @brief explicitly create a binary array (with subtype)
  15263. Creates a JSON binary array value from a given binary container. Binary
  15264. values are part of various binary formats, such as CBOR, MessagePack, and
  15265. BSON. This constructor is used to create a value for serialization to those
  15266. formats.
  15267. @note Note, this function exists because of the difficulty in correctly
  15268. specifying the correct template overload in the standard value ctor, as both
  15269. JSON arrays and JSON binary arrays are backed with some form of a
  15270. `std::vector`. Because JSON binary arrays are a non-standard extension it
  15271. was decided that it would be best to prevent automatic initialization of a
  15272. binary array type, for backwards compatibility and so it does not happen on
  15273. accident.
  15274. @param[in] init container containing bytes to use as binary type
  15275. @param[in] subtype subtype to use in MessagePack and BSON
  15276. @return JSON binary array value
  15277. @complexity Linear in the size of @a init.
  15278. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15279. changes to any JSON value.
  15280. @since version 3.8.0
  15281. */
  15282. JSON_HEDLEY_WARN_UNUSED_RESULT
  15283. static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype)
  15284. {
  15285. auto res = basic_json();
  15286. res.m_type = value_t::binary;
  15287. res.m_value = binary_t(init, subtype);
  15288. return res;
  15289. }
  15290. /// @copydoc binary(const typename binary_t::container_type&)
  15291. JSON_HEDLEY_WARN_UNUSED_RESULT
  15292. static basic_json binary(typename binary_t::container_type&& init)
  15293. {
  15294. auto res = basic_json();
  15295. res.m_type = value_t::binary;
  15296. res.m_value = std::move(init);
  15297. return res;
  15298. }
  15299. /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t)
  15300. JSON_HEDLEY_WARN_UNUSED_RESULT
  15301. static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype)
  15302. {
  15303. auto res = basic_json();
  15304. res.m_type = value_t::binary;
  15305. res.m_value = binary_t(std::move(init), subtype);
  15306. return res;
  15307. }
  15308. /*!
  15309. @brief explicitly create an array from an initializer list
  15310. Creates a JSON array value from a given initializer list. That is, given a
  15311. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  15312. initializer list is empty, the empty array `[]` is created.
  15313. @note This function is only needed to express two edge cases that cannot
  15314. be realized with the initializer list constructor (@ref
  15315. basic_json(initializer_list_t, bool, value_t)). These cases
  15316. are:
  15317. 1. creating an array whose elements are all pairs whose first element is a
  15318. string -- in this case, the initializer list constructor would create an
  15319. object, taking the first elements as keys
  15320. 2. creating an empty array -- passing the empty initializer list to the
  15321. initializer list constructor yields an empty object
  15322. @param[in] init initializer list with JSON values to create an array from
  15323. (optional)
  15324. @return JSON array value
  15325. @complexity Linear in the size of @a init.
  15326. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15327. changes to any JSON value.
  15328. @liveexample{The following code shows an example for the `array`
  15329. function.,array}
  15330. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15331. create a JSON value from an initializer list
  15332. @sa @ref object(initializer_list_t) -- create a JSON object
  15333. value from an initializer list
  15334. @since version 1.0.0
  15335. */
  15336. JSON_HEDLEY_WARN_UNUSED_RESULT
  15337. static basic_json array(initializer_list_t init = {})
  15338. {
  15339. return basic_json(init, false, value_t::array);
  15340. }
  15341. /*!
  15342. @brief explicitly create an object from an initializer list
  15343. Creates a JSON object value from a given initializer list. The initializer
  15344. lists elements must be pairs, and their first elements must be strings. If
  15345. the initializer list is empty, the empty object `{}` is created.
  15346. @note This function is only added for symmetry reasons. In contrast to the
  15347. related function @ref array(initializer_list_t), there are
  15348. no cases which can only be expressed by this function. That is, any
  15349. initializer list @a init can also be passed to the initializer list
  15350. constructor @ref basic_json(initializer_list_t, bool, value_t).
  15351. @param[in] init initializer list to create an object from (optional)
  15352. @return JSON object value
  15353. @throw type_error.301 if @a init is not a list of pairs whose first
  15354. elements are strings. In this case, no object can be created. When such a
  15355. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  15356. an array would have been created from the passed initializer list @a init.
  15357. See example below.
  15358. @complexity Linear in the size of @a init.
  15359. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15360. changes to any JSON value.
  15361. @liveexample{The following code shows an example for the `object`
  15362. function.,object}
  15363. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  15364. create a JSON value from an initializer list
  15365. @sa @ref array(initializer_list_t) -- create a JSON array
  15366. value from an initializer list
  15367. @since version 1.0.0
  15368. */
  15369. JSON_HEDLEY_WARN_UNUSED_RESULT
  15370. static basic_json object(initializer_list_t init = {})
  15371. {
  15372. return basic_json(init, false, value_t::object);
  15373. }
  15374. /*!
  15375. @brief construct an array with count copies of given value
  15376. Constructs a JSON array value by creating @a cnt copies of a passed value.
  15377. In case @a cnt is `0`, an empty array is created.
  15378. @param[in] cnt the number of JSON copies of @a val to create
  15379. @param[in] val the JSON value to copy
  15380. @post `std::distance(begin(),end()) == cnt` holds.
  15381. @complexity Linear in @a cnt.
  15382. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15383. changes to any JSON value.
  15384. @liveexample{The following code shows examples for the @ref
  15385. basic_json(size_type\, const basic_json&)
  15386. constructor.,basic_json__size_type_basic_json}
  15387. @since version 1.0.0
  15388. */
  15389. basic_json(size_type cnt, const basic_json& val)
  15390. : m_type(value_t::array)
  15391. {
  15392. m_value.array = create<array_t>(cnt, val);
  15393. assert_invariant();
  15394. }
  15395. /*!
  15396. @brief construct a JSON container given an iterator range
  15397. Constructs the JSON value with the contents of the range `[first, last)`.
  15398. The semantics depends on the different types a JSON value can have:
  15399. - In case of a null type, invalid_iterator.206 is thrown.
  15400. - In case of other primitive types (number, boolean, or string), @a first
  15401. must be `begin()` and @a last must be `end()`. In this case, the value is
  15402. copied. Otherwise, invalid_iterator.204 is thrown.
  15403. - In case of structured types (array, object), the constructor behaves as
  15404. similar versions for `std::vector` or `std::map`; that is, a JSON array
  15405. or object is constructed from the values in the range.
  15406. @tparam InputIT an input iterator type (@ref iterator or @ref
  15407. const_iterator)
  15408. @param[in] first begin of the range to copy from (included)
  15409. @param[in] last end of the range to copy from (excluded)
  15410. @pre Iterators @a first and @a last must be initialized. **This
  15411. precondition is enforced with an assertion (see warning).** If
  15412. assertions are switched off, a violation of this precondition yields
  15413. undefined behavior.
  15414. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  15415. checked efficiently. Only certain edge cases are detected; see the
  15416. description of the exceptions below. A violation of this precondition
  15417. yields undefined behavior.
  15418. @warning A precondition is enforced with a runtime assertion that will
  15419. result in calling `std::abort` if this precondition is not met.
  15420. Assertions can be disabled by defining `NDEBUG` at compile time.
  15421. See https://en.cppreference.com/w/cpp/error/assert for more
  15422. information.
  15423. @throw invalid_iterator.201 if iterators @a first and @a last are not
  15424. compatible (i.e., do not belong to the same JSON value). In this case,
  15425. the range `[first, last)` is undefined.
  15426. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  15427. primitive type (number, boolean, or string), but @a first does not point
  15428. to the first element any more. In this case, the range `[first, last)` is
  15429. undefined. See example code below.
  15430. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  15431. null value. In this case, the range `[first, last)` is undefined.
  15432. @complexity Linear in distance between @a first and @a last.
  15433. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15434. changes to any JSON value.
  15435. @liveexample{The example below shows several ways to create JSON values by
  15436. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  15437. @since version 1.0.0
  15438. */
  15439. template < class InputIT, typename std::enable_if <
  15440. std::is_same<InputIT, typename basic_json_t::iterator>::value ||
  15441. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int >::type = 0 >
  15442. basic_json(InputIT first, InputIT last)
  15443. {
  15444. JSON_ASSERT(first.m_object != nullptr);
  15445. JSON_ASSERT(last.m_object != nullptr);
  15446. // make sure iterator fits the current value
  15447. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  15448. {
  15449. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  15450. }
  15451. // copy type from first iterator
  15452. m_type = first.m_object->m_type;
  15453. // check if iterator range is complete for primitive values
  15454. switch (m_type)
  15455. {
  15456. case value_t::boolean:
  15457. case value_t::number_float:
  15458. case value_t::number_integer:
  15459. case value_t::number_unsigned:
  15460. case value_t::string:
  15461. {
  15462. if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin()
  15463. || !last.m_it.primitive_iterator.is_end()))
  15464. {
  15465. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  15466. }
  15467. break;
  15468. }
  15469. default:
  15470. break;
  15471. }
  15472. switch (m_type)
  15473. {
  15474. case value_t::number_integer:
  15475. {
  15476. m_value.number_integer = first.m_object->m_value.number_integer;
  15477. break;
  15478. }
  15479. case value_t::number_unsigned:
  15480. {
  15481. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  15482. break;
  15483. }
  15484. case value_t::number_float:
  15485. {
  15486. m_value.number_float = first.m_object->m_value.number_float;
  15487. break;
  15488. }
  15489. case value_t::boolean:
  15490. {
  15491. m_value.boolean = first.m_object->m_value.boolean;
  15492. break;
  15493. }
  15494. case value_t::string:
  15495. {
  15496. m_value = *first.m_object->m_value.string;
  15497. break;
  15498. }
  15499. case value_t::object:
  15500. {
  15501. m_value.object = create<object_t>(first.m_it.object_iterator,
  15502. last.m_it.object_iterator);
  15503. break;
  15504. }
  15505. case value_t::array:
  15506. {
  15507. m_value.array = create<array_t>(first.m_it.array_iterator,
  15508. last.m_it.array_iterator);
  15509. break;
  15510. }
  15511. case value_t::binary:
  15512. {
  15513. m_value = *first.m_object->m_value.binary;
  15514. break;
  15515. }
  15516. default:
  15517. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  15518. std::string(first.m_object->type_name())));
  15519. }
  15520. assert_invariant();
  15521. }
  15522. ///////////////////////////////////////
  15523. // other constructors and destructor //
  15524. ///////////////////////////////////////
  15525. template<typename JsonRef,
  15526. detail::enable_if_t<detail::conjunction<detail::is_json_ref<JsonRef>,
  15527. std::is_same<typename JsonRef::value_type, basic_json>>::value, int> = 0 >
  15528. basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {}
  15529. /*!
  15530. @brief copy constructor
  15531. Creates a copy of a given JSON value.
  15532. @param[in] other the JSON value to copy
  15533. @post `*this == other`
  15534. @complexity Linear in the size of @a other.
  15535. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15536. changes to any JSON value.
  15537. @requirement This function helps `basic_json` satisfying the
  15538. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15539. requirements:
  15540. - The complexity is linear.
  15541. - As postcondition, it holds: `other == basic_json(other)`.
  15542. @liveexample{The following code shows an example for the copy
  15543. constructor.,basic_json__basic_json}
  15544. @since version 1.0.0
  15545. */
  15546. basic_json(const basic_json& other)
  15547. : m_type(other.m_type)
  15548. {
  15549. // check of passed value is valid
  15550. other.assert_invariant();
  15551. switch (m_type)
  15552. {
  15553. case value_t::object:
  15554. {
  15555. m_value = *other.m_value.object;
  15556. break;
  15557. }
  15558. case value_t::array:
  15559. {
  15560. m_value = *other.m_value.array;
  15561. break;
  15562. }
  15563. case value_t::string:
  15564. {
  15565. m_value = *other.m_value.string;
  15566. break;
  15567. }
  15568. case value_t::boolean:
  15569. {
  15570. m_value = other.m_value.boolean;
  15571. break;
  15572. }
  15573. case value_t::number_integer:
  15574. {
  15575. m_value = other.m_value.number_integer;
  15576. break;
  15577. }
  15578. case value_t::number_unsigned:
  15579. {
  15580. m_value = other.m_value.number_unsigned;
  15581. break;
  15582. }
  15583. case value_t::number_float:
  15584. {
  15585. m_value = other.m_value.number_float;
  15586. break;
  15587. }
  15588. case value_t::binary:
  15589. {
  15590. m_value = *other.m_value.binary;
  15591. break;
  15592. }
  15593. default:
  15594. break;
  15595. }
  15596. assert_invariant();
  15597. }
  15598. /*!
  15599. @brief move constructor
  15600. Move constructor. Constructs a JSON value with the contents of the given
  15601. value @a other using move semantics. It "steals" the resources from @a
  15602. other and leaves it as JSON null value.
  15603. @param[in,out] other value to move to this object
  15604. @post `*this` has the same value as @a other before the call.
  15605. @post @a other is a JSON null value.
  15606. @complexity Constant.
  15607. @exceptionsafety No-throw guarantee: this constructor never throws
  15608. exceptions.
  15609. @requirement This function helps `basic_json` satisfying the
  15610. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  15611. requirements.
  15612. @liveexample{The code below shows the move constructor explicitly called
  15613. via std::move.,basic_json__moveconstructor}
  15614. @since version 1.0.0
  15615. */
  15616. basic_json(basic_json&& other) noexcept
  15617. : m_type(std::move(other.m_type)),
  15618. m_value(std::move(other.m_value))
  15619. {
  15620. // check that passed value is valid
  15621. other.assert_invariant();
  15622. // invalidate payload
  15623. other.m_type = value_t::null;
  15624. other.m_value = {};
  15625. assert_invariant();
  15626. }
  15627. /*!
  15628. @brief copy assignment
  15629. Copy assignment operator. Copies a JSON value via the "copy and swap"
  15630. strategy: It is expressed in terms of the copy constructor, destructor,
  15631. and the `swap()` member function.
  15632. @param[in] other value to copy from
  15633. @complexity Linear.
  15634. @requirement This function helps `basic_json` satisfying the
  15635. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15636. requirements:
  15637. - The complexity is linear.
  15638. @liveexample{The code below shows and example for the copy assignment. It
  15639. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  15640. copy of `a` (which is the null value after the swap) is
  15641. destroyed.,basic_json__copyassignment}
  15642. @since version 1.0.0
  15643. */
  15644. basic_json& operator=(basic_json other) noexcept (
  15645. std::is_nothrow_move_constructible<value_t>::value&&
  15646. std::is_nothrow_move_assignable<value_t>::value&&
  15647. std::is_nothrow_move_constructible<json_value>::value&&
  15648. std::is_nothrow_move_assignable<json_value>::value
  15649. )
  15650. {
  15651. // check that passed value is valid
  15652. other.assert_invariant();
  15653. using std::swap;
  15654. swap(m_type, other.m_type);
  15655. swap(m_value, other.m_value);
  15656. assert_invariant();
  15657. return *this;
  15658. }
  15659. /*!
  15660. @brief destructor
  15661. Destroys the JSON value and frees all allocated memory.
  15662. @complexity Linear.
  15663. @requirement This function helps `basic_json` satisfying the
  15664. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  15665. requirements:
  15666. - The complexity is linear.
  15667. - All stored elements are destroyed and all memory is freed.
  15668. @since version 1.0.0
  15669. */
  15670. ~basic_json() noexcept
  15671. {
  15672. assert_invariant();
  15673. m_value.destroy(m_type);
  15674. }
  15675. /// @}
  15676. public:
  15677. ///////////////////////
  15678. // object inspection //
  15679. ///////////////////////
  15680. /// @name object inspection
  15681. /// Functions to inspect the type of a JSON value.
  15682. /// @{
  15683. /*!
  15684. @brief serialization
  15685. Serialization function for JSON values. The function tries to mimic
  15686. Python's `json.dumps()` function, and currently supports its @a indent
  15687. and @a ensure_ascii parameters.
  15688. @param[in] indent If indent is nonnegative, then array elements and object
  15689. members will be pretty-printed with that indent level. An indent level of
  15690. `0` will only insert newlines. `-1` (the default) selects the most compact
  15691. representation.
  15692. @param[in] indent_char The character to use for indentation if @a indent is
  15693. greater than `0`. The default is ` ` (space).
  15694. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  15695. in the output are escaped with `\uXXXX` sequences, and the result consists
  15696. of ASCII characters only.
  15697. @param[in] error_handler how to react on decoding errors; there are three
  15698. possible values: `strict` (throws and exception in case a decoding error
  15699. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  15700. and `ignore` (ignore invalid UTF-8 sequences during serialization; all
  15701. bytes are copied to the output unchanged).
  15702. @return string containing the serialization of the JSON value
  15703. @throw type_error.316 if a string stored inside the JSON value is not
  15704. UTF-8 encoded and @a error_handler is set to strict
  15705. @note Binary values are serialized as object containing two keys:
  15706. - "bytes": an array of bytes as integers
  15707. - "subtype": the subtype as integer or "null" if the binary has no subtype
  15708. @complexity Linear.
  15709. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15710. changes in the JSON value.
  15711. @liveexample{The following example shows the effect of different @a indent\,
  15712. @a indent_char\, and @a ensure_ascii parameters to the result of the
  15713. serialization.,dump}
  15714. @see https://docs.python.org/2/library/json.html#json.dump
  15715. @since version 1.0.0; indentation character @a indent_char, option
  15716. @a ensure_ascii and exceptions added in version 3.0.0; error
  15717. handlers added in version 3.4.0; serialization of binary values added
  15718. in version 3.8.0.
  15719. */
  15720. string_t dump(const int indent = -1,
  15721. const char indent_char = ' ',
  15722. const bool ensure_ascii = false,
  15723. const error_handler_t error_handler = error_handler_t::strict) const
  15724. {
  15725. string_t result;
  15726. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  15727. if (indent >= 0)
  15728. {
  15729. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  15730. }
  15731. else
  15732. {
  15733. s.dump(*this, false, ensure_ascii, 0);
  15734. }
  15735. return result;
  15736. }
  15737. /*!
  15738. @brief return the type of the JSON value (explicit)
  15739. Return the type of the JSON value as a value from the @ref value_t
  15740. enumeration.
  15741. @return the type of the JSON value
  15742. Value type | return value
  15743. ------------------------- | -------------------------
  15744. null | value_t::null
  15745. boolean | value_t::boolean
  15746. string | value_t::string
  15747. number (integer) | value_t::number_integer
  15748. number (unsigned integer) | value_t::number_unsigned
  15749. number (floating-point) | value_t::number_float
  15750. object | value_t::object
  15751. array | value_t::array
  15752. binary | value_t::binary
  15753. discarded | value_t::discarded
  15754. @complexity Constant.
  15755. @exceptionsafety No-throw guarantee: this member function never throws
  15756. exceptions.
  15757. @liveexample{The following code exemplifies `type()` for all JSON
  15758. types.,type}
  15759. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15760. @sa @ref type_name() -- return the type as string
  15761. @since version 1.0.0
  15762. */
  15763. constexpr value_t type() const noexcept
  15764. {
  15765. return m_type;
  15766. }
  15767. /*!
  15768. @brief return whether type is primitive
  15769. This function returns true if and only if the JSON type is primitive
  15770. (string, number, boolean, or null).
  15771. @return `true` if type is primitive (string, number, boolean, or null),
  15772. `false` otherwise.
  15773. @complexity Constant.
  15774. @exceptionsafety No-throw guarantee: this member function never throws
  15775. exceptions.
  15776. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  15777. types.,is_primitive}
  15778. @sa @ref is_structured() -- returns whether JSON value is structured
  15779. @sa @ref is_null() -- returns whether JSON value is `null`
  15780. @sa @ref is_string() -- returns whether JSON value is a string
  15781. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  15782. @sa @ref is_number() -- returns whether JSON value is a number
  15783. @sa @ref is_binary() -- returns whether JSON value is a binary array
  15784. @since version 1.0.0
  15785. */
  15786. constexpr bool is_primitive() const noexcept
  15787. {
  15788. return is_null() || is_string() || is_boolean() || is_number() || is_binary();
  15789. }
  15790. /*!
  15791. @brief return whether type is structured
  15792. This function returns true if and only if the JSON type is structured
  15793. (array or object).
  15794. @return `true` if type is structured (array or object), `false` otherwise.
  15795. @complexity Constant.
  15796. @exceptionsafety No-throw guarantee: this member function never throws
  15797. exceptions.
  15798. @liveexample{The following code exemplifies `is_structured()` for all JSON
  15799. types.,is_structured}
  15800. @sa @ref is_primitive() -- returns whether value is primitive
  15801. @sa @ref is_array() -- returns whether value is an array
  15802. @sa @ref is_object() -- returns whether value is an object
  15803. @since version 1.0.0
  15804. */
  15805. constexpr bool is_structured() const noexcept
  15806. {
  15807. return is_array() || is_object();
  15808. }
  15809. /*!
  15810. @brief return whether value is null
  15811. This function returns true if and only if the JSON value is null.
  15812. @return `true` if type is null, `false` otherwise.
  15813. @complexity Constant.
  15814. @exceptionsafety No-throw guarantee: this member function never throws
  15815. exceptions.
  15816. @liveexample{The following code exemplifies `is_null()` for all JSON
  15817. types.,is_null}
  15818. @since version 1.0.0
  15819. */
  15820. constexpr bool is_null() const noexcept
  15821. {
  15822. return m_type == value_t::null;
  15823. }
  15824. /*!
  15825. @brief return whether value is a boolean
  15826. This function returns true if and only if the JSON value is a boolean.
  15827. @return `true` if type is boolean, `false` otherwise.
  15828. @complexity Constant.
  15829. @exceptionsafety No-throw guarantee: this member function never throws
  15830. exceptions.
  15831. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  15832. types.,is_boolean}
  15833. @since version 1.0.0
  15834. */
  15835. constexpr bool is_boolean() const noexcept
  15836. {
  15837. return m_type == value_t::boolean;
  15838. }
  15839. /*!
  15840. @brief return whether value is a number
  15841. This function returns true if and only if the JSON value is a number. This
  15842. includes both integer (signed and unsigned) and floating-point values.
  15843. @return `true` if type is number (regardless whether integer, unsigned
  15844. integer or floating-type), `false` otherwise.
  15845. @complexity Constant.
  15846. @exceptionsafety No-throw guarantee: this member function never throws
  15847. exceptions.
  15848. @liveexample{The following code exemplifies `is_number()` for all JSON
  15849. types.,is_number}
  15850. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15851. integer number
  15852. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15853. number
  15854. @sa @ref is_number_float() -- check if value is a floating-point number
  15855. @since version 1.0.0
  15856. */
  15857. constexpr bool is_number() const noexcept
  15858. {
  15859. return is_number_integer() || is_number_float();
  15860. }
  15861. /*!
  15862. @brief return whether value is an integer number
  15863. This function returns true if and only if the JSON value is a signed or
  15864. unsigned integer number. This excludes floating-point values.
  15865. @return `true` if type is an integer or unsigned integer number, `false`
  15866. otherwise.
  15867. @complexity Constant.
  15868. @exceptionsafety No-throw guarantee: this member function never throws
  15869. exceptions.
  15870. @liveexample{The following code exemplifies `is_number_integer()` for all
  15871. JSON types.,is_number_integer}
  15872. @sa @ref is_number() -- check if value is a number
  15873. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15874. number
  15875. @sa @ref is_number_float() -- check if value is a floating-point number
  15876. @since version 1.0.0
  15877. */
  15878. constexpr bool is_number_integer() const noexcept
  15879. {
  15880. return m_type == value_t::number_integer || m_type == value_t::number_unsigned;
  15881. }
  15882. /*!
  15883. @brief return whether value is an unsigned integer number
  15884. This function returns true if and only if the JSON value is an unsigned
  15885. integer number. This excludes floating-point and signed integer values.
  15886. @return `true` if type is an unsigned integer number, `false` otherwise.
  15887. @complexity Constant.
  15888. @exceptionsafety No-throw guarantee: this member function never throws
  15889. exceptions.
  15890. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  15891. JSON types.,is_number_unsigned}
  15892. @sa @ref is_number() -- check if value is a number
  15893. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  15894. integer number
  15895. @sa @ref is_number_float() -- check if value is a floating-point number
  15896. @since version 2.0.0
  15897. */
  15898. constexpr bool is_number_unsigned() const noexcept
  15899. {
  15900. return m_type == value_t::number_unsigned;
  15901. }
  15902. /*!
  15903. @brief return whether value is a floating-point number
  15904. This function returns true if and only if the JSON value is a
  15905. floating-point number. This excludes signed and unsigned integer values.
  15906. @return `true` if type is a floating-point number, `false` otherwise.
  15907. @complexity Constant.
  15908. @exceptionsafety No-throw guarantee: this member function never throws
  15909. exceptions.
  15910. @liveexample{The following code exemplifies `is_number_float()` for all
  15911. JSON types.,is_number_float}
  15912. @sa @ref is_number() -- check if value is number
  15913. @sa @ref is_number_integer() -- check if value is an integer number
  15914. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  15915. number
  15916. @since version 1.0.0
  15917. */
  15918. constexpr bool is_number_float() const noexcept
  15919. {
  15920. return m_type == value_t::number_float;
  15921. }
  15922. /*!
  15923. @brief return whether value is an object
  15924. This function returns true if and only if the JSON value is an object.
  15925. @return `true` if type is object, `false` otherwise.
  15926. @complexity Constant.
  15927. @exceptionsafety No-throw guarantee: this member function never throws
  15928. exceptions.
  15929. @liveexample{The following code exemplifies `is_object()` for all JSON
  15930. types.,is_object}
  15931. @since version 1.0.0
  15932. */
  15933. constexpr bool is_object() const noexcept
  15934. {
  15935. return m_type == value_t::object;
  15936. }
  15937. /*!
  15938. @brief return whether value is an array
  15939. This function returns true if and only if the JSON value is an array.
  15940. @return `true` if type is array, `false` otherwise.
  15941. @complexity Constant.
  15942. @exceptionsafety No-throw guarantee: this member function never throws
  15943. exceptions.
  15944. @liveexample{The following code exemplifies `is_array()` for all JSON
  15945. types.,is_array}
  15946. @since version 1.0.0
  15947. */
  15948. constexpr bool is_array() const noexcept
  15949. {
  15950. return m_type == value_t::array;
  15951. }
  15952. /*!
  15953. @brief return whether value is a string
  15954. This function returns true if and only if the JSON value is a string.
  15955. @return `true` if type is string, `false` otherwise.
  15956. @complexity Constant.
  15957. @exceptionsafety No-throw guarantee: this member function never throws
  15958. exceptions.
  15959. @liveexample{The following code exemplifies `is_string()` for all JSON
  15960. types.,is_string}
  15961. @since version 1.0.0
  15962. */
  15963. constexpr bool is_string() const noexcept
  15964. {
  15965. return m_type == value_t::string;
  15966. }
  15967. /*!
  15968. @brief return whether value is a binary array
  15969. This function returns true if and only if the JSON value is a binary array.
  15970. @return `true` if type is binary array, `false` otherwise.
  15971. @complexity Constant.
  15972. @exceptionsafety No-throw guarantee: this member function never throws
  15973. exceptions.
  15974. @liveexample{The following code exemplifies `is_binary()` for all JSON
  15975. types.,is_binary}
  15976. @since version 3.8.0
  15977. */
  15978. constexpr bool is_binary() const noexcept
  15979. {
  15980. return m_type == value_t::binary;
  15981. }
  15982. /*!
  15983. @brief return whether value is discarded
  15984. This function returns true if and only if the JSON value was discarded
  15985. during parsing with a callback function (see @ref parser_callback_t).
  15986. @note This function will always be `false` for JSON values after parsing.
  15987. That is, discarded values can only occur during parsing, but will be
  15988. removed when inside a structured value or replaced by null in other cases.
  15989. @return `true` if type is discarded, `false` otherwise.
  15990. @complexity Constant.
  15991. @exceptionsafety No-throw guarantee: this member function never throws
  15992. exceptions.
  15993. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  15994. types.,is_discarded}
  15995. @since version 1.0.0
  15996. */
  15997. constexpr bool is_discarded() const noexcept
  15998. {
  15999. return m_type == value_t::discarded;
  16000. }
  16001. /*!
  16002. @brief return the type of the JSON value (implicit)
  16003. Implicitly return the type of the JSON value as a value from the @ref
  16004. value_t enumeration.
  16005. @return the type of the JSON value
  16006. @complexity Constant.
  16007. @exceptionsafety No-throw guarantee: this member function never throws
  16008. exceptions.
  16009. @liveexample{The following code exemplifies the @ref value_t operator for
  16010. all JSON types.,operator__value_t}
  16011. @sa @ref type() -- return the type of the JSON value (explicit)
  16012. @sa @ref type_name() -- return the type as string
  16013. @since version 1.0.0
  16014. */
  16015. constexpr operator value_t() const noexcept
  16016. {
  16017. return m_type;
  16018. }
  16019. /// @}
  16020. private:
  16021. //////////////////
  16022. // value access //
  16023. //////////////////
  16024. /// get a boolean (explicit)
  16025. boolean_t get_impl(boolean_t* /*unused*/) const
  16026. {
  16027. if (JSON_HEDLEY_LIKELY(is_boolean()))
  16028. {
  16029. return m_value.boolean;
  16030. }
  16031. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  16032. }
  16033. /// get a pointer to the value (object)
  16034. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  16035. {
  16036. return is_object() ? m_value.object : nullptr;
  16037. }
  16038. /// get a pointer to the value (object)
  16039. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  16040. {
  16041. return is_object() ? m_value.object : nullptr;
  16042. }
  16043. /// get a pointer to the value (array)
  16044. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  16045. {
  16046. return is_array() ? m_value.array : nullptr;
  16047. }
  16048. /// get a pointer to the value (array)
  16049. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  16050. {
  16051. return is_array() ? m_value.array : nullptr;
  16052. }
  16053. /// get a pointer to the value (string)
  16054. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  16055. {
  16056. return is_string() ? m_value.string : nullptr;
  16057. }
  16058. /// get a pointer to the value (string)
  16059. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  16060. {
  16061. return is_string() ? m_value.string : nullptr;
  16062. }
  16063. /// get a pointer to the value (boolean)
  16064. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  16065. {
  16066. return is_boolean() ? &m_value.boolean : nullptr;
  16067. }
  16068. /// get a pointer to the value (boolean)
  16069. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  16070. {
  16071. return is_boolean() ? &m_value.boolean : nullptr;
  16072. }
  16073. /// get a pointer to the value (integer number)
  16074. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  16075. {
  16076. return is_number_integer() ? &m_value.number_integer : nullptr;
  16077. }
  16078. /// get a pointer to the value (integer number)
  16079. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  16080. {
  16081. return is_number_integer() ? &m_value.number_integer : nullptr;
  16082. }
  16083. /// get a pointer to the value (unsigned number)
  16084. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  16085. {
  16086. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16087. }
  16088. /// get a pointer to the value (unsigned number)
  16089. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  16090. {
  16091. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  16092. }
  16093. /// get a pointer to the value (floating-point number)
  16094. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  16095. {
  16096. return is_number_float() ? &m_value.number_float : nullptr;
  16097. }
  16098. /// get a pointer to the value (floating-point number)
  16099. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  16100. {
  16101. return is_number_float() ? &m_value.number_float : nullptr;
  16102. }
  16103. /// get a pointer to the value (binary)
  16104. binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept
  16105. {
  16106. return is_binary() ? m_value.binary : nullptr;
  16107. }
  16108. /// get a pointer to the value (binary)
  16109. constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept
  16110. {
  16111. return is_binary() ? m_value.binary : nullptr;
  16112. }
  16113. /*!
  16114. @brief helper function to implement get_ref()
  16115. This function helps to implement get_ref() without code duplication for
  16116. const and non-const overloads
  16117. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  16118. @throw type_error.303 if ReferenceType does not match underlying value
  16119. type of the current JSON
  16120. */
  16121. template<typename ReferenceType, typename ThisType>
  16122. static ReferenceType get_ref_impl(ThisType& obj)
  16123. {
  16124. // delegate the call to get_ptr<>()
  16125. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  16126. if (JSON_HEDLEY_LIKELY(ptr != nullptr))
  16127. {
  16128. return *ptr;
  16129. }
  16130. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  16131. }
  16132. public:
  16133. /// @name value access
  16134. /// Direct access to the stored value of a JSON value.
  16135. /// @{
  16136. /*!
  16137. @brief get special-case overload
  16138. This overloads avoids a lot of template boilerplate, it can be seen as the
  16139. identity method
  16140. @tparam BasicJsonType == @ref basic_json
  16141. @return a copy of *this
  16142. @complexity Constant.
  16143. @since version 2.1.0
  16144. */
  16145. template<typename BasicJsonType, detail::enable_if_t<
  16146. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  16147. int> = 0>
  16148. basic_json get() const
  16149. {
  16150. return *this;
  16151. }
  16152. /*!
  16153. @brief get special-case overload
  16154. This overloads converts the current @ref basic_json in a different
  16155. @ref basic_json type
  16156. @tparam BasicJsonType == @ref basic_json
  16157. @return a copy of *this, converted into @tparam BasicJsonType
  16158. @complexity Depending on the implementation of the called `from_json()`
  16159. method.
  16160. @since version 3.2.0
  16161. */
  16162. template < typename BasicJsonType, detail::enable_if_t <
  16163. !std::is_same<BasicJsonType, basic_json>::value&&
  16164. detail::is_basic_json<BasicJsonType>::value, int > = 0 >
  16165. BasicJsonType get() const
  16166. {
  16167. return *this;
  16168. }
  16169. /*!
  16170. @brief get a value (explicit)
  16171. Explicit type conversion between the JSON value and a compatible value
  16172. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16173. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16174. The value is converted by calling the @ref json_serializer<ValueType>
  16175. `from_json()` method.
  16176. The function is equivalent to executing
  16177. @code {.cpp}
  16178. ValueType ret;
  16179. JSONSerializer<ValueType>::from_json(*this, ret);
  16180. return ret;
  16181. @endcode
  16182. This overloads is chosen if:
  16183. - @a ValueType is not @ref basic_json,
  16184. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16185. `void from_json(const basic_json&, ValueType&)`, and
  16186. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  16187. the form `ValueType from_json(const basic_json&)`
  16188. @tparam ValueTypeCV the provided value type
  16189. @tparam ValueType the returned value type
  16190. @return copy of the JSON value, converted to @a ValueType
  16191. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16192. @liveexample{The example below shows several conversions from JSON values
  16193. to other types. There a few things to note: (1) Floating-point numbers can
  16194. be converted to integers\, (2) A JSON array can be converted to a standard
  16195. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16196. associative containers such as `std::unordered_map<std::string\,
  16197. json>`.,get__ValueType_const}
  16198. @since version 2.1.0
  16199. */
  16200. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16201. detail::enable_if_t <
  16202. !detail::is_basic_json<ValueType>::value &&
  16203. detail::has_from_json<basic_json_t, ValueType>::value &&
  16204. !detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16205. int > = 0 >
  16206. ValueType get() const noexcept(noexcept(
  16207. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  16208. {
  16209. // we cannot static_assert on ValueTypeCV being non-const, because
  16210. // there is support for get<const basic_json_t>(), which is why we
  16211. // still need the uncvref
  16212. static_assert(!std::is_reference<ValueTypeCV>::value,
  16213. "get() cannot be used with reference types, you might want to use get_ref()");
  16214. static_assert(std::is_default_constructible<ValueType>::value,
  16215. "types must be DefaultConstructible when used with get()");
  16216. ValueType ret;
  16217. JSONSerializer<ValueType>::from_json(*this, ret);
  16218. return ret;
  16219. }
  16220. /*!
  16221. @brief get a value (explicit); special case
  16222. Explicit type conversion between the JSON value and a compatible value
  16223. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  16224. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  16225. The value is converted by calling the @ref json_serializer<ValueType>
  16226. `from_json()` method.
  16227. The function is equivalent to executing
  16228. @code {.cpp}
  16229. return JSONSerializer<ValueTypeCV>::from_json(*this);
  16230. @endcode
  16231. This overloads is chosen if:
  16232. - @a ValueType is not @ref basic_json and
  16233. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16234. `ValueType from_json(const basic_json&)`
  16235. @note If @ref json_serializer<ValueType> has both overloads of
  16236. `from_json()`, this one is chosen.
  16237. @tparam ValueTypeCV the provided value type
  16238. @tparam ValueType the returned value type
  16239. @return copy of the JSON value, converted to @a ValueType
  16240. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16241. @since version 2.1.0
  16242. */
  16243. template < typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  16244. detail::enable_if_t < !std::is_same<basic_json_t, ValueType>::value &&
  16245. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  16246. int > = 0 >
  16247. ValueType get() const noexcept(noexcept(
  16248. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
  16249. {
  16250. static_assert(!std::is_reference<ValueTypeCV>::value,
  16251. "get() cannot be used with reference types, you might want to use get_ref()");
  16252. return JSONSerializer<ValueType>::from_json(*this);
  16253. }
  16254. /*!
  16255. @brief get a value (explicit)
  16256. Explicit type conversion between the JSON value and a compatible value.
  16257. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  16258. `from_json()` method.
  16259. The function is equivalent to executing
  16260. @code {.cpp}
  16261. ValueType v;
  16262. JSONSerializer<ValueType>::from_json(*this, v);
  16263. @endcode
  16264. This overloads is chosen if:
  16265. - @a ValueType is not @ref basic_json,
  16266. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  16267. `void from_json(const basic_json&, ValueType&)`, and
  16268. @tparam ValueType the input parameter type.
  16269. @return the input parameter, allowing chaining calls.
  16270. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  16271. @liveexample{The example below shows several conversions from JSON values
  16272. to other types. There a few things to note: (1) Floating-point numbers can
  16273. be converted to integers\, (2) A JSON array can be converted to a standard
  16274. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16275. associative containers such as `std::unordered_map<std::string\,
  16276. json>`.,get_to}
  16277. @since version 3.3.0
  16278. */
  16279. template < typename ValueType,
  16280. detail::enable_if_t <
  16281. !detail::is_basic_json<ValueType>::value&&
  16282. detail::has_from_json<basic_json_t, ValueType>::value,
  16283. int > = 0 >
  16284. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  16285. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  16286. {
  16287. JSONSerializer<ValueType>::from_json(*this, v);
  16288. return v;
  16289. }
  16290. // specialization to allow to call get_to with a basic_json value
  16291. // see https://github.com/nlohmann/json/issues/2175
  16292. template<typename ValueType,
  16293. detail::enable_if_t <
  16294. detail::is_basic_json<ValueType>::value,
  16295. int> = 0>
  16296. ValueType & get_to(ValueType& v) const
  16297. {
  16298. v = *this;
  16299. return v;
  16300. }
  16301. template <
  16302. typename T, std::size_t N,
  16303. typename Array = T (&)[N],
  16304. detail::enable_if_t <
  16305. detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
  16306. Array get_to(T (&v)[N]) const
  16307. noexcept(noexcept(JSONSerializer<Array>::from_json(
  16308. std::declval<const basic_json_t&>(), v)))
  16309. {
  16310. JSONSerializer<Array>::from_json(*this, v);
  16311. return v;
  16312. }
  16313. /*!
  16314. @brief get a pointer value (implicit)
  16315. Implicit pointer access to the internally stored JSON value. No copies are
  16316. made.
  16317. @warning Writing data to the pointee of the result yields an undefined
  16318. state.
  16319. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16320. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16321. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  16322. assertion.
  16323. @return pointer to the internally stored JSON value if the requested
  16324. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16325. @complexity Constant.
  16326. @liveexample{The example below shows how pointers to internal values of a
  16327. JSON value can be requested. Note that no type conversions are made and a
  16328. `nullptr` is returned if the value and the requested pointer type does not
  16329. match.,get_ptr}
  16330. @since version 1.0.0
  16331. */
  16332. template<typename PointerType, typename std::enable_if<
  16333. std::is_pointer<PointerType>::value, int>::type = 0>
  16334. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16335. {
  16336. // delegate the call to get_impl_ptr<>()
  16337. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16338. }
  16339. /*!
  16340. @brief get a pointer value (implicit)
  16341. @copydoc get_ptr()
  16342. */
  16343. template < typename PointerType, typename std::enable_if <
  16344. std::is_pointer<PointerType>::value&&
  16345. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int >::type = 0 >
  16346. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  16347. {
  16348. // delegate the call to get_impl_ptr<>() const
  16349. return get_impl_ptr(static_cast<PointerType>(nullptr));
  16350. }
  16351. /*!
  16352. @brief get a pointer value (explicit)
  16353. Explicit pointer access to the internally stored JSON value. No copies are
  16354. made.
  16355. @warning The pointer becomes invalid if the underlying JSON object
  16356. changes.
  16357. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  16358. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  16359. @ref number_unsigned_t, or @ref number_float_t.
  16360. @return pointer to the internally stored JSON value if the requested
  16361. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  16362. @complexity Constant.
  16363. @liveexample{The example below shows how pointers to internal values of a
  16364. JSON value can be requested. Note that no type conversions are made and a
  16365. `nullptr` is returned if the value and the requested pointer type does not
  16366. match.,get__PointerType}
  16367. @sa @ref get_ptr() for explicit pointer-member access
  16368. @since version 1.0.0
  16369. */
  16370. template<typename PointerType, typename std::enable_if<
  16371. std::is_pointer<PointerType>::value, int>::type = 0>
  16372. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  16373. {
  16374. // delegate the call to get_ptr
  16375. return get_ptr<PointerType>();
  16376. }
  16377. /*!
  16378. @brief get a pointer value (explicit)
  16379. @copydoc get()
  16380. */
  16381. template<typename PointerType, typename std::enable_if<
  16382. std::is_pointer<PointerType>::value, int>::type = 0>
  16383. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  16384. {
  16385. // delegate the call to get_ptr
  16386. return get_ptr<PointerType>();
  16387. }
  16388. /*!
  16389. @brief get a reference value (implicit)
  16390. Implicit reference access to the internally stored JSON value. No copies
  16391. are made.
  16392. @warning Writing data to the referee of the result yields an undefined
  16393. state.
  16394. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  16395. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  16396. @ref number_float_t. Enforced by static assertion.
  16397. @return reference to the internally stored JSON value if the requested
  16398. reference type @a ReferenceType fits to the JSON value; throws
  16399. type_error.303 otherwise
  16400. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  16401. with the stored JSON value; see example below
  16402. @complexity Constant.
  16403. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  16404. @since version 1.1.0
  16405. */
  16406. template<typename ReferenceType, typename std::enable_if<
  16407. std::is_reference<ReferenceType>::value, int>::type = 0>
  16408. ReferenceType get_ref()
  16409. {
  16410. // delegate call to get_ref_impl
  16411. return get_ref_impl<ReferenceType>(*this);
  16412. }
  16413. /*!
  16414. @brief get a reference value (implicit)
  16415. @copydoc get_ref()
  16416. */
  16417. template < typename ReferenceType, typename std::enable_if <
  16418. std::is_reference<ReferenceType>::value&&
  16419. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int >::type = 0 >
  16420. ReferenceType get_ref() const
  16421. {
  16422. // delegate call to get_ref_impl
  16423. return get_ref_impl<ReferenceType>(*this);
  16424. }
  16425. /*!
  16426. @brief get a value (implicit)
  16427. Implicit type conversion between the JSON value and a compatible value.
  16428. The call is realized by calling @ref get() const.
  16429. @tparam ValueType non-pointer type compatible to the JSON value, for
  16430. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  16431. `std::vector` types for JSON arrays. The character type of @ref string_t
  16432. as well as an initializer list of this type is excluded to avoid
  16433. ambiguities as these types implicitly convert to `std::string`.
  16434. @return copy of the JSON value, converted to type @a ValueType
  16435. @throw type_error.302 in case passed type @a ValueType is incompatible
  16436. to the JSON value type (e.g., the JSON value is of type boolean, but a
  16437. string is requested); see example below
  16438. @complexity Linear in the size of the JSON value.
  16439. @liveexample{The example below shows several conversions from JSON values
  16440. to other types. There a few things to note: (1) Floating-point numbers can
  16441. be converted to integers\, (2) A JSON array can be converted to a standard
  16442. `std::vector<short>`\, (3) A JSON object can be converted to C++
  16443. associative containers such as `std::unordered_map<std::string\,
  16444. json>`.,operator__ValueType}
  16445. @since version 1.0.0
  16446. */
  16447. template < typename ValueType, typename std::enable_if <
  16448. !std::is_pointer<ValueType>::value&&
  16449. !std::is_same<ValueType, detail::json_ref<basic_json>>::value&&
  16450. !std::is_same<ValueType, typename string_t::value_type>::value&&
  16451. !detail::is_basic_json<ValueType>::value
  16452. && !std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  16453. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914))
  16454. && !std::is_same<ValueType, typename std::string_view>::value
  16455. #endif
  16456. && detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  16457. , int >::type = 0 >
  16458. operator ValueType() const
  16459. {
  16460. // delegate the call to get<>() const
  16461. return get<ValueType>();
  16462. }
  16463. /*!
  16464. @return reference to the binary value
  16465. @throw type_error.302 if the value is not binary
  16466. @sa @ref is_binary() to check if the value is binary
  16467. @since version 3.8.0
  16468. */
  16469. binary_t& get_binary()
  16470. {
  16471. if (!is_binary())
  16472. {
  16473. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16474. }
  16475. return *get_ptr<binary_t*>();
  16476. }
  16477. /// @copydoc get_binary()
  16478. const binary_t& get_binary() const
  16479. {
  16480. if (!is_binary())
  16481. {
  16482. JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name())));
  16483. }
  16484. return *get_ptr<const binary_t*>();
  16485. }
  16486. /// @}
  16487. ////////////////////
  16488. // element access //
  16489. ////////////////////
  16490. /// @name element access
  16491. /// Access to the JSON value.
  16492. /// @{
  16493. /*!
  16494. @brief access specified array element with bounds checking
  16495. Returns a reference to the element at specified location @a idx, with
  16496. bounds checking.
  16497. @param[in] idx index of the element to access
  16498. @return reference to the element at index @a idx
  16499. @throw type_error.304 if the JSON value is not an array; in this case,
  16500. calling `at` with an index makes no sense. See example below.
  16501. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16502. that is, `idx >= size()`. See example below.
  16503. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16504. changes in the JSON value.
  16505. @complexity Constant.
  16506. @since version 1.0.0
  16507. @liveexample{The example below shows how array elements can be read and
  16508. written using `at()`. It also demonstrates the different exceptions that
  16509. can be thrown.,at__size_type}
  16510. */
  16511. reference at(size_type idx)
  16512. {
  16513. // at only works for arrays
  16514. if (JSON_HEDLEY_LIKELY(is_array()))
  16515. {
  16516. JSON_TRY
  16517. {
  16518. return m_value.array->at(idx);
  16519. }
  16520. JSON_CATCH (std::out_of_range&)
  16521. {
  16522. // create better exception explanation
  16523. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16524. }
  16525. }
  16526. else
  16527. {
  16528. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16529. }
  16530. }
  16531. /*!
  16532. @brief access specified array element with bounds checking
  16533. Returns a const reference to the element at specified location @a idx,
  16534. with bounds checking.
  16535. @param[in] idx index of the element to access
  16536. @return const reference to the element at index @a idx
  16537. @throw type_error.304 if the JSON value is not an array; in this case,
  16538. calling `at` with an index makes no sense. See example below.
  16539. @throw out_of_range.401 if the index @a idx is out of range of the array;
  16540. that is, `idx >= size()`. See example below.
  16541. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16542. changes in the JSON value.
  16543. @complexity Constant.
  16544. @since version 1.0.0
  16545. @liveexample{The example below shows how array elements can be read using
  16546. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16547. at__size_type_const}
  16548. */
  16549. const_reference at(size_type idx) const
  16550. {
  16551. // at only works for arrays
  16552. if (JSON_HEDLEY_LIKELY(is_array()))
  16553. {
  16554. JSON_TRY
  16555. {
  16556. return m_value.array->at(idx);
  16557. }
  16558. JSON_CATCH (std::out_of_range&)
  16559. {
  16560. // create better exception explanation
  16561. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16562. }
  16563. }
  16564. else
  16565. {
  16566. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16567. }
  16568. }
  16569. /*!
  16570. @brief access specified object element with bounds checking
  16571. Returns a reference to the element at with specified key @a key, with
  16572. bounds checking.
  16573. @param[in] key key of the element to access
  16574. @return reference to the element at key @a key
  16575. @throw type_error.304 if the JSON value is not an object; in this case,
  16576. calling `at` with a key makes no sense. See example below.
  16577. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16578. that is, `find(key) == end()`. See example below.
  16579. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16580. changes in the JSON value.
  16581. @complexity Logarithmic in the size of the container.
  16582. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16583. access by reference
  16584. @sa @ref value() for access by value with a default value
  16585. @since version 1.0.0
  16586. @liveexample{The example below shows how object elements can be read and
  16587. written using `at()`. It also demonstrates the different exceptions that
  16588. can be thrown.,at__object_t_key_type}
  16589. */
  16590. reference at(const typename object_t::key_type& key)
  16591. {
  16592. // at only works for objects
  16593. if (JSON_HEDLEY_LIKELY(is_object()))
  16594. {
  16595. JSON_TRY
  16596. {
  16597. return m_value.object->at(key);
  16598. }
  16599. JSON_CATCH (std::out_of_range&)
  16600. {
  16601. // create better exception explanation
  16602. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16603. }
  16604. }
  16605. else
  16606. {
  16607. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16608. }
  16609. }
  16610. /*!
  16611. @brief access specified object element with bounds checking
  16612. Returns a const reference to the element at with specified key @a key,
  16613. with bounds checking.
  16614. @param[in] key key of the element to access
  16615. @return const reference to the element at key @a key
  16616. @throw type_error.304 if the JSON value is not an object; in this case,
  16617. calling `at` with a key makes no sense. See example below.
  16618. @throw out_of_range.403 if the key @a key is is not stored in the object;
  16619. that is, `find(key) == end()`. See example below.
  16620. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16621. changes in the JSON value.
  16622. @complexity Logarithmic in the size of the container.
  16623. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16624. access by reference
  16625. @sa @ref value() for access by value with a default value
  16626. @since version 1.0.0
  16627. @liveexample{The example below shows how object elements can be read using
  16628. `at()`. It also demonstrates the different exceptions that can be thrown.,
  16629. at__object_t_key_type_const}
  16630. */
  16631. const_reference at(const typename object_t::key_type& key) const
  16632. {
  16633. // at only works for objects
  16634. if (JSON_HEDLEY_LIKELY(is_object()))
  16635. {
  16636. JSON_TRY
  16637. {
  16638. return m_value.object->at(key);
  16639. }
  16640. JSON_CATCH (std::out_of_range&)
  16641. {
  16642. // create better exception explanation
  16643. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  16644. }
  16645. }
  16646. else
  16647. {
  16648. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  16649. }
  16650. }
  16651. /*!
  16652. @brief access specified array element
  16653. Returns a reference to the element at specified location @a idx.
  16654. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  16655. then the array is silently filled up with `null` values to make `idx` a
  16656. valid reference to the last stored element.
  16657. @param[in] idx index of the element to access
  16658. @return reference to the element at index @a idx
  16659. @throw type_error.305 if the JSON value is not an array or null; in that
  16660. cases, using the [] operator with an index makes no sense.
  16661. @complexity Constant if @a idx is in the range of the array. Otherwise
  16662. linear in `idx - size()`.
  16663. @liveexample{The example below shows how array elements can be read and
  16664. written using `[]` operator. Note the addition of `null`
  16665. values.,operatorarray__size_type}
  16666. @since version 1.0.0
  16667. */
  16668. reference operator[](size_type idx)
  16669. {
  16670. // implicitly convert null value to an empty array
  16671. if (is_null())
  16672. {
  16673. m_type = value_t::array;
  16674. m_value.array = create<array_t>();
  16675. assert_invariant();
  16676. }
  16677. // operator[] only works for arrays
  16678. if (JSON_HEDLEY_LIKELY(is_array()))
  16679. {
  16680. // fill up array with null values if given idx is outside range
  16681. if (idx >= m_value.array->size())
  16682. {
  16683. m_value.array->insert(m_value.array->end(),
  16684. idx - m_value.array->size() + 1,
  16685. basic_json());
  16686. }
  16687. return m_value.array->operator[](idx);
  16688. }
  16689. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16690. }
  16691. /*!
  16692. @brief access specified array element
  16693. Returns a const reference to the element at specified location @a idx.
  16694. @param[in] idx index of the element to access
  16695. @return const reference to the element at index @a idx
  16696. @throw type_error.305 if the JSON value is not an array; in that case,
  16697. using the [] operator with an index makes no sense.
  16698. @complexity Constant.
  16699. @liveexample{The example below shows how array elements can be read using
  16700. the `[]` operator.,operatorarray__size_type_const}
  16701. @since version 1.0.0
  16702. */
  16703. const_reference operator[](size_type idx) const
  16704. {
  16705. // const operator[] only works for arrays
  16706. if (JSON_HEDLEY_LIKELY(is_array()))
  16707. {
  16708. return m_value.array->operator[](idx);
  16709. }
  16710. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  16711. }
  16712. /*!
  16713. @brief access specified object element
  16714. Returns a reference to the element at with specified key @a key.
  16715. @note If @a key is not found in the object, then it is silently added to
  16716. the object and filled with a `null` value to make `key` a valid reference.
  16717. In case the value was `null` before, it is converted to an object.
  16718. @param[in] key key of the element to access
  16719. @return reference to the element at key @a key
  16720. @throw type_error.305 if the JSON value is not an object or null; in that
  16721. cases, using the [] operator with a key makes no sense.
  16722. @complexity Logarithmic in the size of the container.
  16723. @liveexample{The example below shows how object elements can be read and
  16724. written using the `[]` operator.,operatorarray__key_type}
  16725. @sa @ref at(const typename object_t::key_type&) for access by reference
  16726. with range checking
  16727. @sa @ref value() for access by value with a default value
  16728. @since version 1.0.0
  16729. */
  16730. reference operator[](const typename object_t::key_type& key)
  16731. {
  16732. // implicitly convert null value to an empty object
  16733. if (is_null())
  16734. {
  16735. m_type = value_t::object;
  16736. m_value.object = create<object_t>();
  16737. assert_invariant();
  16738. }
  16739. // operator[] only works for objects
  16740. if (JSON_HEDLEY_LIKELY(is_object()))
  16741. {
  16742. return m_value.object->operator[](key);
  16743. }
  16744. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16745. }
  16746. /*!
  16747. @brief read-only access specified object element
  16748. Returns a const reference to the element at with specified key @a key. No
  16749. bounds checking is performed.
  16750. @warning If the element with key @a key does not exist, the behavior is
  16751. undefined.
  16752. @param[in] key key of the element to access
  16753. @return const reference to the element at key @a key
  16754. @pre The element with key @a key must exist. **This precondition is
  16755. enforced with an assertion.**
  16756. @throw type_error.305 if the JSON value is not an object; in that case,
  16757. using the [] operator with a key makes no sense.
  16758. @complexity Logarithmic in the size of the container.
  16759. @liveexample{The example below shows how object elements can be read using
  16760. the `[]` operator.,operatorarray__key_type_const}
  16761. @sa @ref at(const typename object_t::key_type&) for access by reference
  16762. with range checking
  16763. @sa @ref value() for access by value with a default value
  16764. @since version 1.0.0
  16765. */
  16766. const_reference operator[](const typename object_t::key_type& key) const
  16767. {
  16768. // const operator[] only works for objects
  16769. if (JSON_HEDLEY_LIKELY(is_object()))
  16770. {
  16771. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  16772. return m_value.object->find(key)->second;
  16773. }
  16774. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16775. }
  16776. /*!
  16777. @brief access specified object element
  16778. Returns a reference to the element at with specified key @a key.
  16779. @note If @a key is not found in the object, then it is silently added to
  16780. the object and filled with a `null` value to make `key` a valid reference.
  16781. In case the value was `null` before, it is converted to an object.
  16782. @param[in] key key of the element to access
  16783. @return reference to the element at key @a key
  16784. @throw type_error.305 if the JSON value is not an object or null; in that
  16785. cases, using the [] operator with a key makes no sense.
  16786. @complexity Logarithmic in the size of the container.
  16787. @liveexample{The example below shows how object elements can be read and
  16788. written using the `[]` operator.,operatorarray__key_type}
  16789. @sa @ref at(const typename object_t::key_type&) for access by reference
  16790. with range checking
  16791. @sa @ref value() for access by value with a default value
  16792. @since version 1.1.0
  16793. */
  16794. template<typename T>
  16795. JSON_HEDLEY_NON_NULL(2)
  16796. reference operator[](T* key)
  16797. {
  16798. // implicitly convert null to object
  16799. if (is_null())
  16800. {
  16801. m_type = value_t::object;
  16802. m_value = value_t::object;
  16803. assert_invariant();
  16804. }
  16805. // at only works for objects
  16806. if (JSON_HEDLEY_LIKELY(is_object()))
  16807. {
  16808. return m_value.object->operator[](key);
  16809. }
  16810. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16811. }
  16812. /*!
  16813. @brief read-only access specified object element
  16814. Returns a const reference to the element at with specified key @a key. No
  16815. bounds checking is performed.
  16816. @warning If the element with key @a key does not exist, the behavior is
  16817. undefined.
  16818. @param[in] key key of the element to access
  16819. @return const reference to the element at key @a key
  16820. @pre The element with key @a key must exist. **This precondition is
  16821. enforced with an assertion.**
  16822. @throw type_error.305 if the JSON value is not an object; in that case,
  16823. using the [] operator with a key makes no sense.
  16824. @complexity Logarithmic in the size of the container.
  16825. @liveexample{The example below shows how object elements can be read using
  16826. the `[]` operator.,operatorarray__key_type_const}
  16827. @sa @ref at(const typename object_t::key_type&) for access by reference
  16828. with range checking
  16829. @sa @ref value() for access by value with a default value
  16830. @since version 1.1.0
  16831. */
  16832. template<typename T>
  16833. JSON_HEDLEY_NON_NULL(2)
  16834. const_reference operator[](T* key) const
  16835. {
  16836. // at only works for objects
  16837. if (JSON_HEDLEY_LIKELY(is_object()))
  16838. {
  16839. JSON_ASSERT(m_value.object->find(key) != m_value.object->end());
  16840. return m_value.object->find(key)->second;
  16841. }
  16842. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  16843. }
  16844. /*!
  16845. @brief access specified object element with default value
  16846. Returns either a copy of an object's element at the specified key @a key
  16847. or a given default value if no element with key @a key exists.
  16848. The function is basically equivalent to executing
  16849. @code {.cpp}
  16850. try {
  16851. return at(key);
  16852. } catch(out_of_range) {
  16853. return default_value;
  16854. }
  16855. @endcode
  16856. @note Unlike @ref at(const typename object_t::key_type&), this function
  16857. does not throw if the given key @a key was not found.
  16858. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  16859. function does not implicitly add an element to the position defined by @a
  16860. key. This function is furthermore also applicable to const objects.
  16861. @param[in] key key of the element to access
  16862. @param[in] default_value the value to return if @a key is not found
  16863. @tparam ValueType type compatible to JSON values, for instance `int` for
  16864. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16865. JSON arrays. Note the type of the expected value at @a key and the default
  16866. value @a default_value must be compatible.
  16867. @return copy of the element at key @a key or @a default_value if @a key
  16868. is not found
  16869. @throw type_error.302 if @a default_value does not match the type of the
  16870. value at @a key
  16871. @throw type_error.306 if the JSON value is not an object; in that case,
  16872. using `value()` with a key makes no sense.
  16873. @complexity Logarithmic in the size of the container.
  16874. @liveexample{The example below shows how object elements can be queried
  16875. with a default value.,basic_json__value}
  16876. @sa @ref at(const typename object_t::key_type&) for access by reference
  16877. with range checking
  16878. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  16879. access by reference
  16880. @since version 1.0.0
  16881. */
  16882. template < class ValueType, typename std::enable_if <
  16883. std::is_convertible<basic_json_t, ValueType>::value
  16884. && !std::is_same<value_t, ValueType>::value, int >::type = 0 >
  16885. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  16886. {
  16887. // at only works for objects
  16888. if (JSON_HEDLEY_LIKELY(is_object()))
  16889. {
  16890. // if key is found, return value and given default value otherwise
  16891. const auto it = find(key);
  16892. if (it != end())
  16893. {
  16894. return *it;
  16895. }
  16896. return default_value;
  16897. }
  16898. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16899. }
  16900. /*!
  16901. @brief overload for a default value of type const char*
  16902. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  16903. */
  16904. string_t value(const typename object_t::key_type& key, const char* default_value) const
  16905. {
  16906. return value(key, string_t(default_value));
  16907. }
  16908. /*!
  16909. @brief access specified object element via JSON Pointer with default value
  16910. Returns either a copy of an object's element at the specified key @a key
  16911. or a given default value if no element with key @a key exists.
  16912. The function is basically equivalent to executing
  16913. @code {.cpp}
  16914. try {
  16915. return at(ptr);
  16916. } catch(out_of_range) {
  16917. return default_value;
  16918. }
  16919. @endcode
  16920. @note Unlike @ref at(const json_pointer&), this function does not throw
  16921. if the given key @a key was not found.
  16922. @param[in] ptr a JSON pointer to the element to access
  16923. @param[in] default_value the value to return if @a ptr found no value
  16924. @tparam ValueType type compatible to JSON values, for instance `int` for
  16925. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  16926. JSON arrays. Note the type of the expected value at @a key and the default
  16927. value @a default_value must be compatible.
  16928. @return copy of the element at key @a key or @a default_value if @a key
  16929. is not found
  16930. @throw type_error.302 if @a default_value does not match the type of the
  16931. value at @a ptr
  16932. @throw type_error.306 if the JSON value is not an object; in that case,
  16933. using `value()` with a key makes no sense.
  16934. @complexity Logarithmic in the size of the container.
  16935. @liveexample{The example below shows how object elements can be queried
  16936. with a default value.,basic_json__value_ptr}
  16937. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  16938. @since version 2.0.2
  16939. */
  16940. template<class ValueType, typename std::enable_if<
  16941. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  16942. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  16943. {
  16944. // at only works for objects
  16945. if (JSON_HEDLEY_LIKELY(is_object()))
  16946. {
  16947. // if pointer resolves a value, return it or use default value
  16948. JSON_TRY
  16949. {
  16950. return ptr.get_checked(this);
  16951. }
  16952. JSON_INTERNAL_CATCH (out_of_range&)
  16953. {
  16954. return default_value;
  16955. }
  16956. }
  16957. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  16958. }
  16959. /*!
  16960. @brief overload for a default value of type const char*
  16961. @copydoc basic_json::value(const json_pointer&, ValueType) const
  16962. */
  16963. JSON_HEDLEY_NON_NULL(3)
  16964. string_t value(const json_pointer& ptr, const char* default_value) const
  16965. {
  16966. return value(ptr, string_t(default_value));
  16967. }
  16968. /*!
  16969. @brief access the first element
  16970. Returns a reference to the first element in the container. For a JSON
  16971. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  16972. @return In case of a structured type (array or object), a reference to the
  16973. first element is returned. In case of number, string, boolean, or binary
  16974. values, a reference to the value is returned.
  16975. @complexity Constant.
  16976. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  16977. or an empty array or object (undefined behavior, **guarded by
  16978. assertions**).
  16979. @post The JSON value remains unchanged.
  16980. @throw invalid_iterator.214 when called on `null` value
  16981. @liveexample{The following code shows an example for `front()`.,front}
  16982. @sa @ref back() -- access the last element
  16983. @since version 1.0.0
  16984. */
  16985. reference front()
  16986. {
  16987. return *begin();
  16988. }
  16989. /*!
  16990. @copydoc basic_json::front()
  16991. */
  16992. const_reference front() const
  16993. {
  16994. return *cbegin();
  16995. }
  16996. /*!
  16997. @brief access the last element
  16998. Returns a reference to the last element in the container. For a JSON
  16999. container `c`, the expression `c.back()` is equivalent to
  17000. @code {.cpp}
  17001. auto tmp = c.end();
  17002. --tmp;
  17003. return *tmp;
  17004. @endcode
  17005. @return In case of a structured type (array or object), a reference to the
  17006. last element is returned. In case of number, string, boolean, or binary
  17007. values, a reference to the value is returned.
  17008. @complexity Constant.
  17009. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  17010. or an empty array or object (undefined behavior, **guarded by
  17011. assertions**).
  17012. @post The JSON value remains unchanged.
  17013. @throw invalid_iterator.214 when called on a `null` value. See example
  17014. below.
  17015. @liveexample{The following code shows an example for `back()`.,back}
  17016. @sa @ref front() -- access the first element
  17017. @since version 1.0.0
  17018. */
  17019. reference back()
  17020. {
  17021. auto tmp = end();
  17022. --tmp;
  17023. return *tmp;
  17024. }
  17025. /*!
  17026. @copydoc basic_json::back()
  17027. */
  17028. const_reference back() const
  17029. {
  17030. auto tmp = cend();
  17031. --tmp;
  17032. return *tmp;
  17033. }
  17034. /*!
  17035. @brief remove element given an iterator
  17036. Removes the element specified by iterator @a pos. The iterator @a pos must
  17037. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  17038. but is not dereferenceable) cannot be used as a value for @a pos.
  17039. If called on a primitive type other than `null`, the resulting JSON value
  17040. will be `null`.
  17041. @param[in] pos iterator to the element to remove
  17042. @return Iterator following the last removed element. If the iterator @a
  17043. pos refers to the last element, the `end()` iterator is returned.
  17044. @tparam IteratorType an @ref iterator or @ref const_iterator
  17045. @post Invalidates iterators and references at or after the point of the
  17046. erase, including the `end()` iterator.
  17047. @throw type_error.307 if called on a `null` value; example: `"cannot use
  17048. erase() with null"`
  17049. @throw invalid_iterator.202 if called on an iterator which does not belong
  17050. to the current JSON value; example: `"iterator does not fit current
  17051. value"`
  17052. @throw invalid_iterator.205 if called on a primitive type with invalid
  17053. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  17054. out of range"`
  17055. @complexity The complexity depends on the type:
  17056. - objects: amortized constant
  17057. - arrays: linear in distance between @a pos and the end of the container
  17058. - strings and binary: linear in the length of the member
  17059. - other types: constant
  17060. @liveexample{The example shows the result of `erase()` for different JSON
  17061. types.,erase__IteratorType}
  17062. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17063. the given range
  17064. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17065. from an object at the given key
  17066. @sa @ref erase(const size_type) -- removes the element from an array at
  17067. the given index
  17068. @since version 1.0.0
  17069. */
  17070. template < class IteratorType, typename std::enable_if <
  17071. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  17072. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  17073. = 0 >
  17074. IteratorType erase(IteratorType pos)
  17075. {
  17076. // make sure iterator fits the current value
  17077. if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
  17078. {
  17079. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  17080. }
  17081. IteratorType result = end();
  17082. switch (m_type)
  17083. {
  17084. case value_t::boolean:
  17085. case value_t::number_float:
  17086. case value_t::number_integer:
  17087. case value_t::number_unsigned:
  17088. case value_t::string:
  17089. case value_t::binary:
  17090. {
  17091. if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin()))
  17092. {
  17093. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  17094. }
  17095. if (is_string())
  17096. {
  17097. AllocatorType<string_t> alloc;
  17098. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17099. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17100. m_value.string = nullptr;
  17101. }
  17102. else if (is_binary())
  17103. {
  17104. AllocatorType<binary_t> alloc;
  17105. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17106. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17107. m_value.binary = nullptr;
  17108. }
  17109. m_type = value_t::null;
  17110. assert_invariant();
  17111. break;
  17112. }
  17113. case value_t::object:
  17114. {
  17115. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  17116. break;
  17117. }
  17118. case value_t::array:
  17119. {
  17120. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  17121. break;
  17122. }
  17123. default:
  17124. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17125. }
  17126. return result;
  17127. }
  17128. /*!
  17129. @brief remove elements given an iterator range
  17130. Removes the element specified by the range `[first; last)`. The iterator
  17131. @a first does not need to be dereferenceable if `first == last`: erasing
  17132. an empty range is a no-op.
  17133. If called on a primitive type other than `null`, the resulting JSON value
  17134. will be `null`.
  17135. @param[in] first iterator to the beginning of the range to remove
  17136. @param[in] last iterator past the end of the range to remove
  17137. @return Iterator following the last removed element. If the iterator @a
  17138. second refers to the last element, the `end()` iterator is returned.
  17139. @tparam IteratorType an @ref iterator or @ref const_iterator
  17140. @post Invalidates iterators and references at or after the point of the
  17141. erase, including the `end()` iterator.
  17142. @throw type_error.307 if called on a `null` value; example: `"cannot use
  17143. erase() with null"`
  17144. @throw invalid_iterator.203 if called on iterators which does not belong
  17145. to the current JSON value; example: `"iterators do not fit current value"`
  17146. @throw invalid_iterator.204 if called on a primitive type with invalid
  17147. iterators (i.e., if `first != begin()` and `last != end()`); example:
  17148. `"iterators out of range"`
  17149. @complexity The complexity depends on the type:
  17150. - objects: `log(size()) + std::distance(first, last)`
  17151. - arrays: linear in the distance between @a first and @a last, plus linear
  17152. in the distance between @a last and end of the container
  17153. - strings and binary: linear in the length of the member
  17154. - other types: constant
  17155. @liveexample{The example shows the result of `erase()` for different JSON
  17156. types.,erase__IteratorType_IteratorType}
  17157. @sa @ref erase(IteratorType) -- removes the element at a given position
  17158. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17159. from an object at the given key
  17160. @sa @ref erase(const size_type) -- removes the element from an array at
  17161. the given index
  17162. @since version 1.0.0
  17163. */
  17164. template < class IteratorType, typename std::enable_if <
  17165. std::is_same<IteratorType, typename basic_json_t::iterator>::value ||
  17166. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int >::type
  17167. = 0 >
  17168. IteratorType erase(IteratorType first, IteratorType last)
  17169. {
  17170. // make sure iterator fits the current value
  17171. if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object))
  17172. {
  17173. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  17174. }
  17175. IteratorType result = end();
  17176. switch (m_type)
  17177. {
  17178. case value_t::boolean:
  17179. case value_t::number_float:
  17180. case value_t::number_integer:
  17181. case value_t::number_unsigned:
  17182. case value_t::string:
  17183. case value_t::binary:
  17184. {
  17185. if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin()
  17186. || !last.m_it.primitive_iterator.is_end()))
  17187. {
  17188. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  17189. }
  17190. if (is_string())
  17191. {
  17192. AllocatorType<string_t> alloc;
  17193. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  17194. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  17195. m_value.string = nullptr;
  17196. }
  17197. else if (is_binary())
  17198. {
  17199. AllocatorType<binary_t> alloc;
  17200. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.binary);
  17201. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.binary, 1);
  17202. m_value.binary = nullptr;
  17203. }
  17204. m_type = value_t::null;
  17205. assert_invariant();
  17206. break;
  17207. }
  17208. case value_t::object:
  17209. {
  17210. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  17211. last.m_it.object_iterator);
  17212. break;
  17213. }
  17214. case value_t::array:
  17215. {
  17216. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  17217. last.m_it.array_iterator);
  17218. break;
  17219. }
  17220. default:
  17221. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17222. }
  17223. return result;
  17224. }
  17225. /*!
  17226. @brief remove element from a JSON object given a key
  17227. Removes elements from a JSON object with the key value @a key.
  17228. @param[in] key value of the elements to remove
  17229. @return Number of elements removed. If @a ObjectType is the default
  17230. `std::map` type, the return value will always be `0` (@a key was not
  17231. found) or `1` (@a key was found).
  17232. @post References and iterators to the erased elements are invalidated.
  17233. Other references and iterators are not affected.
  17234. @throw type_error.307 when called on a type other than JSON object;
  17235. example: `"cannot use erase() with null"`
  17236. @complexity `log(size()) + count(key)`
  17237. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  17238. @sa @ref erase(IteratorType) -- removes the element at a given position
  17239. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17240. the given range
  17241. @sa @ref erase(const size_type) -- removes the element from an array at
  17242. the given index
  17243. @since version 1.0.0
  17244. */
  17245. size_type erase(const typename object_t::key_type& key)
  17246. {
  17247. // this erase only works for objects
  17248. if (JSON_HEDLEY_LIKELY(is_object()))
  17249. {
  17250. return m_value.object->erase(key);
  17251. }
  17252. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17253. }
  17254. /*!
  17255. @brief remove element from a JSON array given an index
  17256. Removes element from a JSON array at the index @a idx.
  17257. @param[in] idx index of the element to remove
  17258. @throw type_error.307 when called on a type other than JSON object;
  17259. example: `"cannot use erase() with null"`
  17260. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  17261. is out of range"`
  17262. @complexity Linear in distance between @a idx and the end of the container.
  17263. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  17264. @sa @ref erase(IteratorType) -- removes the element at a given position
  17265. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  17266. the given range
  17267. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  17268. from an object at the given key
  17269. @since version 1.0.0
  17270. */
  17271. void erase(const size_type idx)
  17272. {
  17273. // this erase only works for arrays
  17274. if (JSON_HEDLEY_LIKELY(is_array()))
  17275. {
  17276. if (JSON_HEDLEY_UNLIKELY(idx >= size()))
  17277. {
  17278. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  17279. }
  17280. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  17281. }
  17282. else
  17283. {
  17284. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  17285. }
  17286. }
  17287. /// @}
  17288. ////////////
  17289. // lookup //
  17290. ////////////
  17291. /// @name lookup
  17292. /// @{
  17293. /*!
  17294. @brief find an element in a JSON object
  17295. Finds an element in a JSON object with key equivalent to @a key. If the
  17296. element is not found or the JSON value is not an object, end() is
  17297. returned.
  17298. @note This method always returns @ref end() when executed on a JSON type
  17299. that is not an object.
  17300. @param[in] key key value of the element to search for.
  17301. @return Iterator to an element with key equivalent to @a key. If no such
  17302. element is found or the JSON value is not an object, past-the-end (see
  17303. @ref end()) iterator is returned.
  17304. @complexity Logarithmic in the size of the JSON object.
  17305. @liveexample{The example shows how `find()` is used.,find__key_type}
  17306. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  17307. @since version 1.0.0
  17308. */
  17309. template<typename KeyT>
  17310. iterator find(KeyT&& key)
  17311. {
  17312. auto result = end();
  17313. if (is_object())
  17314. {
  17315. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17316. }
  17317. return result;
  17318. }
  17319. /*!
  17320. @brief find an element in a JSON object
  17321. @copydoc find(KeyT&&)
  17322. */
  17323. template<typename KeyT>
  17324. const_iterator find(KeyT&& key) const
  17325. {
  17326. auto result = cend();
  17327. if (is_object())
  17328. {
  17329. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  17330. }
  17331. return result;
  17332. }
  17333. /*!
  17334. @brief returns the number of occurrences of a key in a JSON object
  17335. Returns the number of elements with key @a key. If ObjectType is the
  17336. default `std::map` type, the return value will always be `0` (@a key was
  17337. not found) or `1` (@a key was found).
  17338. @note This method always returns `0` when executed on a JSON type that is
  17339. not an object.
  17340. @param[in] key key value of the element to count
  17341. @return Number of elements with key @a key. If the JSON value is not an
  17342. object, the return value will be `0`.
  17343. @complexity Logarithmic in the size of the JSON object.
  17344. @liveexample{The example shows how `count()` is used.,count}
  17345. @since version 1.0.0
  17346. */
  17347. template<typename KeyT>
  17348. size_type count(KeyT&& key) const
  17349. {
  17350. // return 0 for all nonobject types
  17351. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  17352. }
  17353. /*!
  17354. @brief check the existence of an element in a JSON object
  17355. Check whether an element exists in a JSON object with key equivalent to
  17356. @a key. If the element is not found or the JSON value is not an object,
  17357. false is returned.
  17358. @note This method always returns false when executed on a JSON type
  17359. that is not an object.
  17360. @param[in] key key value to check its existence.
  17361. @return true if an element with specified @a key exists. If no such
  17362. element with such key is found or the JSON value is not an object,
  17363. false is returned.
  17364. @complexity Logarithmic in the size of the JSON object.
  17365. @liveexample{The following code shows an example for `contains()`.,contains}
  17366. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  17367. @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
  17368. @since version 3.6.0
  17369. */
  17370. template < typename KeyT, typename std::enable_if <
  17371. !std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int >::type = 0 >
  17372. bool contains(KeyT && key) const
  17373. {
  17374. return is_object() && m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  17375. }
  17376. /*!
  17377. @brief check the existence of an element in a JSON object given a JSON pointer
  17378. Check whether the given JSON pointer @a ptr can be resolved in the current
  17379. JSON value.
  17380. @note This method can be executed on any JSON value type.
  17381. @param[in] ptr JSON pointer to check its existence.
  17382. @return true if the JSON pointer can be resolved to a stored value, false
  17383. otherwise.
  17384. @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
  17385. @throw parse_error.106 if an array index begins with '0'
  17386. @throw parse_error.109 if an array index was not a number
  17387. @complexity Logarithmic in the size of the JSON object.
  17388. @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
  17389. @sa @ref contains(KeyT &&) const -- checks the existence of a key
  17390. @since version 3.7.0
  17391. */
  17392. bool contains(const json_pointer& ptr) const
  17393. {
  17394. return ptr.contains(this);
  17395. }
  17396. /// @}
  17397. ///////////////
  17398. // iterators //
  17399. ///////////////
  17400. /// @name iterators
  17401. /// @{
  17402. /*!
  17403. @brief returns an iterator to the first element
  17404. Returns an iterator to the first element.
  17405. @image html range-begin-end.svg "Illustration from cppreference.com"
  17406. @return iterator to the first element
  17407. @complexity Constant.
  17408. @requirement This function helps `basic_json` satisfying the
  17409. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17410. requirements:
  17411. - The complexity is constant.
  17412. @liveexample{The following code shows an example for `begin()`.,begin}
  17413. @sa @ref cbegin() -- returns a const iterator to the beginning
  17414. @sa @ref end() -- returns an iterator to the end
  17415. @sa @ref cend() -- returns a const iterator to the end
  17416. @since version 1.0.0
  17417. */
  17418. iterator begin() noexcept
  17419. {
  17420. iterator result(this);
  17421. result.set_begin();
  17422. return result;
  17423. }
  17424. /*!
  17425. @copydoc basic_json::cbegin()
  17426. */
  17427. const_iterator begin() const noexcept
  17428. {
  17429. return cbegin();
  17430. }
  17431. /*!
  17432. @brief returns a const iterator to the first element
  17433. Returns a const iterator to the first element.
  17434. @image html range-begin-end.svg "Illustration from cppreference.com"
  17435. @return const iterator to the first element
  17436. @complexity Constant.
  17437. @requirement This function helps `basic_json` satisfying the
  17438. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17439. requirements:
  17440. - The complexity is constant.
  17441. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  17442. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  17443. @sa @ref begin() -- returns an iterator to the beginning
  17444. @sa @ref end() -- returns an iterator to the end
  17445. @sa @ref cend() -- returns a const iterator to the end
  17446. @since version 1.0.0
  17447. */
  17448. const_iterator cbegin() const noexcept
  17449. {
  17450. const_iterator result(this);
  17451. result.set_begin();
  17452. return result;
  17453. }
  17454. /*!
  17455. @brief returns an iterator to one past the last element
  17456. Returns an iterator to one past the last element.
  17457. @image html range-begin-end.svg "Illustration from cppreference.com"
  17458. @return iterator one past the last element
  17459. @complexity Constant.
  17460. @requirement This function helps `basic_json` satisfying the
  17461. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17462. requirements:
  17463. - The complexity is constant.
  17464. @liveexample{The following code shows an example for `end()`.,end}
  17465. @sa @ref cend() -- returns a const iterator to the end
  17466. @sa @ref begin() -- returns an iterator to the beginning
  17467. @sa @ref cbegin() -- returns a const iterator to the beginning
  17468. @since version 1.0.0
  17469. */
  17470. iterator end() noexcept
  17471. {
  17472. iterator result(this);
  17473. result.set_end();
  17474. return result;
  17475. }
  17476. /*!
  17477. @copydoc basic_json::cend()
  17478. */
  17479. const_iterator end() const noexcept
  17480. {
  17481. return cend();
  17482. }
  17483. /*!
  17484. @brief returns a const iterator to one past the last element
  17485. Returns a const iterator to one past the last element.
  17486. @image html range-begin-end.svg "Illustration from cppreference.com"
  17487. @return const iterator one past the last element
  17488. @complexity Constant.
  17489. @requirement This function helps `basic_json` satisfying the
  17490. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17491. requirements:
  17492. - The complexity is constant.
  17493. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  17494. @liveexample{The following code shows an example for `cend()`.,cend}
  17495. @sa @ref end() -- returns an iterator to the end
  17496. @sa @ref begin() -- returns an iterator to the beginning
  17497. @sa @ref cbegin() -- returns a const iterator to the beginning
  17498. @since version 1.0.0
  17499. */
  17500. const_iterator cend() const noexcept
  17501. {
  17502. const_iterator result(this);
  17503. result.set_end();
  17504. return result;
  17505. }
  17506. /*!
  17507. @brief returns an iterator to the reverse-beginning
  17508. Returns an iterator to the reverse-beginning; that is, the last element.
  17509. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17510. @complexity Constant.
  17511. @requirement This function helps `basic_json` satisfying the
  17512. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17513. requirements:
  17514. - The complexity is constant.
  17515. - Has the semantics of `reverse_iterator(end())`.
  17516. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  17517. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17518. @sa @ref rend() -- returns a reverse iterator to the end
  17519. @sa @ref crend() -- returns a const reverse iterator to the end
  17520. @since version 1.0.0
  17521. */
  17522. reverse_iterator rbegin() noexcept
  17523. {
  17524. return reverse_iterator(end());
  17525. }
  17526. /*!
  17527. @copydoc basic_json::crbegin()
  17528. */
  17529. const_reverse_iterator rbegin() const noexcept
  17530. {
  17531. return crbegin();
  17532. }
  17533. /*!
  17534. @brief returns an iterator to the reverse-end
  17535. Returns an iterator to the reverse-end; that is, one before the first
  17536. element.
  17537. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17538. @complexity Constant.
  17539. @requirement This function helps `basic_json` satisfying the
  17540. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17541. requirements:
  17542. - The complexity is constant.
  17543. - Has the semantics of `reverse_iterator(begin())`.
  17544. @liveexample{The following code shows an example for `rend()`.,rend}
  17545. @sa @ref crend() -- returns a const reverse iterator to the end
  17546. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17547. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17548. @since version 1.0.0
  17549. */
  17550. reverse_iterator rend() noexcept
  17551. {
  17552. return reverse_iterator(begin());
  17553. }
  17554. /*!
  17555. @copydoc basic_json::crend()
  17556. */
  17557. const_reverse_iterator rend() const noexcept
  17558. {
  17559. return crend();
  17560. }
  17561. /*!
  17562. @brief returns a const reverse iterator to the last element
  17563. Returns a const iterator to the reverse-beginning; that is, the last
  17564. element.
  17565. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17566. @complexity Constant.
  17567. @requirement This function helps `basic_json` satisfying the
  17568. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17569. requirements:
  17570. - The complexity is constant.
  17571. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  17572. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  17573. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17574. @sa @ref rend() -- returns a reverse iterator to the end
  17575. @sa @ref crend() -- returns a const reverse iterator to the end
  17576. @since version 1.0.0
  17577. */
  17578. const_reverse_iterator crbegin() const noexcept
  17579. {
  17580. return const_reverse_iterator(cend());
  17581. }
  17582. /*!
  17583. @brief returns a const reverse iterator to one before the first
  17584. Returns a const reverse iterator to the reverse-end; that is, one before
  17585. the first element.
  17586. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  17587. @complexity Constant.
  17588. @requirement This function helps `basic_json` satisfying the
  17589. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  17590. requirements:
  17591. - The complexity is constant.
  17592. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  17593. @liveexample{The following code shows an example for `crend()`.,crend}
  17594. @sa @ref rend() -- returns a reverse iterator to the end
  17595. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  17596. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  17597. @since version 1.0.0
  17598. */
  17599. const_reverse_iterator crend() const noexcept
  17600. {
  17601. return const_reverse_iterator(cbegin());
  17602. }
  17603. public:
  17604. /*!
  17605. @brief wrapper to access iterator member functions in range-based for
  17606. This function allows to access @ref iterator::key() and @ref
  17607. iterator::value() during range-based for loops. In these loops, a
  17608. reference to the JSON values is returned, so there is no access to the
  17609. underlying iterator.
  17610. For loop without iterator_wrapper:
  17611. @code{cpp}
  17612. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17613. {
  17614. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17615. }
  17616. @endcode
  17617. Range-based for loop without iterator proxy:
  17618. @code{cpp}
  17619. for (auto it : j_object)
  17620. {
  17621. // "it" is of type json::reference and has no key() member
  17622. std::cout << "value: " << it << '\n';
  17623. }
  17624. @endcode
  17625. Range-based for loop with iterator proxy:
  17626. @code{cpp}
  17627. for (auto it : json::iterator_wrapper(j_object))
  17628. {
  17629. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17630. }
  17631. @endcode
  17632. @note When iterating over an array, `key()` will return the index of the
  17633. element as string (see example).
  17634. @param[in] ref reference to a JSON value
  17635. @return iteration proxy object wrapping @a ref with an interface to use in
  17636. range-based for loops
  17637. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  17638. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17639. changes in the JSON value.
  17640. @complexity Constant.
  17641. @note The name of this function is not yet final and may change in the
  17642. future.
  17643. @deprecated This stream operator is deprecated and will be removed in
  17644. future 4.0.0 of the library. Please use @ref items() instead;
  17645. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  17646. */
  17647. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  17648. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  17649. {
  17650. return ref.items();
  17651. }
  17652. /*!
  17653. @copydoc iterator_wrapper(reference)
  17654. */
  17655. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items())
  17656. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  17657. {
  17658. return ref.items();
  17659. }
  17660. /*!
  17661. @brief helper to access iterator member functions in range-based for
  17662. This function allows to access @ref iterator::key() and @ref
  17663. iterator::value() during range-based for loops. In these loops, a
  17664. reference to the JSON values is returned, so there is no access to the
  17665. underlying iterator.
  17666. For loop without `items()` function:
  17667. @code{cpp}
  17668. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  17669. {
  17670. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  17671. }
  17672. @endcode
  17673. Range-based for loop without `items()` function:
  17674. @code{cpp}
  17675. for (auto it : j_object)
  17676. {
  17677. // "it" is of type json::reference and has no key() member
  17678. std::cout << "value: " << it << '\n';
  17679. }
  17680. @endcode
  17681. Range-based for loop with `items()` function:
  17682. @code{cpp}
  17683. for (auto& el : j_object.items())
  17684. {
  17685. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  17686. }
  17687. @endcode
  17688. The `items()` function also allows to use
  17689. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  17690. (C++17):
  17691. @code{cpp}
  17692. for (auto& [key, val] : j_object.items())
  17693. {
  17694. std::cout << "key: " << key << ", value:" << val << '\n';
  17695. }
  17696. @endcode
  17697. @note When iterating over an array, `key()` will return the index of the
  17698. element as string (see example). For primitive types (e.g., numbers),
  17699. `key()` returns an empty string.
  17700. @warning Using `items()` on temporary objects is dangerous. Make sure the
  17701. object's lifetime exeeds the iteration. See
  17702. <https://github.com/nlohmann/json/issues/2040> for more
  17703. information.
  17704. @return iteration proxy object wrapping @a ref with an interface to use in
  17705. range-based for loops
  17706. @liveexample{The following code shows how the function is used.,items}
  17707. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  17708. changes in the JSON value.
  17709. @complexity Constant.
  17710. @since version 3.1.0, structured bindings support since 3.5.0.
  17711. */
  17712. iteration_proxy<iterator> items() noexcept
  17713. {
  17714. return iteration_proxy<iterator>(*this);
  17715. }
  17716. /*!
  17717. @copydoc items()
  17718. */
  17719. iteration_proxy<const_iterator> items() const noexcept
  17720. {
  17721. return iteration_proxy<const_iterator>(*this);
  17722. }
  17723. /// @}
  17724. //////////////
  17725. // capacity //
  17726. //////////////
  17727. /// @name capacity
  17728. /// @{
  17729. /*!
  17730. @brief checks whether the container is empty.
  17731. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  17732. @return The return value depends on the different types and is
  17733. defined as follows:
  17734. Value type | return value
  17735. ----------- | -------------
  17736. null | `true`
  17737. boolean | `false`
  17738. string | `false`
  17739. number | `false`
  17740. binary | `false`
  17741. object | result of function `object_t::empty()`
  17742. array | result of function `array_t::empty()`
  17743. @liveexample{The following code uses `empty()` to check if a JSON
  17744. object contains any elements.,empty}
  17745. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17746. the Container concept; that is, their `empty()` functions have constant
  17747. complexity.
  17748. @iterators No changes.
  17749. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17750. @note This function does not return whether a string stored as JSON value
  17751. is empty - it returns whether the JSON container itself is empty which is
  17752. false in the case of a string.
  17753. @requirement This function helps `basic_json` satisfying the
  17754. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17755. requirements:
  17756. - The complexity is constant.
  17757. - Has the semantics of `begin() == end()`.
  17758. @sa @ref size() -- returns the number of elements
  17759. @since version 1.0.0
  17760. */
  17761. bool empty() const noexcept
  17762. {
  17763. switch (m_type)
  17764. {
  17765. case value_t::null:
  17766. {
  17767. // null values are empty
  17768. return true;
  17769. }
  17770. case value_t::array:
  17771. {
  17772. // delegate call to array_t::empty()
  17773. return m_value.array->empty();
  17774. }
  17775. case value_t::object:
  17776. {
  17777. // delegate call to object_t::empty()
  17778. return m_value.object->empty();
  17779. }
  17780. default:
  17781. {
  17782. // all other types are nonempty
  17783. return false;
  17784. }
  17785. }
  17786. }
  17787. /*!
  17788. @brief returns the number of elements
  17789. Returns the number of elements in a JSON value.
  17790. @return The return value depends on the different types and is
  17791. defined as follows:
  17792. Value type | return value
  17793. ----------- | -------------
  17794. null | `0`
  17795. boolean | `1`
  17796. string | `1`
  17797. number | `1`
  17798. binary | `1`
  17799. object | result of function object_t::size()
  17800. array | result of function array_t::size()
  17801. @liveexample{The following code calls `size()` on the different value
  17802. types.,size}
  17803. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17804. the Container concept; that is, their size() functions have constant
  17805. complexity.
  17806. @iterators No changes.
  17807. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17808. @note This function does not return the length of a string stored as JSON
  17809. value - it returns the number of elements in the JSON value which is 1 in
  17810. the case of a string.
  17811. @requirement This function helps `basic_json` satisfying the
  17812. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17813. requirements:
  17814. - The complexity is constant.
  17815. - Has the semantics of `std::distance(begin(), end())`.
  17816. @sa @ref empty() -- checks whether the container is empty
  17817. @sa @ref max_size() -- returns the maximal number of elements
  17818. @since version 1.0.0
  17819. */
  17820. size_type size() const noexcept
  17821. {
  17822. switch (m_type)
  17823. {
  17824. case value_t::null:
  17825. {
  17826. // null values are empty
  17827. return 0;
  17828. }
  17829. case value_t::array:
  17830. {
  17831. // delegate call to array_t::size()
  17832. return m_value.array->size();
  17833. }
  17834. case value_t::object:
  17835. {
  17836. // delegate call to object_t::size()
  17837. return m_value.object->size();
  17838. }
  17839. default:
  17840. {
  17841. // all other types have size 1
  17842. return 1;
  17843. }
  17844. }
  17845. }
  17846. /*!
  17847. @brief returns the maximum possible number of elements
  17848. Returns the maximum number of elements a JSON value is able to hold due to
  17849. system or library implementation limitations, i.e. `std::distance(begin(),
  17850. end())` for the JSON value.
  17851. @return The return value depends on the different types and is
  17852. defined as follows:
  17853. Value type | return value
  17854. ----------- | -------------
  17855. null | `0` (same as `size()`)
  17856. boolean | `1` (same as `size()`)
  17857. string | `1` (same as `size()`)
  17858. number | `1` (same as `size()`)
  17859. binary | `1` (same as `size()`)
  17860. object | result of function `object_t::max_size()`
  17861. array | result of function `array_t::max_size()`
  17862. @liveexample{The following code calls `max_size()` on the different value
  17863. types. Note the output is implementation specific.,max_size}
  17864. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  17865. the Container concept; that is, their `max_size()` functions have constant
  17866. complexity.
  17867. @iterators No changes.
  17868. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17869. @requirement This function helps `basic_json` satisfying the
  17870. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  17871. requirements:
  17872. - The complexity is constant.
  17873. - Has the semantics of returning `b.size()` where `b` is the largest
  17874. possible JSON value.
  17875. @sa @ref size() -- returns the number of elements
  17876. @since version 1.0.0
  17877. */
  17878. size_type max_size() const noexcept
  17879. {
  17880. switch (m_type)
  17881. {
  17882. case value_t::array:
  17883. {
  17884. // delegate call to array_t::max_size()
  17885. return m_value.array->max_size();
  17886. }
  17887. case value_t::object:
  17888. {
  17889. // delegate call to object_t::max_size()
  17890. return m_value.object->max_size();
  17891. }
  17892. default:
  17893. {
  17894. // all other types have max_size() == size()
  17895. return size();
  17896. }
  17897. }
  17898. }
  17899. /// @}
  17900. ///////////////
  17901. // modifiers //
  17902. ///////////////
  17903. /// @name modifiers
  17904. /// @{
  17905. /*!
  17906. @brief clears the contents
  17907. Clears the content of a JSON value and resets it to the default value as
  17908. if @ref basic_json(value_t) would have been called with the current value
  17909. type from @ref type():
  17910. Value type | initial value
  17911. ----------- | -------------
  17912. null | `null`
  17913. boolean | `false`
  17914. string | `""`
  17915. number | `0`
  17916. binary | An empty byte vector
  17917. object | `{}`
  17918. array | `[]`
  17919. @post Has the same effect as calling
  17920. @code {.cpp}
  17921. *this = basic_json(type());
  17922. @endcode
  17923. @liveexample{The example below shows the effect of `clear()` to different
  17924. JSON types.,clear}
  17925. @complexity Linear in the size of the JSON value.
  17926. @iterators All iterators, pointers and references related to this container
  17927. are invalidated.
  17928. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  17929. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  17930. same value than calling `clear()`
  17931. @since version 1.0.0
  17932. */
  17933. void clear() noexcept
  17934. {
  17935. switch (m_type)
  17936. {
  17937. case value_t::number_integer:
  17938. {
  17939. m_value.number_integer = 0;
  17940. break;
  17941. }
  17942. case value_t::number_unsigned:
  17943. {
  17944. m_value.number_unsigned = 0;
  17945. break;
  17946. }
  17947. case value_t::number_float:
  17948. {
  17949. m_value.number_float = 0.0;
  17950. break;
  17951. }
  17952. case value_t::boolean:
  17953. {
  17954. m_value.boolean = false;
  17955. break;
  17956. }
  17957. case value_t::string:
  17958. {
  17959. m_value.string->clear();
  17960. break;
  17961. }
  17962. case value_t::binary:
  17963. {
  17964. m_value.binary->clear();
  17965. break;
  17966. }
  17967. case value_t::array:
  17968. {
  17969. m_value.array->clear();
  17970. break;
  17971. }
  17972. case value_t::object:
  17973. {
  17974. m_value.object->clear();
  17975. break;
  17976. }
  17977. default:
  17978. break;
  17979. }
  17980. }
  17981. /*!
  17982. @brief add an object to an array
  17983. Appends the given element @a val to the end of the JSON value. If the
  17984. function is called on a JSON null value, an empty array is created before
  17985. appending @a val.
  17986. @param[in] val the value to add to the JSON array
  17987. @throw type_error.308 when called on a type other than JSON array or
  17988. null; example: `"cannot use push_back() with number"`
  17989. @complexity Amortized constant.
  17990. @liveexample{The example shows how `push_back()` and `+=` can be used to
  17991. add elements to a JSON array. Note how the `null` value was silently
  17992. converted to a JSON array.,push_back}
  17993. @since version 1.0.0
  17994. */
  17995. void push_back(basic_json&& val)
  17996. {
  17997. // push_back only works for null objects or arrays
  17998. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  17999. {
  18000. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18001. }
  18002. // transform null object into an array
  18003. if (is_null())
  18004. {
  18005. m_type = value_t::array;
  18006. m_value = value_t::array;
  18007. assert_invariant();
  18008. }
  18009. // add element to array (move semantics)
  18010. m_value.array->push_back(std::move(val));
  18011. // if val is moved from, basic_json move constructor marks it null so we do not call the destructor
  18012. }
  18013. /*!
  18014. @brief add an object to an array
  18015. @copydoc push_back(basic_json&&)
  18016. */
  18017. reference operator+=(basic_json&& val)
  18018. {
  18019. push_back(std::move(val));
  18020. return *this;
  18021. }
  18022. /*!
  18023. @brief add an object to an array
  18024. @copydoc push_back(basic_json&&)
  18025. */
  18026. void push_back(const basic_json& val)
  18027. {
  18028. // push_back only works for null objects or arrays
  18029. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  18030. {
  18031. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18032. }
  18033. // transform null object into an array
  18034. if (is_null())
  18035. {
  18036. m_type = value_t::array;
  18037. m_value = value_t::array;
  18038. assert_invariant();
  18039. }
  18040. // add element to array
  18041. m_value.array->push_back(val);
  18042. }
  18043. /*!
  18044. @brief add an object to an array
  18045. @copydoc push_back(basic_json&&)
  18046. */
  18047. reference operator+=(const basic_json& val)
  18048. {
  18049. push_back(val);
  18050. return *this;
  18051. }
  18052. /*!
  18053. @brief add an object to an object
  18054. Inserts the given element @a val to the JSON object. If the function is
  18055. called on a JSON null value, an empty object is created before inserting
  18056. @a val.
  18057. @param[in] val the value to add to the JSON object
  18058. @throw type_error.308 when called on a type other than JSON object or
  18059. null; example: `"cannot use push_back() with number"`
  18060. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  18061. @liveexample{The example shows how `push_back()` and `+=` can be used to
  18062. add elements to a JSON object. Note how the `null` value was silently
  18063. converted to a JSON object.,push_back__object_t__value}
  18064. @since version 1.0.0
  18065. */
  18066. void push_back(const typename object_t::value_type& val)
  18067. {
  18068. // push_back only works for null objects or objects
  18069. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  18070. {
  18071. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  18072. }
  18073. // transform null object into an object
  18074. if (is_null())
  18075. {
  18076. m_type = value_t::object;
  18077. m_value = value_t::object;
  18078. assert_invariant();
  18079. }
  18080. // add element to array
  18081. m_value.object->insert(val);
  18082. }
  18083. /*!
  18084. @brief add an object to an object
  18085. @copydoc push_back(const typename object_t::value_type&)
  18086. */
  18087. reference operator+=(const typename object_t::value_type& val)
  18088. {
  18089. push_back(val);
  18090. return *this;
  18091. }
  18092. /*!
  18093. @brief add an object to an object
  18094. This function allows to use `push_back` with an initializer list. In case
  18095. 1. the current value is an object,
  18096. 2. the initializer list @a init contains only two elements, and
  18097. 3. the first element of @a init is a string,
  18098. @a init is converted into an object element and added using
  18099. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  18100. is converted to a JSON value and added using @ref push_back(basic_json&&).
  18101. @param[in] init an initializer list
  18102. @complexity Linear in the size of the initializer list @a init.
  18103. @note This function is required to resolve an ambiguous overload error,
  18104. because pairs like `{"key", "value"}` can be both interpreted as
  18105. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  18106. https://github.com/nlohmann/json/issues/235 for more information.
  18107. @liveexample{The example shows how initializer lists are treated as
  18108. objects when possible.,push_back__initializer_list}
  18109. */
  18110. void push_back(initializer_list_t init)
  18111. {
  18112. if (is_object() && init.size() == 2 && (*init.begin())->is_string())
  18113. {
  18114. basic_json&& key = init.begin()->moved_or_copied();
  18115. push_back(typename object_t::value_type(
  18116. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  18117. }
  18118. else
  18119. {
  18120. push_back(basic_json(init));
  18121. }
  18122. }
  18123. /*!
  18124. @brief add an object to an object
  18125. @copydoc push_back(initializer_list_t)
  18126. */
  18127. reference operator+=(initializer_list_t init)
  18128. {
  18129. push_back(init);
  18130. return *this;
  18131. }
  18132. /*!
  18133. @brief add an object to an array
  18134. Creates a JSON value from the passed parameters @a args to the end of the
  18135. JSON value. If the function is called on a JSON null value, an empty array
  18136. is created before appending the value created from @a args.
  18137. @param[in] args arguments to forward to a constructor of @ref basic_json
  18138. @tparam Args compatible types to create a @ref basic_json object
  18139. @return reference to the inserted element
  18140. @throw type_error.311 when called on a type other than JSON array or
  18141. null; example: `"cannot use emplace_back() with number"`
  18142. @complexity Amortized constant.
  18143. @liveexample{The example shows how `push_back()` can be used to add
  18144. elements to a JSON array. Note how the `null` value was silently converted
  18145. to a JSON array.,emplace_back}
  18146. @since version 2.0.8, returns reference since 3.7.0
  18147. */
  18148. template<class... Args>
  18149. reference emplace_back(Args&& ... args)
  18150. {
  18151. // emplace_back only works for null objects or arrays
  18152. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array())))
  18153. {
  18154. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  18155. }
  18156. // transform null object into an array
  18157. if (is_null())
  18158. {
  18159. m_type = value_t::array;
  18160. m_value = value_t::array;
  18161. assert_invariant();
  18162. }
  18163. // add element to array (perfect forwarding)
  18164. #ifdef JSON_HAS_CPP_17
  18165. return m_value.array->emplace_back(std::forward<Args>(args)...);
  18166. #else
  18167. m_value.array->emplace_back(std::forward<Args>(args)...);
  18168. return m_value.array->back();
  18169. #endif
  18170. }
  18171. /*!
  18172. @brief add an object to an object if key does not exist
  18173. Inserts a new element into a JSON object constructed in-place with the
  18174. given @a args if there is no element with the key in the container. If the
  18175. function is called on a JSON null value, an empty object is created before
  18176. appending the value created from @a args.
  18177. @param[in] args arguments to forward to a constructor of @ref basic_json
  18178. @tparam Args compatible types to create a @ref basic_json object
  18179. @return a pair consisting of an iterator to the inserted element, or the
  18180. already-existing element if no insertion happened, and a bool
  18181. denoting whether the insertion took place.
  18182. @throw type_error.311 when called on a type other than JSON object or
  18183. null; example: `"cannot use emplace() with number"`
  18184. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  18185. @liveexample{The example shows how `emplace()` can be used to add elements
  18186. to a JSON object. Note how the `null` value was silently converted to a
  18187. JSON object. Further note how no value is added if there was already one
  18188. value stored with the same key.,emplace}
  18189. @since version 2.0.8
  18190. */
  18191. template<class... Args>
  18192. std::pair<iterator, bool> emplace(Args&& ... args)
  18193. {
  18194. // emplace only works for null objects or arrays
  18195. if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object())))
  18196. {
  18197. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  18198. }
  18199. // transform null object into an object
  18200. if (is_null())
  18201. {
  18202. m_type = value_t::object;
  18203. m_value = value_t::object;
  18204. assert_invariant();
  18205. }
  18206. // add element to array (perfect forwarding)
  18207. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  18208. // create result iterator and set iterator to the result of emplace
  18209. auto it = begin();
  18210. it.m_it.object_iterator = res.first;
  18211. // return pair of iterator and boolean
  18212. return {it, res.second};
  18213. }
  18214. /// Helper for insertion of an iterator
  18215. /// @note: This uses std::distance to support GCC 4.8,
  18216. /// see https://github.com/nlohmann/json/pull/1257
  18217. template<typename... Args>
  18218. iterator insert_iterator(const_iterator pos, Args&& ... args)
  18219. {
  18220. iterator result(this);
  18221. JSON_ASSERT(m_value.array != nullptr);
  18222. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  18223. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  18224. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  18225. // This could have been written as:
  18226. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  18227. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  18228. return result;
  18229. }
  18230. /*!
  18231. @brief inserts element
  18232. Inserts element @a val before iterator @a pos.
  18233. @param[in] pos iterator before which the content will be inserted; may be
  18234. the end() iterator
  18235. @param[in] val element to insert
  18236. @return iterator pointing to the inserted @a val.
  18237. @throw type_error.309 if called on JSON values other than arrays;
  18238. example: `"cannot use insert() with string"`
  18239. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18240. example: `"iterator does not fit current value"`
  18241. @complexity Constant plus linear in the distance between @a pos and end of
  18242. the container.
  18243. @liveexample{The example shows how `insert()` is used.,insert}
  18244. @since version 1.0.0
  18245. */
  18246. iterator insert(const_iterator pos, const basic_json& val)
  18247. {
  18248. // insert only works for arrays
  18249. if (JSON_HEDLEY_LIKELY(is_array()))
  18250. {
  18251. // check if iterator pos fits to this JSON value
  18252. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18253. {
  18254. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18255. }
  18256. // insert to array and return iterator
  18257. return insert_iterator(pos, val);
  18258. }
  18259. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18260. }
  18261. /*!
  18262. @brief inserts element
  18263. @copydoc insert(const_iterator, const basic_json&)
  18264. */
  18265. iterator insert(const_iterator pos, basic_json&& val)
  18266. {
  18267. return insert(pos, val);
  18268. }
  18269. /*!
  18270. @brief inserts elements
  18271. Inserts @a cnt copies of @a val before iterator @a pos.
  18272. @param[in] pos iterator before which the content will be inserted; may be
  18273. the end() iterator
  18274. @param[in] cnt number of copies of @a val to insert
  18275. @param[in] val element to insert
  18276. @return iterator pointing to the first element inserted, or @a pos if
  18277. `cnt==0`
  18278. @throw type_error.309 if called on JSON values other than arrays; example:
  18279. `"cannot use insert() with string"`
  18280. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18281. example: `"iterator does not fit current value"`
  18282. @complexity Linear in @a cnt plus linear in the distance between @a pos
  18283. and end of the container.
  18284. @liveexample{The example shows how `insert()` is used.,insert__count}
  18285. @since version 1.0.0
  18286. */
  18287. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  18288. {
  18289. // insert only works for arrays
  18290. if (JSON_HEDLEY_LIKELY(is_array()))
  18291. {
  18292. // check if iterator pos fits to this JSON value
  18293. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18294. {
  18295. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18296. }
  18297. // insert to array and return iterator
  18298. return insert_iterator(pos, cnt, val);
  18299. }
  18300. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18301. }
  18302. /*!
  18303. @brief inserts elements
  18304. Inserts elements from range `[first, last)` before iterator @a pos.
  18305. @param[in] pos iterator before which the content will be inserted; may be
  18306. the end() iterator
  18307. @param[in] first begin of the range of elements to insert
  18308. @param[in] last end of the range of elements to insert
  18309. @throw type_error.309 if called on JSON values other than arrays; example:
  18310. `"cannot use insert() with string"`
  18311. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18312. example: `"iterator does not fit current value"`
  18313. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18314. same JSON value; example: `"iterators do not fit"`
  18315. @throw invalid_iterator.211 if @a first or @a last are iterators into
  18316. container for which insert is called; example: `"passed iterators may not
  18317. belong to container"`
  18318. @return iterator pointing to the first element inserted, or @a pos if
  18319. `first==last`
  18320. @complexity Linear in `std::distance(first, last)` plus linear in the
  18321. distance between @a pos and end of the container.
  18322. @liveexample{The example shows how `insert()` is used.,insert__range}
  18323. @since version 1.0.0
  18324. */
  18325. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  18326. {
  18327. // insert only works for arrays
  18328. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  18329. {
  18330. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18331. }
  18332. // check if iterator pos fits to this JSON value
  18333. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18334. {
  18335. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18336. }
  18337. // check if range iterators belong to the same JSON object
  18338. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18339. {
  18340. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18341. }
  18342. if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
  18343. {
  18344. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  18345. }
  18346. // insert to array and return iterator
  18347. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  18348. }
  18349. /*!
  18350. @brief inserts elements
  18351. Inserts elements from initializer list @a ilist before iterator @a pos.
  18352. @param[in] pos iterator before which the content will be inserted; may be
  18353. the end() iterator
  18354. @param[in] ilist initializer list to insert the values from
  18355. @throw type_error.309 if called on JSON values other than arrays; example:
  18356. `"cannot use insert() with string"`
  18357. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  18358. example: `"iterator does not fit current value"`
  18359. @return iterator pointing to the first element inserted, or @a pos if
  18360. `ilist` is empty
  18361. @complexity Linear in `ilist.size()` plus linear in the distance between
  18362. @a pos and end of the container.
  18363. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  18364. @since version 1.0.0
  18365. */
  18366. iterator insert(const_iterator pos, initializer_list_t ilist)
  18367. {
  18368. // insert only works for arrays
  18369. if (JSON_HEDLEY_UNLIKELY(!is_array()))
  18370. {
  18371. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18372. }
  18373. // check if iterator pos fits to this JSON value
  18374. if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
  18375. {
  18376. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  18377. }
  18378. // insert to array and return iterator
  18379. return insert_iterator(pos, ilist.begin(), ilist.end());
  18380. }
  18381. /*!
  18382. @brief inserts elements
  18383. Inserts elements from range `[first, last)`.
  18384. @param[in] first begin of the range of elements to insert
  18385. @param[in] last end of the range of elements to insert
  18386. @throw type_error.309 if called on JSON values other than objects; example:
  18387. `"cannot use insert() with string"`
  18388. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18389. point to an object; example: `"iterators first and last must point to
  18390. objects"`
  18391. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18392. same JSON value; example: `"iterators do not fit"`
  18393. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  18394. of elements to insert.
  18395. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  18396. @since version 3.0.0
  18397. */
  18398. void insert(const_iterator first, const_iterator last)
  18399. {
  18400. // insert only works for objects
  18401. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18402. {
  18403. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  18404. }
  18405. // check if range iterators belong to the same JSON object
  18406. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18407. {
  18408. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18409. }
  18410. // passed iterators must belong to objects
  18411. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()))
  18412. {
  18413. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18414. }
  18415. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  18416. }
  18417. /*!
  18418. @brief updates a JSON object from another object, overwriting existing keys
  18419. Inserts all values from JSON object @a j and overwrites existing keys.
  18420. @param[in] j JSON object to read values from
  18421. @throw type_error.312 if called on JSON values other than objects; example:
  18422. `"cannot use update() with string"`
  18423. @complexity O(N*log(size() + N)), where N is the number of elements to
  18424. insert.
  18425. @liveexample{The example shows how `update()` is used.,update}
  18426. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18427. @since version 3.0.0
  18428. */
  18429. void update(const_reference j)
  18430. {
  18431. // implicitly convert null value to an empty object
  18432. if (is_null())
  18433. {
  18434. m_type = value_t::object;
  18435. m_value.object = create<object_t>();
  18436. assert_invariant();
  18437. }
  18438. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18439. {
  18440. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18441. }
  18442. if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
  18443. {
  18444. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  18445. }
  18446. for (auto it = j.cbegin(); it != j.cend(); ++it)
  18447. {
  18448. m_value.object->operator[](it.key()) = it.value();
  18449. }
  18450. }
  18451. /*!
  18452. @brief updates a JSON object from another object, overwriting existing keys
  18453. Inserts all values from from range `[first, last)` and overwrites existing
  18454. keys.
  18455. @param[in] first begin of the range of elements to insert
  18456. @param[in] last end of the range of elements to insert
  18457. @throw type_error.312 if called on JSON values other than objects; example:
  18458. `"cannot use update() with string"`
  18459. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  18460. point to an object; example: `"iterators first and last must point to
  18461. objects"`
  18462. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  18463. same JSON value; example: `"iterators do not fit"`
  18464. @complexity O(N*log(size() + N)), where N is the number of elements to
  18465. insert.
  18466. @liveexample{The example shows how `update()` is used__range.,update}
  18467. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  18468. @since version 3.0.0
  18469. */
  18470. void update(const_iterator first, const_iterator last)
  18471. {
  18472. // implicitly convert null value to an empty object
  18473. if (is_null())
  18474. {
  18475. m_type = value_t::object;
  18476. m_value.object = create<object_t>();
  18477. assert_invariant();
  18478. }
  18479. if (JSON_HEDLEY_UNLIKELY(!is_object()))
  18480. {
  18481. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  18482. }
  18483. // check if range iterators belong to the same JSON object
  18484. if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
  18485. {
  18486. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  18487. }
  18488. // passed iterators must belong to objects
  18489. if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object()
  18490. || !last.m_object->is_object()))
  18491. {
  18492. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  18493. }
  18494. for (auto it = first; it != last; ++it)
  18495. {
  18496. m_value.object->operator[](it.key()) = it.value();
  18497. }
  18498. }
  18499. /*!
  18500. @brief exchanges the values
  18501. Exchanges the contents of the JSON value with those of @a other. Does not
  18502. invoke any move, copy, or swap operations on individual elements. All
  18503. iterators and references remain valid. The past-the-end iterator is
  18504. invalidated.
  18505. @param[in,out] other JSON value to exchange the contents with
  18506. @complexity Constant.
  18507. @liveexample{The example below shows how JSON values can be swapped with
  18508. `swap()`.,swap__reference}
  18509. @since version 1.0.0
  18510. */
  18511. void swap(reference other) noexcept (
  18512. std::is_nothrow_move_constructible<value_t>::value&&
  18513. std::is_nothrow_move_assignable<value_t>::value&&
  18514. std::is_nothrow_move_constructible<json_value>::value&&
  18515. std::is_nothrow_move_assignable<json_value>::value
  18516. )
  18517. {
  18518. std::swap(m_type, other.m_type);
  18519. std::swap(m_value, other.m_value);
  18520. assert_invariant();
  18521. }
  18522. /*!
  18523. @brief exchanges the values
  18524. Exchanges the contents of the JSON value from @a left with those of @a right. Does not
  18525. invoke any move, copy, or swap operations on individual elements. All
  18526. iterators and references remain valid. The past-the-end iterator is
  18527. invalidated. implemented as a friend function callable via ADL.
  18528. @param[in,out] left JSON value to exchange the contents with
  18529. @param[in,out] right JSON value to exchange the contents with
  18530. @complexity Constant.
  18531. @liveexample{The example below shows how JSON values can be swapped with
  18532. `swap()`.,swap__reference}
  18533. @since version 1.0.0
  18534. */
  18535. friend void swap(reference left, reference right) noexcept (
  18536. std::is_nothrow_move_constructible<value_t>::value&&
  18537. std::is_nothrow_move_assignable<value_t>::value&&
  18538. std::is_nothrow_move_constructible<json_value>::value&&
  18539. std::is_nothrow_move_assignable<json_value>::value
  18540. )
  18541. {
  18542. left.swap(right);
  18543. }
  18544. /*!
  18545. @brief exchanges the values
  18546. Exchanges the contents of a JSON array with those of @a other. Does not
  18547. invoke any move, copy, or swap operations on individual elements. All
  18548. iterators and references remain valid. The past-the-end iterator is
  18549. invalidated.
  18550. @param[in,out] other array to exchange the contents with
  18551. @throw type_error.310 when JSON value is not an array; example: `"cannot
  18552. use swap() with string"`
  18553. @complexity Constant.
  18554. @liveexample{The example below shows how arrays can be swapped with
  18555. `swap()`.,swap__array_t}
  18556. @since version 1.0.0
  18557. */
  18558. void swap(array_t& other)
  18559. {
  18560. // swap only works for arrays
  18561. if (JSON_HEDLEY_LIKELY(is_array()))
  18562. {
  18563. std::swap(*(m_value.array), other);
  18564. }
  18565. else
  18566. {
  18567. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18568. }
  18569. }
  18570. /*!
  18571. @brief exchanges the values
  18572. Exchanges the contents of a JSON object with those of @a other. Does not
  18573. invoke any move, copy, or swap operations on individual elements. All
  18574. iterators and references remain valid. The past-the-end iterator is
  18575. invalidated.
  18576. @param[in,out] other object to exchange the contents with
  18577. @throw type_error.310 when JSON value is not an object; example:
  18578. `"cannot use swap() with string"`
  18579. @complexity Constant.
  18580. @liveexample{The example below shows how objects can be swapped with
  18581. `swap()`.,swap__object_t}
  18582. @since version 1.0.0
  18583. */
  18584. void swap(object_t& other)
  18585. {
  18586. // swap only works for objects
  18587. if (JSON_HEDLEY_LIKELY(is_object()))
  18588. {
  18589. std::swap(*(m_value.object), other);
  18590. }
  18591. else
  18592. {
  18593. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18594. }
  18595. }
  18596. /*!
  18597. @brief exchanges the values
  18598. Exchanges the contents of a JSON string with those of @a other. Does not
  18599. invoke any move, copy, or swap operations on individual elements. All
  18600. iterators and references remain valid. The past-the-end iterator is
  18601. invalidated.
  18602. @param[in,out] other string to exchange the contents with
  18603. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18604. use swap() with boolean"`
  18605. @complexity Constant.
  18606. @liveexample{The example below shows how strings can be swapped with
  18607. `swap()`.,swap__string_t}
  18608. @since version 1.0.0
  18609. */
  18610. void swap(string_t& other)
  18611. {
  18612. // swap only works for strings
  18613. if (JSON_HEDLEY_LIKELY(is_string()))
  18614. {
  18615. std::swap(*(m_value.string), other);
  18616. }
  18617. else
  18618. {
  18619. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18620. }
  18621. }
  18622. /*!
  18623. @brief exchanges the values
  18624. Exchanges the contents of a JSON string with those of @a other. Does not
  18625. invoke any move, copy, or swap operations on individual elements. All
  18626. iterators and references remain valid. The past-the-end iterator is
  18627. invalidated.
  18628. @param[in,out] other binary to exchange the contents with
  18629. @throw type_error.310 when JSON value is not a string; example: `"cannot
  18630. use swap() with boolean"`
  18631. @complexity Constant.
  18632. @liveexample{The example below shows how strings can be swapped with
  18633. `swap()`.,swap__binary_t}
  18634. @since version 3.8.0
  18635. */
  18636. void swap(binary_t& other)
  18637. {
  18638. // swap only works for strings
  18639. if (JSON_HEDLEY_LIKELY(is_binary()))
  18640. {
  18641. std::swap(*(m_value.binary), other);
  18642. }
  18643. else
  18644. {
  18645. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18646. }
  18647. }
  18648. /// @copydoc swap(binary_t)
  18649. void swap(typename binary_t::container_type& other)
  18650. {
  18651. // swap only works for strings
  18652. if (JSON_HEDLEY_LIKELY(is_binary()))
  18653. {
  18654. std::swap(*(m_value.binary), other);
  18655. }
  18656. else
  18657. {
  18658. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  18659. }
  18660. }
  18661. /// @}
  18662. public:
  18663. //////////////////////////////////////////
  18664. // lexicographical comparison operators //
  18665. //////////////////////////////////////////
  18666. /// @name lexicographical comparison operators
  18667. /// @{
  18668. /*!
  18669. @brief comparison: equal
  18670. Compares two JSON values for equality according to the following rules:
  18671. - Two JSON values are equal if (1) they are from the same type and (2)
  18672. their stored values are the same according to their respective
  18673. `operator==`.
  18674. - Integer and floating-point numbers are automatically converted before
  18675. comparison. Note that two NaN values are always treated as unequal.
  18676. - Two JSON null values are equal.
  18677. @note Floating-point inside JSON values numbers are compared with
  18678. `json::number_float_t::operator==` which is `double::operator==` by
  18679. default. To compare floating-point while respecting an epsilon, an alternative
  18680. [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39)
  18681. could be used, for instance
  18682. @code {.cpp}
  18683. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  18684. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  18685. {
  18686. return std::abs(a - b) <= epsilon;
  18687. }
  18688. @endcode
  18689. Or you can self-defined operator equal function like this:
  18690. @code {.cpp}
  18691. bool my_equal(const_reference lhs, const_reference rhs) {
  18692. const auto lhs_type lhs.type();
  18693. const auto rhs_type rhs.type();
  18694. if (lhs_type == rhs_type) {
  18695. switch(lhs_type)
  18696. // self_defined case
  18697. case value_t::number_float:
  18698. return std::abs(lhs - rhs) <= std::numeric_limits<float>::epsilon();
  18699. // other cases remain the same with the original
  18700. ...
  18701. }
  18702. ...
  18703. }
  18704. @endcode
  18705. @note NaN values never compare equal to themselves or to other NaN values.
  18706. @param[in] lhs first JSON value to consider
  18707. @param[in] rhs second JSON value to consider
  18708. @return whether the values @a lhs and @a rhs are equal
  18709. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18710. @complexity Linear.
  18711. @liveexample{The example demonstrates comparing several JSON
  18712. types.,operator__equal}
  18713. @since version 1.0.0
  18714. */
  18715. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  18716. {
  18717. const auto lhs_type = lhs.type();
  18718. const auto rhs_type = rhs.type();
  18719. if (lhs_type == rhs_type)
  18720. {
  18721. switch (lhs_type)
  18722. {
  18723. case value_t::array:
  18724. return *lhs.m_value.array == *rhs.m_value.array;
  18725. case value_t::object:
  18726. return *lhs.m_value.object == *rhs.m_value.object;
  18727. case value_t::null:
  18728. return true;
  18729. case value_t::string:
  18730. return *lhs.m_value.string == *rhs.m_value.string;
  18731. case value_t::boolean:
  18732. return lhs.m_value.boolean == rhs.m_value.boolean;
  18733. case value_t::number_integer:
  18734. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  18735. case value_t::number_unsigned:
  18736. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  18737. case value_t::number_float:
  18738. return lhs.m_value.number_float == rhs.m_value.number_float;
  18739. case value_t::binary:
  18740. return *lhs.m_value.binary == *rhs.m_value.binary;
  18741. default:
  18742. return false;
  18743. }
  18744. }
  18745. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  18746. {
  18747. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  18748. }
  18749. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  18750. {
  18751. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  18752. }
  18753. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  18754. {
  18755. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  18756. }
  18757. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  18758. {
  18759. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18760. }
  18761. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  18762. {
  18763. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  18764. }
  18765. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  18766. {
  18767. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18768. }
  18769. return false;
  18770. }
  18771. /*!
  18772. @brief comparison: equal
  18773. @copydoc operator==(const_reference, const_reference)
  18774. */
  18775. template<typename ScalarType, typename std::enable_if<
  18776. std::is_scalar<ScalarType>::value, int>::type = 0>
  18777. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  18778. {
  18779. return lhs == basic_json(rhs);
  18780. }
  18781. /*!
  18782. @brief comparison: equal
  18783. @copydoc operator==(const_reference, const_reference)
  18784. */
  18785. template<typename ScalarType, typename std::enable_if<
  18786. std::is_scalar<ScalarType>::value, int>::type = 0>
  18787. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  18788. {
  18789. return basic_json(lhs) == rhs;
  18790. }
  18791. /*!
  18792. @brief comparison: not equal
  18793. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  18794. @param[in] lhs first JSON value to consider
  18795. @param[in] rhs second JSON value to consider
  18796. @return whether the values @a lhs and @a rhs are not equal
  18797. @complexity Linear.
  18798. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18799. @liveexample{The example demonstrates comparing several JSON
  18800. types.,operator__notequal}
  18801. @since version 1.0.0
  18802. */
  18803. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  18804. {
  18805. return !(lhs == rhs);
  18806. }
  18807. /*!
  18808. @brief comparison: not equal
  18809. @copydoc operator!=(const_reference, const_reference)
  18810. */
  18811. template<typename ScalarType, typename std::enable_if<
  18812. std::is_scalar<ScalarType>::value, int>::type = 0>
  18813. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  18814. {
  18815. return lhs != basic_json(rhs);
  18816. }
  18817. /*!
  18818. @brief comparison: not equal
  18819. @copydoc operator!=(const_reference, const_reference)
  18820. */
  18821. template<typename ScalarType, typename std::enable_if<
  18822. std::is_scalar<ScalarType>::value, int>::type = 0>
  18823. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  18824. {
  18825. return basic_json(lhs) != rhs;
  18826. }
  18827. /*!
  18828. @brief comparison: less than
  18829. Compares whether one JSON value @a lhs is less than another JSON value @a
  18830. rhs according to the following rules:
  18831. - If @a lhs and @a rhs have the same type, the values are compared using
  18832. the default `<` operator.
  18833. - Integer and floating-point numbers are automatically converted before
  18834. comparison
  18835. - In case @a lhs and @a rhs have different types, the values are ignored
  18836. and the order of the types is considered, see
  18837. @ref operator<(const value_t, const value_t).
  18838. @param[in] lhs first JSON value to consider
  18839. @param[in] rhs second JSON value to consider
  18840. @return whether @a lhs is less than @a rhs
  18841. @complexity Linear.
  18842. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18843. @liveexample{The example demonstrates comparing several JSON
  18844. types.,operator__less}
  18845. @since version 1.0.0
  18846. */
  18847. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  18848. {
  18849. const auto lhs_type = lhs.type();
  18850. const auto rhs_type = rhs.type();
  18851. if (lhs_type == rhs_type)
  18852. {
  18853. switch (lhs_type)
  18854. {
  18855. case value_t::array:
  18856. // note parentheses are necessary, see
  18857. // https://github.com/nlohmann/json/issues/1530
  18858. return (*lhs.m_value.array) < (*rhs.m_value.array);
  18859. case value_t::object:
  18860. return (*lhs.m_value.object) < (*rhs.m_value.object);
  18861. case value_t::null:
  18862. return false;
  18863. case value_t::string:
  18864. return (*lhs.m_value.string) < (*rhs.m_value.string);
  18865. case value_t::boolean:
  18866. return (lhs.m_value.boolean) < (rhs.m_value.boolean);
  18867. case value_t::number_integer:
  18868. return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
  18869. case value_t::number_unsigned:
  18870. return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
  18871. case value_t::number_float:
  18872. return (lhs.m_value.number_float) < (rhs.m_value.number_float);
  18873. case value_t::binary:
  18874. return (*lhs.m_value.binary) < (*rhs.m_value.binary);
  18875. default:
  18876. return false;
  18877. }
  18878. }
  18879. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float)
  18880. {
  18881. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  18882. }
  18883. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer)
  18884. {
  18885. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  18886. }
  18887. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float)
  18888. {
  18889. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  18890. }
  18891. else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned)
  18892. {
  18893. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  18894. }
  18895. else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned)
  18896. {
  18897. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  18898. }
  18899. else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer)
  18900. {
  18901. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  18902. }
  18903. // We only reach this line if we cannot compare values. In that case,
  18904. // we compare types. Note we have to call the operator explicitly,
  18905. // because MSVC has problems otherwise.
  18906. return operator<(lhs_type, rhs_type);
  18907. }
  18908. /*!
  18909. @brief comparison: less than
  18910. @copydoc operator<(const_reference, const_reference)
  18911. */
  18912. template<typename ScalarType, typename std::enable_if<
  18913. std::is_scalar<ScalarType>::value, int>::type = 0>
  18914. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  18915. {
  18916. return lhs < basic_json(rhs);
  18917. }
  18918. /*!
  18919. @brief comparison: less than
  18920. @copydoc operator<(const_reference, const_reference)
  18921. */
  18922. template<typename ScalarType, typename std::enable_if<
  18923. std::is_scalar<ScalarType>::value, int>::type = 0>
  18924. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  18925. {
  18926. return basic_json(lhs) < rhs;
  18927. }
  18928. /*!
  18929. @brief comparison: less than or equal
  18930. Compares whether one JSON value @a lhs is less than or equal to another
  18931. JSON value by calculating `not (rhs < lhs)`.
  18932. @param[in] lhs first JSON value to consider
  18933. @param[in] rhs second JSON value to consider
  18934. @return whether @a lhs is less than or equal to @a rhs
  18935. @complexity Linear.
  18936. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18937. @liveexample{The example demonstrates comparing several JSON
  18938. types.,operator__greater}
  18939. @since version 1.0.0
  18940. */
  18941. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  18942. {
  18943. return !(rhs < lhs);
  18944. }
  18945. /*!
  18946. @brief comparison: less than or equal
  18947. @copydoc operator<=(const_reference, const_reference)
  18948. */
  18949. template<typename ScalarType, typename std::enable_if<
  18950. std::is_scalar<ScalarType>::value, int>::type = 0>
  18951. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  18952. {
  18953. return lhs <= basic_json(rhs);
  18954. }
  18955. /*!
  18956. @brief comparison: less than or equal
  18957. @copydoc operator<=(const_reference, const_reference)
  18958. */
  18959. template<typename ScalarType, typename std::enable_if<
  18960. std::is_scalar<ScalarType>::value, int>::type = 0>
  18961. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  18962. {
  18963. return basic_json(lhs) <= rhs;
  18964. }
  18965. /*!
  18966. @brief comparison: greater than
  18967. Compares whether one JSON value @a lhs is greater than another
  18968. JSON value by calculating `not (lhs <= rhs)`.
  18969. @param[in] lhs first JSON value to consider
  18970. @param[in] rhs second JSON value to consider
  18971. @return whether @a lhs is greater than to @a rhs
  18972. @complexity Linear.
  18973. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  18974. @liveexample{The example demonstrates comparing several JSON
  18975. types.,operator__lessequal}
  18976. @since version 1.0.0
  18977. */
  18978. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  18979. {
  18980. return !(lhs <= rhs);
  18981. }
  18982. /*!
  18983. @brief comparison: greater than
  18984. @copydoc operator>(const_reference, const_reference)
  18985. */
  18986. template<typename ScalarType, typename std::enable_if<
  18987. std::is_scalar<ScalarType>::value, int>::type = 0>
  18988. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  18989. {
  18990. return lhs > basic_json(rhs);
  18991. }
  18992. /*!
  18993. @brief comparison: greater than
  18994. @copydoc operator>(const_reference, const_reference)
  18995. */
  18996. template<typename ScalarType, typename std::enable_if<
  18997. std::is_scalar<ScalarType>::value, int>::type = 0>
  18998. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  18999. {
  19000. return basic_json(lhs) > rhs;
  19001. }
  19002. /*!
  19003. @brief comparison: greater than or equal
  19004. Compares whether one JSON value @a lhs is greater than or equal to another
  19005. JSON value by calculating `not (lhs < rhs)`.
  19006. @param[in] lhs first JSON value to consider
  19007. @param[in] rhs second JSON value to consider
  19008. @return whether @a lhs is greater than or equal to @a rhs
  19009. @complexity Linear.
  19010. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19011. @liveexample{The example demonstrates comparing several JSON
  19012. types.,operator__greaterequal}
  19013. @since version 1.0.0
  19014. */
  19015. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  19016. {
  19017. return !(lhs < rhs);
  19018. }
  19019. /*!
  19020. @brief comparison: greater than or equal
  19021. @copydoc operator>=(const_reference, const_reference)
  19022. */
  19023. template<typename ScalarType, typename std::enable_if<
  19024. std::is_scalar<ScalarType>::value, int>::type = 0>
  19025. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  19026. {
  19027. return lhs >= basic_json(rhs);
  19028. }
  19029. /*!
  19030. @brief comparison: greater than or equal
  19031. @copydoc operator>=(const_reference, const_reference)
  19032. */
  19033. template<typename ScalarType, typename std::enable_if<
  19034. std::is_scalar<ScalarType>::value, int>::type = 0>
  19035. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  19036. {
  19037. return basic_json(lhs) >= rhs;
  19038. }
  19039. /// @}
  19040. ///////////////////
  19041. // serialization //
  19042. ///////////////////
  19043. /// @name serialization
  19044. /// @{
  19045. /*!
  19046. @brief serialize to stream
  19047. Serialize the given JSON value @a j to the output stream @a o. The JSON
  19048. value will be serialized using the @ref dump member function.
  19049. - The indentation of the output can be controlled with the member variable
  19050. `width` of the output stream @a o. For instance, using the manipulator
  19051. `std::setw(4)` on @a o sets the indentation level to `4` and the
  19052. serialization result is the same as calling `dump(4)`.
  19053. - The indentation character can be controlled with the member variable
  19054. `fill` of the output stream @a o. For instance, the manipulator
  19055. `std::setfill('\\t')` sets indentation to use a tab character rather than
  19056. the default space character.
  19057. @param[in,out] o stream to serialize to
  19058. @param[in] j JSON value to serialize
  19059. @return the stream @a o
  19060. @throw type_error.316 if a string stored inside the JSON value is not
  19061. UTF-8 encoded
  19062. @complexity Linear.
  19063. @liveexample{The example below shows the serialization with different
  19064. parameters to `width` to adjust the indentation level.,operator_serialize}
  19065. @since version 1.0.0; indentation character added in version 3.0.0
  19066. */
  19067. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  19068. {
  19069. // read width member and use it as indentation parameter if nonzero
  19070. const bool pretty_print = o.width() > 0;
  19071. const auto indentation = pretty_print ? o.width() : 0;
  19072. // reset width to 0 for subsequent calls to this stream
  19073. o.width(0);
  19074. // do the actual serialization
  19075. serializer s(detail::output_adapter<char>(o), o.fill());
  19076. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  19077. return o;
  19078. }
  19079. /*!
  19080. @brief serialize to stream
  19081. @deprecated This stream operator is deprecated and will be removed in
  19082. future 4.0.0 of the library. Please use
  19083. @ref operator<<(std::ostream&, const basic_json&)
  19084. instead; that is, replace calls like `j >> o;` with `o << j;`.
  19085. @since version 1.0.0; deprecated since version 3.0.0
  19086. */
  19087. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&))
  19088. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  19089. {
  19090. return o << j;
  19091. }
  19092. /// @}
  19093. /////////////////////
  19094. // deserialization //
  19095. /////////////////////
  19096. /// @name deserialization
  19097. /// @{
  19098. /*!
  19099. @brief deserialize from a compatible input
  19100. @tparam InputType A compatible input, for instance
  19101. - an std::istream object
  19102. - a FILE pointer
  19103. - a C-style array of characters
  19104. - a pointer to a null-terminated string of single byte characters
  19105. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19106. iterators.
  19107. @param[in] i input to read from
  19108. @param[in] cb a parser callback function of type @ref parser_callback_t
  19109. which is used to control the deserialization by filtering unwanted values
  19110. (optional)
  19111. @param[in] allow_exceptions whether to throw exceptions in case of a
  19112. parse error (optional, true by default)
  19113. @param[in] ignore_comments whether comments should be ignored and treated
  19114. like whitespace (true) or yield a parse error (true); (optional, false by
  19115. default)
  19116. @return deserialized JSON value; in case of a parse error and
  19117. @a allow_exceptions set to `false`, the return value will be
  19118. value_t::discarded.
  19119. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19120. of input; expected string literal""`
  19121. @throw parse_error.102 if to_unicode fails or surrogate error
  19122. @throw parse_error.103 if to_unicode fails
  19123. @complexity Linear in the length of the input. The parser is a predictive
  19124. LL(1) parser. The complexity can be higher if the parser callback function
  19125. @a cb or reading from the input @a i has a super-linear complexity.
  19126. @note A UTF-8 byte order mark is silently ignored.
  19127. @liveexample{The example below demonstrates the `parse()` function reading
  19128. from an array.,parse__array__parser_callback_t}
  19129. @liveexample{The example below demonstrates the `parse()` function with
  19130. and without callback function.,parse__string__parser_callback_t}
  19131. @liveexample{The example below demonstrates the `parse()` function with
  19132. and without callback function.,parse__istream__parser_callback_t}
  19133. @liveexample{The example below demonstrates the `parse()` function reading
  19134. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  19135. @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to
  19136. ignore comments.
  19137. */
  19138. template<typename InputType>
  19139. JSON_HEDLEY_WARN_UNUSED_RESULT
  19140. static basic_json parse(InputType&& i,
  19141. const parser_callback_t cb = nullptr,
  19142. const bool allow_exceptions = true,
  19143. const bool ignore_comments = false)
  19144. {
  19145. basic_json result;
  19146. parser(detail::input_adapter(std::forward<InputType>(i)), cb, allow_exceptions, ignore_comments).parse(true, result);
  19147. return result;
  19148. }
  19149. /*!
  19150. @brief deserialize from a pair of character iterators
  19151. The value_type of the iterator must be a integral type with size of 1, 2 or
  19152. 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32.
  19153. @param[in] first iterator to start of character range
  19154. @param[in] last iterator to end of character range
  19155. @param[in] cb a parser callback function of type @ref parser_callback_t
  19156. which is used to control the deserialization by filtering unwanted values
  19157. (optional)
  19158. @param[in] allow_exceptions whether to throw exceptions in case of a
  19159. parse error (optional, true by default)
  19160. @param[in] ignore_comments whether comments should be ignored and treated
  19161. like whitespace (true) or yield a parse error (true); (optional, false by
  19162. default)
  19163. @return deserialized JSON value; in case of a parse error and
  19164. @a allow_exceptions set to `false`, the return value will be
  19165. value_t::discarded.
  19166. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19167. of input; expected string literal""`
  19168. @throw parse_error.102 if to_unicode fails or surrogate error
  19169. @throw parse_error.103 if to_unicode fails
  19170. */
  19171. template<typename IteratorType>
  19172. JSON_HEDLEY_WARN_UNUSED_RESULT
  19173. static basic_json parse(IteratorType first,
  19174. IteratorType last,
  19175. const parser_callback_t cb = nullptr,
  19176. const bool allow_exceptions = true,
  19177. const bool ignore_comments = false)
  19178. {
  19179. basic_json result;
  19180. parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result);
  19181. return result;
  19182. }
  19183. JSON_HEDLEY_WARN_UNUSED_RESULT
  19184. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len))
  19185. static basic_json parse(detail::span_input_adapter&& i,
  19186. const parser_callback_t cb = nullptr,
  19187. const bool allow_exceptions = true,
  19188. const bool ignore_comments = false)
  19189. {
  19190. basic_json result;
  19191. parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result);
  19192. return result;
  19193. }
  19194. /*!
  19195. @brief check if the input is valid JSON
  19196. Unlike the @ref parse(InputType&&, const parser_callback_t,const bool)
  19197. function, this function neither throws an exception in case of invalid JSON
  19198. input (i.e., a parse error) nor creates diagnostic information.
  19199. @tparam InputType A compatible input, for instance
  19200. - an std::istream object
  19201. - a FILE pointer
  19202. - a C-style array of characters
  19203. - a pointer to a null-terminated string of single byte characters
  19204. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19205. iterators.
  19206. @param[in] i input to read from
  19207. @param[in] ignore_comments whether comments should be ignored and treated
  19208. like whitespace (true) or yield a parse error (true); (optional, false by
  19209. default)
  19210. @return Whether the input read from @a i is valid JSON.
  19211. @complexity Linear in the length of the input. The parser is a predictive
  19212. LL(1) parser.
  19213. @note A UTF-8 byte order mark is silently ignored.
  19214. @liveexample{The example below demonstrates the `accept()` function reading
  19215. from a string.,accept__string}
  19216. */
  19217. template<typename InputType>
  19218. static bool accept(InputType&& i,
  19219. const bool ignore_comments = false)
  19220. {
  19221. return parser(detail::input_adapter(std::forward<InputType>(i)), nullptr, false, ignore_comments).accept(true);
  19222. }
  19223. template<typename IteratorType>
  19224. static bool accept(IteratorType first, IteratorType last,
  19225. const bool ignore_comments = false)
  19226. {
  19227. return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true);
  19228. }
  19229. JSON_HEDLEY_WARN_UNUSED_RESULT
  19230. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len))
  19231. static bool accept(detail::span_input_adapter&& i,
  19232. const bool ignore_comments = false)
  19233. {
  19234. return parser(i.get(), nullptr, false, ignore_comments).accept(true);
  19235. }
  19236. /*!
  19237. @brief generate SAX events
  19238. The SAX event lister must follow the interface of @ref json_sax.
  19239. This function reads from a compatible input. Examples are:
  19240. - an std::istream object
  19241. - a FILE pointer
  19242. - a C-style array of characters
  19243. - a pointer to a null-terminated string of single byte characters
  19244. - an object obj for which begin(obj) and end(obj) produces a valid pair of
  19245. iterators.
  19246. @param[in] i input to read from
  19247. @param[in,out] sax SAX event listener
  19248. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  19249. @param[in] strict whether the input has to be consumed completely
  19250. @param[in] ignore_comments whether comments should be ignored and treated
  19251. like whitespace (true) or yield a parse error (true); (optional, false by
  19252. default); only applies to the JSON file format.
  19253. @return return value of the last processed SAX event
  19254. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  19255. of input; expected string literal""`
  19256. @throw parse_error.102 if to_unicode fails or surrogate error
  19257. @throw parse_error.103 if to_unicode fails
  19258. @complexity Linear in the length of the input. The parser is a predictive
  19259. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  19260. a super-linear complexity.
  19261. @note A UTF-8 byte order mark is silently ignored.
  19262. @liveexample{The example below demonstrates the `sax_parse()` function
  19263. reading from string and processing the events with a user-defined SAX
  19264. event consumer.,sax_parse}
  19265. @since version 3.2.0
  19266. */
  19267. template <typename InputType, typename SAX>
  19268. JSON_HEDLEY_NON_NULL(2)
  19269. static bool sax_parse(InputType&& i, SAX* sax,
  19270. input_format_t format = input_format_t::json,
  19271. const bool strict = true,
  19272. const bool ignore_comments = false)
  19273. {
  19274. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19275. return format == input_format_t::json
  19276. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19277. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19278. }
  19279. template<class IteratorType, class SAX>
  19280. JSON_HEDLEY_NON_NULL(3)
  19281. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax,
  19282. input_format_t format = input_format_t::json,
  19283. const bool strict = true,
  19284. const bool ignore_comments = false)
  19285. {
  19286. auto ia = detail::input_adapter(std::move(first), std::move(last));
  19287. return format == input_format_t::json
  19288. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19289. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19290. }
  19291. template <typename SAX>
  19292. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...))
  19293. JSON_HEDLEY_NON_NULL(2)
  19294. static bool sax_parse(detail::span_input_adapter&& i, SAX* sax,
  19295. input_format_t format = input_format_t::json,
  19296. const bool strict = true,
  19297. const bool ignore_comments = false)
  19298. {
  19299. auto ia = i.get();
  19300. return format == input_format_t::json
  19301. ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict)
  19302. : detail::binary_reader<basic_json, decltype(ia), SAX>(std::move(ia)).sax_parse(format, sax, strict);
  19303. }
  19304. /*!
  19305. @brief deserialize from stream
  19306. @deprecated This stream operator is deprecated and will be removed in
  19307. version 4.0.0 of the library. Please use
  19308. @ref operator>>(std::istream&, basic_json&)
  19309. instead; that is, replace calls like `j << i;` with `i >> j;`.
  19310. @since version 1.0.0; deprecated since version 3.0.0
  19311. */
  19312. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&))
  19313. friend std::istream& operator<<(basic_json& j, std::istream& i)
  19314. {
  19315. return operator>>(i, j);
  19316. }
  19317. /*!
  19318. @brief deserialize from stream
  19319. Deserializes an input stream to a JSON value.
  19320. @param[in,out] i input stream to read a serialized JSON value from
  19321. @param[in,out] j JSON value to write the deserialized input to
  19322. @throw parse_error.101 in case of an unexpected token
  19323. @throw parse_error.102 if to_unicode fails or surrogate error
  19324. @throw parse_error.103 if to_unicode fails
  19325. @complexity Linear in the length of the input. The parser is a predictive
  19326. LL(1) parser.
  19327. @note A UTF-8 byte order mark is silently ignored.
  19328. @liveexample{The example below shows how a JSON value is constructed by
  19329. reading a serialization from a stream.,operator_deserialize}
  19330. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  19331. parser callback function to filter values while parsing
  19332. @since version 1.0.0
  19333. */
  19334. friend std::istream& operator>>(std::istream& i, basic_json& j)
  19335. {
  19336. parser(detail::input_adapter(i)).parse(false, j);
  19337. return i;
  19338. }
  19339. /// @}
  19340. ///////////////////////////
  19341. // convenience functions //
  19342. ///////////////////////////
  19343. /*!
  19344. @brief return the type as string
  19345. Returns the type name as string to be used in error messages - usually to
  19346. indicate that a function was called on a wrong JSON type.
  19347. @return a string representation of a the @a m_type member:
  19348. Value type | return value
  19349. ----------- | -------------
  19350. null | `"null"`
  19351. boolean | `"boolean"`
  19352. string | `"string"`
  19353. number | `"number"` (for all number types)
  19354. object | `"object"`
  19355. array | `"array"`
  19356. binary | `"binary"`
  19357. discarded | `"discarded"`
  19358. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  19359. @complexity Constant.
  19360. @liveexample{The following code exemplifies `type_name()` for all JSON
  19361. types.,type_name}
  19362. @sa @ref type() -- return the type of the JSON value
  19363. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  19364. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  19365. since 3.0.0
  19366. */
  19367. JSON_HEDLEY_RETURNS_NON_NULL
  19368. const char* type_name() const noexcept
  19369. {
  19370. {
  19371. switch (m_type)
  19372. {
  19373. case value_t::null:
  19374. return "null";
  19375. case value_t::object:
  19376. return "object";
  19377. case value_t::array:
  19378. return "array";
  19379. case value_t::string:
  19380. return "string";
  19381. case value_t::boolean:
  19382. return "boolean";
  19383. case value_t::binary:
  19384. return "binary";
  19385. case value_t::discarded:
  19386. return "discarded";
  19387. default:
  19388. return "number";
  19389. }
  19390. }
  19391. }
  19392. private:
  19393. //////////////////////
  19394. // member variables //
  19395. //////////////////////
  19396. /// the type of the current element
  19397. value_t m_type = value_t::null;
  19398. /// the value of the current element
  19399. json_value m_value = {};
  19400. //////////////////////////////////////////
  19401. // binary serialization/deserialization //
  19402. //////////////////////////////////////////
  19403. /// @name binary serialization/deserialization support
  19404. /// @{
  19405. public:
  19406. /*!
  19407. @brief create a CBOR serialization of a given JSON value
  19408. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  19409. Binary Object Representation) serialization format. CBOR is a binary
  19410. serialization format which aims to be more compact than JSON itself, yet
  19411. more efficient to parse.
  19412. The library uses the following mapping from JSON values types to
  19413. CBOR types according to the CBOR specification (RFC 7049):
  19414. JSON value type | value/range | CBOR type | first byte
  19415. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  19416. null | `null` | Null | 0xF6
  19417. boolean | `true` | True | 0xF5
  19418. boolean | `false` | False | 0xF4
  19419. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  19420. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  19421. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  19422. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  19423. number_integer | -24..-1 | Negative integer | 0x20..0x37
  19424. number_integer | 0..23 | Integer | 0x00..0x17
  19425. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19426. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19427. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19428. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19429. number_unsigned | 0..23 | Integer | 0x00..0x17
  19430. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  19431. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  19432. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  19433. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  19434. number_float | *any value representable by a float* | Single-Precision Float | 0xFA
  19435. number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB
  19436. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  19437. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  19438. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  19439. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  19440. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  19441. array | *size*: 0..23 | array | 0x80..0x97
  19442. array | *size*: 23..255 | array (1 byte follow) | 0x98
  19443. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  19444. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  19445. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  19446. object | *size*: 0..23 | map | 0xA0..0xB7
  19447. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  19448. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  19449. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  19450. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  19451. binary | *size*: 0..23 | byte string | 0x40..0x57
  19452. binary | *size*: 23..255 | byte string (1 byte follow) | 0x58
  19453. binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59
  19454. binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A
  19455. binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B
  19456. @note The mapping is **complete** in the sense that any JSON value type
  19457. can be converted to a CBOR value.
  19458. @note If NaN or Infinity are stored inside a JSON number, they are
  19459. serialized properly. This behavior differs from the @ref dump()
  19460. function which serializes NaN or Infinity to `null`.
  19461. @note The following CBOR types are not used in the conversion:
  19462. - UTF-8 strings terminated by "break" (0x7F)
  19463. - arrays terminated by "break" (0x9F)
  19464. - maps terminated by "break" (0xBF)
  19465. - byte strings terminated by "break" (0x5F)
  19466. - date/time (0xC0..0xC1)
  19467. - bignum (0xC2..0xC3)
  19468. - decimal fraction (0xC4)
  19469. - bigfloat (0xC5)
  19470. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19471. - expected conversions (0xD5..0xD7)
  19472. - simple values (0xE0..0xF3, 0xF8)
  19473. - undefined (0xF7)
  19474. - half-precision floats (0xF9)
  19475. - break (0xFF)
  19476. @param[in] j JSON value to serialize
  19477. @return CBOR serialization as byte vector
  19478. @complexity Linear in the size of the JSON value @a j.
  19479. @liveexample{The example shows the serialization of a JSON value to a byte
  19480. vector in CBOR format.,to_cbor}
  19481. @sa http://cbor.io
  19482. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19483. analogous deserialization
  19484. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19485. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19486. related UBJSON format
  19487. @since version 2.0.9; compact representation of floating-point numbers
  19488. since version 3.8.0
  19489. */
  19490. static std::vector<uint8_t> to_cbor(const basic_json& j)
  19491. {
  19492. std::vector<uint8_t> result;
  19493. to_cbor(j, result);
  19494. return result;
  19495. }
  19496. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  19497. {
  19498. binary_writer<uint8_t>(o).write_cbor(j);
  19499. }
  19500. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  19501. {
  19502. binary_writer<char>(o).write_cbor(j);
  19503. }
  19504. /*!
  19505. @brief create a MessagePack serialization of a given JSON value
  19506. Serializes a given JSON value @a j to a byte vector using the MessagePack
  19507. serialization format. MessagePack is a binary serialization format which
  19508. aims to be more compact than JSON itself, yet more efficient to parse.
  19509. The library uses the following mapping from JSON values types to
  19510. MessagePack types according to the MessagePack specification:
  19511. JSON value type | value/range | MessagePack type | first byte
  19512. --------------- | --------------------------------- | ---------------- | ----------
  19513. null | `null` | nil | 0xC0
  19514. boolean | `true` | true | 0xC3
  19515. boolean | `false` | false | 0xC2
  19516. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  19517. number_integer | -2147483648..-32769 | int32 | 0xD2
  19518. number_integer | -32768..-129 | int16 | 0xD1
  19519. number_integer | -128..-33 | int8 | 0xD0
  19520. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  19521. number_integer | 0..127 | positive fixint | 0x00..0x7F
  19522. number_integer | 128..255 | uint 8 | 0xCC
  19523. number_integer | 256..65535 | uint 16 | 0xCD
  19524. number_integer | 65536..4294967295 | uint 32 | 0xCE
  19525. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19526. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  19527. number_unsigned | 128..255 | uint 8 | 0xCC
  19528. number_unsigned | 256..65535 | uint 16 | 0xCD
  19529. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  19530. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  19531. number_float | *any value representable by a float* | float 32 | 0xCA
  19532. number_float | *any value NOT representable by a float* | float 64 | 0xCB
  19533. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  19534. string | *length*: 32..255 | str 8 | 0xD9
  19535. string | *length*: 256..65535 | str 16 | 0xDA
  19536. string | *length*: 65536..4294967295 | str 32 | 0xDB
  19537. array | *size*: 0..15 | fixarray | 0x90..0x9F
  19538. array | *size*: 16..65535 | array 16 | 0xDC
  19539. array | *size*: 65536..4294967295 | array 32 | 0xDD
  19540. object | *size*: 0..15 | fix map | 0x80..0x8F
  19541. object | *size*: 16..65535 | map 16 | 0xDE
  19542. object | *size*: 65536..4294967295 | map 32 | 0xDF
  19543. binary | *size*: 0..255 | bin 8 | 0xC4
  19544. binary | *size*: 256..65535 | bin 16 | 0xC5
  19545. binary | *size*: 65536..4294967295 | bin 32 | 0xC6
  19546. @note The mapping is **complete** in the sense that any JSON value type
  19547. can be converted to a MessagePack value.
  19548. @note The following values can **not** be converted to a MessagePack value:
  19549. - strings with more than 4294967295 bytes
  19550. - byte strings with more than 4294967295 bytes
  19551. - arrays with more than 4294967295 elements
  19552. - objects with more than 4294967295 elements
  19553. @note Any MessagePack output created @ref to_msgpack can be successfully
  19554. parsed by @ref from_msgpack.
  19555. @note If NaN or Infinity are stored inside a JSON number, they are
  19556. serialized properly. This behavior differs from the @ref dump()
  19557. function which serializes NaN or Infinity to `null`.
  19558. @param[in] j JSON value to serialize
  19559. @return MessagePack serialization as byte vector
  19560. @complexity Linear in the size of the JSON value @a j.
  19561. @liveexample{The example shows the serialization of a JSON value to a byte
  19562. vector in MessagePack format.,to_msgpack}
  19563. @sa http://msgpack.org
  19564. @sa @ref from_msgpack for the analogous deserialization
  19565. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19566. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19567. related UBJSON format
  19568. @since version 2.0.9
  19569. */
  19570. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  19571. {
  19572. std::vector<uint8_t> result;
  19573. to_msgpack(j, result);
  19574. return result;
  19575. }
  19576. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  19577. {
  19578. binary_writer<uint8_t>(o).write_msgpack(j);
  19579. }
  19580. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  19581. {
  19582. binary_writer<char>(o).write_msgpack(j);
  19583. }
  19584. /*!
  19585. @brief create a UBJSON serialization of a given JSON value
  19586. Serializes a given JSON value @a j to a byte vector using the UBJSON
  19587. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  19588. than JSON itself, yet more efficient to parse.
  19589. The library uses the following mapping from JSON values types to
  19590. UBJSON types according to the UBJSON specification:
  19591. JSON value type | value/range | UBJSON type | marker
  19592. --------------- | --------------------------------- | ----------- | ------
  19593. null | `null` | null | `Z`
  19594. boolean | `true` | true | `T`
  19595. boolean | `false` | false | `F`
  19596. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  19597. number_integer | -2147483648..-32769 | int32 | `l`
  19598. number_integer | -32768..-129 | int16 | `I`
  19599. number_integer | -128..127 | int8 | `i`
  19600. number_integer | 128..255 | uint8 | `U`
  19601. number_integer | 256..32767 | int16 | `I`
  19602. number_integer | 32768..2147483647 | int32 | `l`
  19603. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  19604. number_unsigned | 0..127 | int8 | `i`
  19605. number_unsigned | 128..255 | uint8 | `U`
  19606. number_unsigned | 256..32767 | int16 | `I`
  19607. number_unsigned | 32768..2147483647 | int32 | `l`
  19608. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  19609. number_float | *any value* | float64 | `D`
  19610. string | *with shortest length indicator* | string | `S`
  19611. array | *see notes on optimized format* | array | `[`
  19612. object | *see notes on optimized format* | map | `{`
  19613. @note The mapping is **complete** in the sense that any JSON value type
  19614. can be converted to a UBJSON value.
  19615. @note The following values can **not** be converted to a UBJSON value:
  19616. - strings with more than 9223372036854775807 bytes (theoretical)
  19617. - unsigned integer numbers above 9223372036854775807
  19618. @note The following markers are not used in the conversion:
  19619. - `Z`: no-op values are not created.
  19620. - `C`: single-byte strings are serialized with `S` markers.
  19621. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  19622. by @ref from_ubjson.
  19623. @note If NaN or Infinity are stored inside a JSON number, they are
  19624. serialized properly. This behavior differs from the @ref dump()
  19625. function which serializes NaN or Infinity to `null`.
  19626. @note The optimized formats for containers are supported: Parameter
  19627. @a use_size adds size information to the beginning of a container and
  19628. removes the closing marker. Parameter @a use_type further checks
  19629. whether all elements of a container have the same type and adds the
  19630. type marker to the beginning of the container. The @a use_type
  19631. parameter must only be used together with @a use_size = true. Note
  19632. that @a use_size = true alone may result in larger representations -
  19633. the benefit of this parameter is that the receiving side is
  19634. immediately informed on the number of elements of the container.
  19635. @note If the JSON data contains the binary type, the value stored is a list
  19636. of integers, as suggested by the UBJSON documentation. In particular,
  19637. this means that serialization and the deserialization of a JSON
  19638. containing binary values into UBJSON and back will result in a
  19639. different JSON object.
  19640. @param[in] j JSON value to serialize
  19641. @param[in] use_size whether to add size annotations to container types
  19642. @param[in] use_type whether to add type annotations to container types
  19643. (must be combined with @a use_size = true)
  19644. @return UBJSON serialization as byte vector
  19645. @complexity Linear in the size of the JSON value @a j.
  19646. @liveexample{The example shows the serialization of a JSON value to a byte
  19647. vector in UBJSON format.,to_ubjson}
  19648. @sa http://ubjson.org
  19649. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19650. analogous deserialization
  19651. @sa @ref to_cbor(const basic_json& for the related CBOR format
  19652. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19653. @since version 3.1.0
  19654. */
  19655. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  19656. const bool use_size = false,
  19657. const bool use_type = false)
  19658. {
  19659. std::vector<uint8_t> result;
  19660. to_ubjson(j, result, use_size, use_type);
  19661. return result;
  19662. }
  19663. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  19664. const bool use_size = false, const bool use_type = false)
  19665. {
  19666. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  19667. }
  19668. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  19669. const bool use_size = false, const bool use_type = false)
  19670. {
  19671. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  19672. }
  19673. /*!
  19674. @brief Serializes the given JSON object `j` to BSON and returns a vector
  19675. containing the corresponding BSON-representation.
  19676. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  19677. stored as a single entity (a so-called document).
  19678. The library uses the following mapping from JSON values types to BSON types:
  19679. JSON value type | value/range | BSON type | marker
  19680. --------------- | --------------------------------- | ----------- | ------
  19681. null | `null` | null | 0x0A
  19682. boolean | `true`, `false` | boolean | 0x08
  19683. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  19684. number_integer | -2147483648..2147483647 | int32 | 0x10
  19685. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  19686. number_unsigned | 0..2147483647 | int32 | 0x10
  19687. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  19688. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  19689. number_float | *any value* | double | 0x01
  19690. string | *any value* | string | 0x02
  19691. array | *any value* | document | 0x04
  19692. object | *any value* | document | 0x03
  19693. binary | *any value* | binary | 0x05
  19694. @warning The mapping is **incomplete**, since only JSON-objects (and things
  19695. contained therein) can be serialized to BSON.
  19696. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  19697. and the keys may not contain U+0000, since they are serialized a
  19698. zero-terminated c-strings.
  19699. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  19700. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  19701. @throw type_error.317 if `!j.is_object()`
  19702. @pre The input `j` is required to be an object: `j.is_object() == true`.
  19703. @note Any BSON output created via @ref to_bson can be successfully parsed
  19704. by @ref from_bson.
  19705. @param[in] j JSON value to serialize
  19706. @return BSON serialization as byte vector
  19707. @complexity Linear in the size of the JSON value @a j.
  19708. @liveexample{The example shows the serialization of a JSON value to a byte
  19709. vector in BSON format.,to_bson}
  19710. @sa http://bsonspec.org/spec.html
  19711. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  19712. analogous deserialization
  19713. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  19714. related UBJSON format
  19715. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  19716. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  19717. */
  19718. static std::vector<uint8_t> to_bson(const basic_json& j)
  19719. {
  19720. std::vector<uint8_t> result;
  19721. to_bson(j, result);
  19722. return result;
  19723. }
  19724. /*!
  19725. @brief Serializes the given JSON object `j` to BSON and forwards the
  19726. corresponding BSON-representation to the given output_adapter `o`.
  19727. @param j The JSON object to convert to BSON.
  19728. @param o The output adapter that receives the binary BSON representation.
  19729. @pre The input `j` shall be an object: `j.is_object() == true`
  19730. @sa @ref to_bson(const basic_json&)
  19731. */
  19732. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  19733. {
  19734. binary_writer<uint8_t>(o).write_bson(j);
  19735. }
  19736. /*!
  19737. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  19738. */
  19739. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  19740. {
  19741. binary_writer<char>(o).write_bson(j);
  19742. }
  19743. /*!
  19744. @brief create a JSON value from an input in CBOR format
  19745. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  19746. Binary Object Representation) serialization format.
  19747. The library maps CBOR types to JSON value types as follows:
  19748. CBOR type | JSON value type | first byte
  19749. ---------------------- | --------------- | ----------
  19750. Integer | number_unsigned | 0x00..0x17
  19751. Unsigned integer | number_unsigned | 0x18
  19752. Unsigned integer | number_unsigned | 0x19
  19753. Unsigned integer | number_unsigned | 0x1A
  19754. Unsigned integer | number_unsigned | 0x1B
  19755. Negative integer | number_integer | 0x20..0x37
  19756. Negative integer | number_integer | 0x38
  19757. Negative integer | number_integer | 0x39
  19758. Negative integer | number_integer | 0x3A
  19759. Negative integer | number_integer | 0x3B
  19760. Byte string | binary | 0x40..0x57
  19761. Byte string | binary | 0x58
  19762. Byte string | binary | 0x59
  19763. Byte string | binary | 0x5A
  19764. Byte string | binary | 0x5B
  19765. UTF-8 string | string | 0x60..0x77
  19766. UTF-8 string | string | 0x78
  19767. UTF-8 string | string | 0x79
  19768. UTF-8 string | string | 0x7A
  19769. UTF-8 string | string | 0x7B
  19770. UTF-8 string | string | 0x7F
  19771. array | array | 0x80..0x97
  19772. array | array | 0x98
  19773. array | array | 0x99
  19774. array | array | 0x9A
  19775. array | array | 0x9B
  19776. array | array | 0x9F
  19777. map | object | 0xA0..0xB7
  19778. map | object | 0xB8
  19779. map | object | 0xB9
  19780. map | object | 0xBA
  19781. map | object | 0xBB
  19782. map | object | 0xBF
  19783. False | `false` | 0xF4
  19784. True | `true` | 0xF5
  19785. Null | `null` | 0xF6
  19786. Half-Precision Float | number_float | 0xF9
  19787. Single-Precision Float | number_float | 0xFA
  19788. Double-Precision Float | number_float | 0xFB
  19789. @warning The mapping is **incomplete** in the sense that not all CBOR
  19790. types can be converted to a JSON value. The following CBOR types
  19791. are not supported and will yield parse errors (parse_error.112):
  19792. - date/time (0xC0..0xC1)
  19793. - bignum (0xC2..0xC3)
  19794. - decimal fraction (0xC4)
  19795. - bigfloat (0xC5)
  19796. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  19797. - expected conversions (0xD5..0xD7)
  19798. - simple values (0xE0..0xF3, 0xF8)
  19799. - undefined (0xF7)
  19800. @warning CBOR allows map keys of any type, whereas JSON only allows
  19801. strings as keys in object values. Therefore, CBOR maps with keys
  19802. other than UTF-8 strings are rejected (parse_error.113).
  19803. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  19804. @ref from_cbor.
  19805. @param[in] i an input in CBOR format convertible to an input adapter
  19806. @param[in] strict whether to expect the input to be consumed until EOF
  19807. (true by default)
  19808. @param[in] allow_exceptions whether to throw exceptions in case of a
  19809. parse error (optional, true by default)
  19810. @return deserialized JSON value; in case of a parse error and
  19811. @a allow_exceptions set to `false`, the return value will be
  19812. value_t::discarded.
  19813. @throw parse_error.110 if the given input ends prematurely or the end of
  19814. file was not reached when @a strict was set to true
  19815. @throw parse_error.112 if unsupported features from CBOR were
  19816. used in the given input @a v or if the input is not valid CBOR
  19817. @throw parse_error.113 if a string was expected as map key, but not found
  19818. @complexity Linear in the size of the input @a i.
  19819. @liveexample{The example shows the deserialization of a byte vector in CBOR
  19820. format to a JSON value.,from_cbor}
  19821. @sa http://cbor.io
  19822. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  19823. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  19824. related MessagePack format
  19825. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  19826. related UBJSON format
  19827. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19828. consume input adapters, removed start_index parameter, and added
  19829. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19830. since 3.2.0
  19831. */
  19832. template<typename InputType>
  19833. JSON_HEDLEY_WARN_UNUSED_RESULT
  19834. static basic_json from_cbor(InputType&& i,
  19835. const bool strict = true,
  19836. const bool allow_exceptions = true)
  19837. {
  19838. basic_json result;
  19839. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19840. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19841. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  19842. return res ? result : basic_json(value_t::discarded);
  19843. }
  19844. /*!
  19845. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  19846. */
  19847. template<typename IteratorType>
  19848. JSON_HEDLEY_WARN_UNUSED_RESULT
  19849. static basic_json from_cbor(IteratorType first, IteratorType last,
  19850. const bool strict = true,
  19851. const bool allow_exceptions = true)
  19852. {
  19853. basic_json result;
  19854. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19855. auto ia = detail::input_adapter(std::move(first), std::move(last));
  19856. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  19857. return res ? result : basic_json(value_t::discarded);
  19858. }
  19859. template<typename T>
  19860. JSON_HEDLEY_WARN_UNUSED_RESULT
  19861. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  19862. static basic_json from_cbor(const T* ptr, std::size_t len,
  19863. const bool strict = true,
  19864. const bool allow_exceptions = true)
  19865. {
  19866. return from_cbor(ptr, ptr + len, strict, allow_exceptions);
  19867. }
  19868. JSON_HEDLEY_WARN_UNUSED_RESULT
  19869. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len))
  19870. static basic_json from_cbor(detail::span_input_adapter&& i,
  19871. const bool strict = true,
  19872. const bool allow_exceptions = true)
  19873. {
  19874. basic_json result;
  19875. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19876. auto ia = i.get();
  19877. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict);
  19878. return res ? result : basic_json(value_t::discarded);
  19879. }
  19880. /*!
  19881. @brief create a JSON value from an input in MessagePack format
  19882. Deserializes a given input @a i to a JSON value using the MessagePack
  19883. serialization format.
  19884. The library maps MessagePack types to JSON value types as follows:
  19885. MessagePack type | JSON value type | first byte
  19886. ---------------- | --------------- | ----------
  19887. positive fixint | number_unsigned | 0x00..0x7F
  19888. fixmap | object | 0x80..0x8F
  19889. fixarray | array | 0x90..0x9F
  19890. fixstr | string | 0xA0..0xBF
  19891. nil | `null` | 0xC0
  19892. false | `false` | 0xC2
  19893. true | `true` | 0xC3
  19894. float 32 | number_float | 0xCA
  19895. float 64 | number_float | 0xCB
  19896. uint 8 | number_unsigned | 0xCC
  19897. uint 16 | number_unsigned | 0xCD
  19898. uint 32 | number_unsigned | 0xCE
  19899. uint 64 | number_unsigned | 0xCF
  19900. int 8 | number_integer | 0xD0
  19901. int 16 | number_integer | 0xD1
  19902. int 32 | number_integer | 0xD2
  19903. int 64 | number_integer | 0xD3
  19904. str 8 | string | 0xD9
  19905. str 16 | string | 0xDA
  19906. str 32 | string | 0xDB
  19907. array 16 | array | 0xDC
  19908. array 32 | array | 0xDD
  19909. map 16 | object | 0xDE
  19910. map 32 | object | 0xDF
  19911. bin 8 | binary | 0xC4
  19912. bin 16 | binary | 0xC5
  19913. bin 32 | binary | 0xC6
  19914. ext 8 | binary | 0xC7
  19915. ext 16 | binary | 0xC8
  19916. ext 32 | binary | 0xC9
  19917. fixext 1 | binary | 0xD4
  19918. fixext 2 | binary | 0xD5
  19919. fixext 4 | binary | 0xD6
  19920. fixext 8 | binary | 0xD7
  19921. fixext 16 | binary | 0xD8
  19922. negative fixint | number_integer | 0xE0-0xFF
  19923. @note Any MessagePack output created @ref to_msgpack can be successfully
  19924. parsed by @ref from_msgpack.
  19925. @param[in] i an input in MessagePack format convertible to an input
  19926. adapter
  19927. @param[in] strict whether to expect the input to be consumed until EOF
  19928. (true by default)
  19929. @param[in] allow_exceptions whether to throw exceptions in case of a
  19930. parse error (optional, true by default)
  19931. @return deserialized JSON value; in case of a parse error and
  19932. @a allow_exceptions set to `false`, the return value will be
  19933. value_t::discarded.
  19934. @throw parse_error.110 if the given input ends prematurely or the end of
  19935. file was not reached when @a strict was set to true
  19936. @throw parse_error.112 if unsupported features from MessagePack were
  19937. used in the given input @a i or if the input is not valid MessagePack
  19938. @throw parse_error.113 if a string was expected as map key, but not found
  19939. @complexity Linear in the size of the input @a i.
  19940. @liveexample{The example shows the deserialization of a byte vector in
  19941. MessagePack format to a JSON value.,from_msgpack}
  19942. @sa http://msgpack.org
  19943. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  19944. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  19945. related CBOR format
  19946. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  19947. the related UBJSON format
  19948. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  19949. the related BSON format
  19950. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  19951. consume input adapters, removed start_index parameter, and added
  19952. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  19953. since 3.2.0
  19954. */
  19955. template<typename InputType>
  19956. JSON_HEDLEY_WARN_UNUSED_RESULT
  19957. static basic_json from_msgpack(InputType&& i,
  19958. const bool strict = true,
  19959. const bool allow_exceptions = true)
  19960. {
  19961. basic_json result;
  19962. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19963. auto ia = detail::input_adapter(std::forward<InputType>(i));
  19964. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  19965. return res ? result : basic_json(value_t::discarded);
  19966. }
  19967. /*!
  19968. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  19969. */
  19970. template<typename IteratorType>
  19971. JSON_HEDLEY_WARN_UNUSED_RESULT
  19972. static basic_json from_msgpack(IteratorType first, IteratorType last,
  19973. const bool strict = true,
  19974. const bool allow_exceptions = true)
  19975. {
  19976. basic_json result;
  19977. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19978. auto ia = detail::input_adapter(std::move(first), std::move(last));
  19979. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  19980. return res ? result : basic_json(value_t::discarded);
  19981. }
  19982. template<typename T>
  19983. JSON_HEDLEY_WARN_UNUSED_RESULT
  19984. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  19985. static basic_json from_msgpack(const T* ptr, std::size_t len,
  19986. const bool strict = true,
  19987. const bool allow_exceptions = true)
  19988. {
  19989. return from_msgpack(ptr, ptr + len, strict, allow_exceptions);
  19990. }
  19991. JSON_HEDLEY_WARN_UNUSED_RESULT
  19992. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len))
  19993. static basic_json from_msgpack(detail::span_input_adapter&& i,
  19994. const bool strict = true,
  19995. const bool allow_exceptions = true)
  19996. {
  19997. basic_json result;
  19998. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  19999. auto ia = i.get();
  20000. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict);
  20001. return res ? result : basic_json(value_t::discarded);
  20002. }
  20003. /*!
  20004. @brief create a JSON value from an input in UBJSON format
  20005. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  20006. Binary JSON) serialization format.
  20007. The library maps UBJSON types to JSON value types as follows:
  20008. UBJSON type | JSON value type | marker
  20009. ----------- | --------------------------------------- | ------
  20010. no-op | *no value, next value is read* | `N`
  20011. null | `null` | `Z`
  20012. false | `false` | `F`
  20013. true | `true` | `T`
  20014. float32 | number_float | `d`
  20015. float64 | number_float | `D`
  20016. uint8 | number_unsigned | `U`
  20017. int8 | number_integer | `i`
  20018. int16 | number_integer | `I`
  20019. int32 | number_integer | `l`
  20020. int64 | number_integer | `L`
  20021. string | string | `S`
  20022. char | string | `C`
  20023. array | array (optimized values are supported) | `[`
  20024. object | object (optimized values are supported) | `{`
  20025. @note The mapping is **complete** in the sense that any UBJSON value can
  20026. be converted to a JSON value.
  20027. @param[in] i an input in UBJSON format convertible to an input adapter
  20028. @param[in] strict whether to expect the input to be consumed until EOF
  20029. (true by default)
  20030. @param[in] allow_exceptions whether to throw exceptions in case of a
  20031. parse error (optional, true by default)
  20032. @return deserialized JSON value; in case of a parse error and
  20033. @a allow_exceptions set to `false`, the return value will be
  20034. value_t::discarded.
  20035. @throw parse_error.110 if the given input ends prematurely or the end of
  20036. file was not reached when @a strict was set to true
  20037. @throw parse_error.112 if a parse error occurs
  20038. @throw parse_error.113 if a string could not be parsed successfully
  20039. @complexity Linear in the size of the input @a i.
  20040. @liveexample{The example shows the deserialization of a byte vector in
  20041. UBJSON format to a JSON value.,from_ubjson}
  20042. @sa http://ubjson.org
  20043. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  20044. analogous serialization
  20045. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  20046. related CBOR format
  20047. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  20048. the related MessagePack format
  20049. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  20050. the related BSON format
  20051. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  20052. */
  20053. template<typename InputType>
  20054. JSON_HEDLEY_WARN_UNUSED_RESULT
  20055. static basic_json from_ubjson(InputType&& i,
  20056. const bool strict = true,
  20057. const bool allow_exceptions = true)
  20058. {
  20059. basic_json result;
  20060. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20061. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20062. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20063. return res ? result : basic_json(value_t::discarded);
  20064. }
  20065. /*!
  20066. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  20067. */
  20068. template<typename IteratorType>
  20069. JSON_HEDLEY_WARN_UNUSED_RESULT
  20070. static basic_json from_ubjson(IteratorType first, IteratorType last,
  20071. const bool strict = true,
  20072. const bool allow_exceptions = true)
  20073. {
  20074. basic_json result;
  20075. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20076. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20077. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20078. return res ? result : basic_json(value_t::discarded);
  20079. }
  20080. template<typename T>
  20081. JSON_HEDLEY_WARN_UNUSED_RESULT
  20082. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  20083. static basic_json from_ubjson(const T* ptr, std::size_t len,
  20084. const bool strict = true,
  20085. const bool allow_exceptions = true)
  20086. {
  20087. return from_ubjson(ptr, ptr + len, strict, allow_exceptions);
  20088. }
  20089. JSON_HEDLEY_WARN_UNUSED_RESULT
  20090. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len))
  20091. static basic_json from_ubjson(detail::span_input_adapter&& i,
  20092. const bool strict = true,
  20093. const bool allow_exceptions = true)
  20094. {
  20095. basic_json result;
  20096. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20097. auto ia = i.get();
  20098. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict);
  20099. return res ? result : basic_json(value_t::discarded);
  20100. }
  20101. /*!
  20102. @brief Create a JSON value from an input in BSON format
  20103. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  20104. serialization format.
  20105. The library maps BSON record types to JSON value types as follows:
  20106. BSON type | BSON marker byte | JSON value type
  20107. --------------- | ---------------- | ---------------------------
  20108. double | 0x01 | number_float
  20109. string | 0x02 | string
  20110. document | 0x03 | object
  20111. array | 0x04 | array
  20112. binary | 0x05 | still unsupported
  20113. undefined | 0x06 | still unsupported
  20114. ObjectId | 0x07 | still unsupported
  20115. boolean | 0x08 | boolean
  20116. UTC Date-Time | 0x09 | still unsupported
  20117. null | 0x0A | null
  20118. Regular Expr. | 0x0B | still unsupported
  20119. DB Pointer | 0x0C | still unsupported
  20120. JavaScript Code | 0x0D | still unsupported
  20121. Symbol | 0x0E | still unsupported
  20122. JavaScript Code | 0x0F | still unsupported
  20123. int32 | 0x10 | number_integer
  20124. Timestamp | 0x11 | still unsupported
  20125. 128-bit decimal float | 0x13 | still unsupported
  20126. Max Key | 0x7F | still unsupported
  20127. Min Key | 0xFF | still unsupported
  20128. @warning The mapping is **incomplete**. The unsupported mappings
  20129. are indicated in the table above.
  20130. @param[in] i an input in BSON format convertible to an input adapter
  20131. @param[in] strict whether to expect the input to be consumed until EOF
  20132. (true by default)
  20133. @param[in] allow_exceptions whether to throw exceptions in case of a
  20134. parse error (optional, true by default)
  20135. @return deserialized JSON value; in case of a parse error and
  20136. @a allow_exceptions set to `false`, the return value will be
  20137. value_t::discarded.
  20138. @throw parse_error.114 if an unsupported BSON record type is encountered
  20139. @complexity Linear in the size of the input @a i.
  20140. @liveexample{The example shows the deserialization of a byte vector in
  20141. BSON format to a JSON value.,from_bson}
  20142. @sa http://bsonspec.org/spec.html
  20143. @sa @ref to_bson(const basic_json&) for the analogous serialization
  20144. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  20145. related CBOR format
  20146. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  20147. the related MessagePack format
  20148. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  20149. related UBJSON format
  20150. */
  20151. template<typename InputType>
  20152. JSON_HEDLEY_WARN_UNUSED_RESULT
  20153. static basic_json from_bson(InputType&& i,
  20154. const bool strict = true,
  20155. const bool allow_exceptions = true)
  20156. {
  20157. basic_json result;
  20158. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20159. auto ia = detail::input_adapter(std::forward<InputType>(i));
  20160. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20161. return res ? result : basic_json(value_t::discarded);
  20162. }
  20163. /*!
  20164. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  20165. */
  20166. template<typename IteratorType>
  20167. JSON_HEDLEY_WARN_UNUSED_RESULT
  20168. static basic_json from_bson(IteratorType first, IteratorType last,
  20169. const bool strict = true,
  20170. const bool allow_exceptions = true)
  20171. {
  20172. basic_json result;
  20173. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20174. auto ia = detail::input_adapter(std::move(first), std::move(last));
  20175. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20176. return res ? result : basic_json(value_t::discarded);
  20177. }
  20178. template<typename T>
  20179. JSON_HEDLEY_WARN_UNUSED_RESULT
  20180. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  20181. static basic_json from_bson(const T* ptr, std::size_t len,
  20182. const bool strict = true,
  20183. const bool allow_exceptions = true)
  20184. {
  20185. return from_bson(ptr, ptr + len, strict, allow_exceptions);
  20186. }
  20187. JSON_HEDLEY_WARN_UNUSED_RESULT
  20188. JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len))
  20189. static basic_json from_bson(detail::span_input_adapter&& i,
  20190. const bool strict = true,
  20191. const bool allow_exceptions = true)
  20192. {
  20193. basic_json result;
  20194. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  20195. auto ia = i.get();
  20196. const bool res = binary_reader<decltype(ia)>(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict);
  20197. return res ? result : basic_json(value_t::discarded);
  20198. }
  20199. /// @}
  20200. //////////////////////////
  20201. // JSON Pointer support //
  20202. //////////////////////////
  20203. /// @name JSON Pointer functions
  20204. /// @{
  20205. /*!
  20206. @brief access specified element via JSON Pointer
  20207. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  20208. No bound checking is performed. Similar to @ref operator[](const typename
  20209. object_t::key_type&), `null` values are created in arrays and objects if
  20210. necessary.
  20211. In particular:
  20212. - If the JSON pointer points to an object key that does not exist, it
  20213. is created an filled with a `null` value before a reference to it
  20214. is returned.
  20215. - If the JSON pointer points to an array index that does not exist, it
  20216. is created an filled with a `null` value before a reference to it
  20217. is returned. All indices between the current maximum and the given
  20218. index are also filled with `null`.
  20219. - The special value `-` is treated as a synonym for the index past the
  20220. end.
  20221. @param[in] ptr a JSON pointer
  20222. @return reference to the element pointed to by @a ptr
  20223. @complexity Constant.
  20224. @throw parse_error.106 if an array index begins with '0'
  20225. @throw parse_error.109 if an array index was not a number
  20226. @throw out_of_range.404 if the JSON pointer can not be resolved
  20227. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  20228. @since version 2.0.0
  20229. */
  20230. reference operator[](const json_pointer& ptr)
  20231. {
  20232. return ptr.get_unchecked(this);
  20233. }
  20234. /*!
  20235. @brief access specified element via JSON Pointer
  20236. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  20237. No bound checking is performed. The function does not change the JSON
  20238. value; no `null` values are created. In particular, the special value
  20239. `-` yields an exception.
  20240. @param[in] ptr JSON pointer to the desired element
  20241. @return const reference to the element pointed to by @a ptr
  20242. @complexity Constant.
  20243. @throw parse_error.106 if an array index begins with '0'
  20244. @throw parse_error.109 if an array index was not a number
  20245. @throw out_of_range.402 if the array index '-' is used
  20246. @throw out_of_range.404 if the JSON pointer can not be resolved
  20247. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  20248. @since version 2.0.0
  20249. */
  20250. const_reference operator[](const json_pointer& ptr) const
  20251. {
  20252. return ptr.get_unchecked(this);
  20253. }
  20254. /*!
  20255. @brief access specified element via JSON Pointer
  20256. Returns a reference to the element at with specified JSON pointer @a ptr,
  20257. with bounds checking.
  20258. @param[in] ptr JSON pointer to the desired element
  20259. @return reference to the element pointed to by @a ptr
  20260. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20261. begins with '0'. See example below.
  20262. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20263. is not a number. See example below.
  20264. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20265. is out of range. See example below.
  20266. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20267. pointer @a ptr. As `at` provides checked access (and no elements are
  20268. implicitly inserted), the index '-' is always invalid. See example below.
  20269. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20270. which cannot be found. See example below.
  20271. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20272. See example below.
  20273. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20274. changes in the JSON value.
  20275. @complexity Constant.
  20276. @since version 2.0.0
  20277. @liveexample{The behavior is shown in the example.,at_json_pointer}
  20278. */
  20279. reference at(const json_pointer& ptr)
  20280. {
  20281. return ptr.get_checked(this);
  20282. }
  20283. /*!
  20284. @brief access specified element via JSON Pointer
  20285. Returns a const reference to the element at with specified JSON pointer @a
  20286. ptr, with bounds checking.
  20287. @param[in] ptr JSON pointer to the desired element
  20288. @return reference to the element pointed to by @a ptr
  20289. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  20290. begins with '0'. See example below.
  20291. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  20292. is not a number. See example below.
  20293. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  20294. is out of range. See example below.
  20295. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  20296. pointer @a ptr. As `at` provides checked access (and no elements are
  20297. implicitly inserted), the index '-' is always invalid. See example below.
  20298. @throw out_of_range.403 if the JSON pointer describes a key of an object
  20299. which cannot be found. See example below.
  20300. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  20301. See example below.
  20302. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  20303. changes in the JSON value.
  20304. @complexity Constant.
  20305. @since version 2.0.0
  20306. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  20307. */
  20308. const_reference at(const json_pointer& ptr) const
  20309. {
  20310. return ptr.get_checked(this);
  20311. }
  20312. /*!
  20313. @brief return flattened JSON value
  20314. The function creates a JSON object whose keys are JSON pointers (see [RFC
  20315. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  20316. primitive. The original JSON value can be restored using the @ref
  20317. unflatten() function.
  20318. @return an object that maps JSON pointers to primitive values
  20319. @note Empty objects and arrays are flattened to `null` and will not be
  20320. reconstructed correctly by the @ref unflatten() function.
  20321. @complexity Linear in the size the JSON value.
  20322. @liveexample{The following code shows how a JSON object is flattened to an
  20323. object whose keys consist of JSON pointers.,flatten}
  20324. @sa @ref unflatten() for the reverse function
  20325. @since version 2.0.0
  20326. */
  20327. basic_json flatten() const
  20328. {
  20329. basic_json result(value_t::object);
  20330. json_pointer::flatten("", *this, result);
  20331. return result;
  20332. }
  20333. /*!
  20334. @brief unflatten a previously flattened JSON value
  20335. The function restores the arbitrary nesting of a JSON value that has been
  20336. flattened before using the @ref flatten() function. The JSON value must
  20337. meet certain constraints:
  20338. 1. The value must be an object.
  20339. 2. The keys must be JSON pointers (see
  20340. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  20341. 3. The mapped values must be primitive JSON types.
  20342. @return the original JSON from a flattened version
  20343. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  20344. values and can not unflattened to their original type. Apart from
  20345. this example, for a JSON value `j`, the following is always true:
  20346. `j == j.flatten().unflatten()`.
  20347. @complexity Linear in the size the JSON value.
  20348. @throw type_error.314 if value is not an object
  20349. @throw type_error.315 if object values are not primitive
  20350. @liveexample{The following code shows how a flattened JSON object is
  20351. unflattened into the original nested JSON object.,unflatten}
  20352. @sa @ref flatten() for the reverse function
  20353. @since version 2.0.0
  20354. */
  20355. basic_json unflatten() const
  20356. {
  20357. return json_pointer::unflatten(*this);
  20358. }
  20359. /// @}
  20360. //////////////////////////
  20361. // JSON Patch functions //
  20362. //////////////////////////
  20363. /// @name JSON Patch functions
  20364. /// @{
  20365. /*!
  20366. @brief applies a JSON patch
  20367. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  20368. expressing a sequence of operations to apply to a JSON) document. With
  20369. this function, a JSON Patch is applied to the current JSON value by
  20370. executing all operations from the patch.
  20371. @param[in] json_patch JSON patch document
  20372. @return patched document
  20373. @note The application of a patch is atomic: Either all operations succeed
  20374. and the patched document is returned or an exception is thrown. In
  20375. any case, the original value is not changed: the patch is applied
  20376. to a copy of the value.
  20377. @throw parse_error.104 if the JSON patch does not consist of an array of
  20378. objects
  20379. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  20380. attributes are missing); example: `"operation add must have member path"`
  20381. @throw out_of_range.401 if an array index is out of range.
  20382. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  20383. resolved successfully in the current JSON value; example: `"key baz not
  20384. found"`
  20385. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  20386. "move")
  20387. @throw other_error.501 if "test" operation was unsuccessful
  20388. @complexity Linear in the size of the JSON value and the length of the
  20389. JSON patch. As usually only a fraction of the JSON value is affected by
  20390. the patch, the complexity can usually be neglected.
  20391. @liveexample{The following code shows how a JSON patch is applied to a
  20392. value.,patch}
  20393. @sa @ref diff -- create a JSON patch by comparing two JSON values
  20394. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20395. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  20396. @since version 2.0.0
  20397. */
  20398. basic_json patch(const basic_json& json_patch) const
  20399. {
  20400. // make a working copy to apply the patch to
  20401. basic_json result = *this;
  20402. // the valid JSON Patch operations
  20403. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  20404. const auto get_op = [](const std::string & op)
  20405. {
  20406. if (op == "add")
  20407. {
  20408. return patch_operations::add;
  20409. }
  20410. if (op == "remove")
  20411. {
  20412. return patch_operations::remove;
  20413. }
  20414. if (op == "replace")
  20415. {
  20416. return patch_operations::replace;
  20417. }
  20418. if (op == "move")
  20419. {
  20420. return patch_operations::move;
  20421. }
  20422. if (op == "copy")
  20423. {
  20424. return patch_operations::copy;
  20425. }
  20426. if (op == "test")
  20427. {
  20428. return patch_operations::test;
  20429. }
  20430. return patch_operations::invalid;
  20431. };
  20432. // wrapper for "add" operation; add value at ptr
  20433. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  20434. {
  20435. // adding to the root of the target document means replacing it
  20436. if (ptr.empty())
  20437. {
  20438. result = val;
  20439. return;
  20440. }
  20441. // make sure the top element of the pointer exists
  20442. json_pointer top_pointer = ptr.top();
  20443. if (top_pointer != ptr)
  20444. {
  20445. result.at(top_pointer);
  20446. }
  20447. // get reference to parent of JSON pointer ptr
  20448. const auto last_path = ptr.back();
  20449. ptr.pop_back();
  20450. basic_json& parent = result[ptr];
  20451. switch (parent.m_type)
  20452. {
  20453. case value_t::null:
  20454. case value_t::object:
  20455. {
  20456. // use operator[] to add value
  20457. parent[last_path] = val;
  20458. break;
  20459. }
  20460. case value_t::array:
  20461. {
  20462. if (last_path == "-")
  20463. {
  20464. // special case: append to back
  20465. parent.push_back(val);
  20466. }
  20467. else
  20468. {
  20469. const auto idx = json_pointer::array_index(last_path);
  20470. if (JSON_HEDLEY_UNLIKELY(idx > parent.size()))
  20471. {
  20472. // avoid undefined behavior
  20473. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  20474. }
  20475. // default case: insert add offset
  20476. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  20477. }
  20478. break;
  20479. }
  20480. // if there exists a parent it cannot be primitive
  20481. default: // LCOV_EXCL_LINE
  20482. JSON_ASSERT(false); // LCOV_EXCL_LINE
  20483. }
  20484. };
  20485. // wrapper for "remove" operation; remove value at ptr
  20486. const auto operation_remove = [&result](json_pointer & ptr)
  20487. {
  20488. // get reference to parent of JSON pointer ptr
  20489. const auto last_path = ptr.back();
  20490. ptr.pop_back();
  20491. basic_json& parent = result.at(ptr);
  20492. // remove child
  20493. if (parent.is_object())
  20494. {
  20495. // perform range check
  20496. auto it = parent.find(last_path);
  20497. if (JSON_HEDLEY_LIKELY(it != parent.end()))
  20498. {
  20499. parent.erase(it);
  20500. }
  20501. else
  20502. {
  20503. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  20504. }
  20505. }
  20506. else if (parent.is_array())
  20507. {
  20508. // note erase performs range check
  20509. parent.erase(json_pointer::array_index(last_path));
  20510. }
  20511. };
  20512. // type check: top level value must be an array
  20513. if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array()))
  20514. {
  20515. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20516. }
  20517. // iterate and apply the operations
  20518. for (const auto& val : json_patch)
  20519. {
  20520. // wrapper to get a value for an operation
  20521. const auto get_value = [&val](const std::string & op,
  20522. const std::string & member,
  20523. bool string_type) -> basic_json &
  20524. {
  20525. // find value
  20526. auto it = val.m_value.object->find(member);
  20527. // context-sensitive error message
  20528. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  20529. // check if desired value is present
  20530. if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
  20531. {
  20532. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  20533. }
  20534. // check if result is of type string
  20535. if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string()))
  20536. {
  20537. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  20538. }
  20539. // no error: return value
  20540. return it->second;
  20541. };
  20542. // type check: every element of the array must be an object
  20543. if (JSON_HEDLEY_UNLIKELY(!val.is_object()))
  20544. {
  20545. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  20546. }
  20547. // collect mandatory members
  20548. const std::string op = get_value("op", "op", true);
  20549. const std::string path = get_value(op, "path", true);
  20550. json_pointer ptr(path);
  20551. switch (get_op(op))
  20552. {
  20553. case patch_operations::add:
  20554. {
  20555. operation_add(ptr, get_value("add", "value", false));
  20556. break;
  20557. }
  20558. case patch_operations::remove:
  20559. {
  20560. operation_remove(ptr);
  20561. break;
  20562. }
  20563. case patch_operations::replace:
  20564. {
  20565. // the "path" location must exist - use at()
  20566. result.at(ptr) = get_value("replace", "value", false);
  20567. break;
  20568. }
  20569. case patch_operations::move:
  20570. {
  20571. const std::string from_path = get_value("move", "from", true);
  20572. json_pointer from_ptr(from_path);
  20573. // the "from" location must exist - use at()
  20574. basic_json v = result.at(from_ptr);
  20575. // The move operation is functionally identical to a
  20576. // "remove" operation on the "from" location, followed
  20577. // immediately by an "add" operation at the target
  20578. // location with the value that was just removed.
  20579. operation_remove(from_ptr);
  20580. operation_add(ptr, v);
  20581. break;
  20582. }
  20583. case patch_operations::copy:
  20584. {
  20585. const std::string from_path = get_value("copy", "from", true);
  20586. const json_pointer from_ptr(from_path);
  20587. // the "from" location must exist - use at()
  20588. basic_json v = result.at(from_ptr);
  20589. // The copy is functionally identical to an "add"
  20590. // operation at the target location using the value
  20591. // specified in the "from" member.
  20592. operation_add(ptr, v);
  20593. break;
  20594. }
  20595. case patch_operations::test:
  20596. {
  20597. bool success = false;
  20598. JSON_TRY
  20599. {
  20600. // check if "value" matches the one at "path"
  20601. // the "path" location must exist - use at()
  20602. success = (result.at(ptr) == get_value("test", "value", false));
  20603. }
  20604. JSON_INTERNAL_CATCH (out_of_range&)
  20605. {
  20606. // ignore out of range errors: success remains false
  20607. }
  20608. // throw an exception if test fails
  20609. if (JSON_HEDLEY_UNLIKELY(!success))
  20610. {
  20611. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  20612. }
  20613. break;
  20614. }
  20615. default:
  20616. {
  20617. // op must be "add", "remove", "replace", "move", "copy", or
  20618. // "test"
  20619. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  20620. }
  20621. }
  20622. }
  20623. return result;
  20624. }
  20625. /*!
  20626. @brief creates a diff as a JSON patch
  20627. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  20628. be changed into the value @a target by calling @ref patch function.
  20629. @invariant For two JSON values @a source and @a target, the following code
  20630. yields always `true`:
  20631. @code {.cpp}
  20632. source.patch(diff(source, target)) == target;
  20633. @endcode
  20634. @note Currently, only `remove`, `add`, and `replace` operations are
  20635. generated.
  20636. @param[in] source JSON value to compare from
  20637. @param[in] target JSON value to compare against
  20638. @param[in] path helper value to create JSON pointers
  20639. @return a JSON patch to convert the @a source to @a target
  20640. @complexity Linear in the lengths of @a source and @a target.
  20641. @liveexample{The following code shows how a JSON patch is created as a
  20642. diff for two JSON values.,diff}
  20643. @sa @ref patch -- apply a JSON patch
  20644. @sa @ref merge_patch -- apply a JSON Merge Patch
  20645. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  20646. @since version 2.0.0
  20647. */
  20648. JSON_HEDLEY_WARN_UNUSED_RESULT
  20649. static basic_json diff(const basic_json& source, const basic_json& target,
  20650. const std::string& path = "")
  20651. {
  20652. // the patch
  20653. basic_json result(value_t::array);
  20654. // if the values are the same, return empty patch
  20655. if (source == target)
  20656. {
  20657. return result;
  20658. }
  20659. if (source.type() != target.type())
  20660. {
  20661. // different types: replace value
  20662. result.push_back(
  20663. {
  20664. {"op", "replace"}, {"path", path}, {"value", target}
  20665. });
  20666. return result;
  20667. }
  20668. switch (source.type())
  20669. {
  20670. case value_t::array:
  20671. {
  20672. // first pass: traverse common elements
  20673. std::size_t i = 0;
  20674. while (i < source.size() && i < target.size())
  20675. {
  20676. // recursive call to compare array values at index i
  20677. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  20678. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20679. ++i;
  20680. }
  20681. // i now reached the end of at least one array
  20682. // in a second pass, traverse the remaining elements
  20683. // remove my remaining elements
  20684. const auto end_index = static_cast<difference_type>(result.size());
  20685. while (i < source.size())
  20686. {
  20687. // add operations in reverse order to avoid invalid
  20688. // indices
  20689. result.insert(result.begin() + end_index, object(
  20690. {
  20691. {"op", "remove"},
  20692. {"path", path + "/" + std::to_string(i)}
  20693. }));
  20694. ++i;
  20695. }
  20696. // add other remaining elements
  20697. while (i < target.size())
  20698. {
  20699. result.push_back(
  20700. {
  20701. {"op", "add"},
  20702. {"path", path + "/-"},
  20703. {"value", target[i]}
  20704. });
  20705. ++i;
  20706. }
  20707. break;
  20708. }
  20709. case value_t::object:
  20710. {
  20711. // first pass: traverse this object's elements
  20712. for (auto it = source.cbegin(); it != source.cend(); ++it)
  20713. {
  20714. // escape the key name to be used in a JSON patch
  20715. const auto key = json_pointer::escape(it.key());
  20716. if (target.find(it.key()) != target.end())
  20717. {
  20718. // recursive call to compare object values at key it
  20719. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  20720. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  20721. }
  20722. else
  20723. {
  20724. // found a key that is not in o -> remove it
  20725. result.push_back(object(
  20726. {
  20727. {"op", "remove"}, {"path", path + "/" + key}
  20728. }));
  20729. }
  20730. }
  20731. // second pass: traverse other object's elements
  20732. for (auto it = target.cbegin(); it != target.cend(); ++it)
  20733. {
  20734. if (source.find(it.key()) == source.end())
  20735. {
  20736. // found a key that is not in this -> add it
  20737. const auto key = json_pointer::escape(it.key());
  20738. result.push_back(
  20739. {
  20740. {"op", "add"}, {"path", path + "/" + key},
  20741. {"value", it.value()}
  20742. });
  20743. }
  20744. }
  20745. break;
  20746. }
  20747. default:
  20748. {
  20749. // both primitive type: replace value
  20750. result.push_back(
  20751. {
  20752. {"op", "replace"}, {"path", path}, {"value", target}
  20753. });
  20754. break;
  20755. }
  20756. }
  20757. return result;
  20758. }
  20759. /// @}
  20760. ////////////////////////////////
  20761. // JSON Merge Patch functions //
  20762. ////////////////////////////////
  20763. /// @name JSON Merge Patch functions
  20764. /// @{
  20765. /*!
  20766. @brief applies a JSON Merge Patch
  20767. The merge patch format is primarily intended for use with the HTTP PATCH
  20768. method as a means of describing a set of modifications to a target
  20769. resource's content. This function applies a merge patch to the current
  20770. JSON value.
  20771. The function implements the following algorithm from Section 2 of
  20772. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  20773. ```
  20774. define MergePatch(Target, Patch):
  20775. if Patch is an Object:
  20776. if Target is not an Object:
  20777. Target = {} // Ignore the contents and set it to an empty Object
  20778. for each Name/Value pair in Patch:
  20779. if Value is null:
  20780. if Name exists in Target:
  20781. remove the Name/Value pair from Target
  20782. else:
  20783. Target[Name] = MergePatch(Target[Name], Value)
  20784. return Target
  20785. else:
  20786. return Patch
  20787. ```
  20788. Thereby, `Target` is the current object; that is, the patch is applied to
  20789. the current value.
  20790. @param[in] apply_patch the patch to apply
  20791. @complexity Linear in the lengths of @a patch.
  20792. @liveexample{The following code shows how a JSON Merge Patch is applied to
  20793. a JSON document.,merge_patch}
  20794. @sa @ref patch -- apply a JSON patch
  20795. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  20796. @since version 3.0.0
  20797. */
  20798. void merge_patch(const basic_json& apply_patch)
  20799. {
  20800. if (apply_patch.is_object())
  20801. {
  20802. if (!is_object())
  20803. {
  20804. *this = object();
  20805. }
  20806. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  20807. {
  20808. if (it.value().is_null())
  20809. {
  20810. erase(it.key());
  20811. }
  20812. else
  20813. {
  20814. operator[](it.key()).merge_patch(it.value());
  20815. }
  20816. }
  20817. }
  20818. else
  20819. {
  20820. *this = apply_patch;
  20821. }
  20822. }
  20823. /// @}
  20824. };
  20825. /*!
  20826. @brief user-defined to_string function for JSON values
  20827. This function implements a user-defined to_string for JSON objects.
  20828. @param[in] j a JSON object
  20829. @return a std::string object
  20830. */
  20831. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20832. std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
  20833. {
  20834. return j.dump();
  20835. }
  20836. } // namespace nlohmann
  20837. ///////////////////////
  20838. // nonmember support //
  20839. ///////////////////////
  20840. // specialization of std::swap, and std::hash
  20841. namespace std
  20842. {
  20843. /// hash value for JSON objects
  20844. template<>
  20845. struct hash<nlohmann::json>
  20846. {
  20847. /*!
  20848. @brief return a hash value for a JSON object
  20849. @since version 1.0.0
  20850. */
  20851. std::size_t operator()(const nlohmann::json& j) const
  20852. {
  20853. // a naive hashing via the string representation
  20854. const auto& h = hash<nlohmann::json::string_t>();
  20855. return h(j.dump());
  20856. }
  20857. };
  20858. /// specialization for std::less<value_t>
  20859. /// @note: do not remove the space after '<',
  20860. /// see https://github.com/nlohmann/json/pull/679
  20861. template<>
  20862. struct less<::nlohmann::detail::value_t>
  20863. {
  20864. /*!
  20865. @brief compare two value_t enum values
  20866. @since version 3.0.0
  20867. */
  20868. bool operator()(nlohmann::detail::value_t lhs,
  20869. nlohmann::detail::value_t rhs) const noexcept
  20870. {
  20871. return nlohmann::detail::operator<(lhs, rhs);
  20872. }
  20873. };
  20874. // C++20 prohibit function specialization in the std namespace.
  20875. #ifndef JSON_HAS_CPP_20
  20876. /*!
  20877. @brief exchanges the values of two JSON objects
  20878. @since version 1.0.0
  20879. */
  20880. template<>
  20881. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  20882. is_nothrow_move_constructible<nlohmann::json>::value&&
  20883. is_nothrow_move_assignable<nlohmann::json>::value
  20884. )
  20885. {
  20886. j1.swap(j2);
  20887. }
  20888. #endif
  20889. } // namespace std
  20890. /*!
  20891. @brief user-defined string literal for JSON values
  20892. This operator implements a user-defined string literal for JSON objects. It
  20893. can be used by adding `"_json"` to a string literal and returns a JSON object
  20894. if no parse error occurred.
  20895. @param[in] s a string representation of a JSON object
  20896. @param[in] n the length of string @a s
  20897. @return a JSON object
  20898. @since version 1.0.0
  20899. */
  20900. JSON_HEDLEY_NON_NULL(1)
  20901. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  20902. {
  20903. return nlohmann::json::parse(s, s + n);
  20904. }
  20905. /*!
  20906. @brief user-defined string literal for JSON pointer
  20907. This operator implements a user-defined string literal for JSON Pointers. It
  20908. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  20909. object if no parse error occurred.
  20910. @param[in] s a string representation of a JSON Pointer
  20911. @param[in] n the length of string @a s
  20912. @return a JSON pointer object
  20913. @since version 2.0.0
  20914. */
  20915. JSON_HEDLEY_NON_NULL(1)
  20916. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  20917. {
  20918. return nlohmann::json::json_pointer(std::string(s, n));
  20919. }
  20920. // #include <nlohmann/detail/macro_unscope.hpp>
  20921. // restore GCC/clang diagnostic settings
  20922. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  20923. #pragma GCC diagnostic pop
  20924. #endif
  20925. #if defined(__clang__)
  20926. #pragma GCC diagnostic pop
  20927. #endif
  20928. // clean up
  20929. #undef JSON_ASSERT
  20930. #undef JSON_INTERNAL_CATCH
  20931. #undef JSON_CATCH
  20932. #undef JSON_THROW
  20933. #undef JSON_TRY
  20934. #undef JSON_HAS_CPP_14
  20935. #undef JSON_HAS_CPP_17
  20936. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  20937. #undef NLOHMANN_BASIC_JSON_TPL
  20938. // #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
  20939. #undef JSON_HEDLEY_ALWAYS_INLINE
  20940. #undef JSON_HEDLEY_ARM_VERSION
  20941. #undef JSON_HEDLEY_ARM_VERSION_CHECK
  20942. #undef JSON_HEDLEY_ARRAY_PARAM
  20943. #undef JSON_HEDLEY_ASSUME
  20944. #undef JSON_HEDLEY_BEGIN_C_DECLS
  20945. #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE
  20946. #undef JSON_HEDLEY_CLANG_HAS_BUILTIN
  20947. #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE
  20948. #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE
  20949. #undef JSON_HEDLEY_CLANG_HAS_EXTENSION
  20950. #undef JSON_HEDLEY_CLANG_HAS_FEATURE
  20951. #undef JSON_HEDLEY_CLANG_HAS_WARNING
  20952. #undef JSON_HEDLEY_COMPCERT_VERSION
  20953. #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK
  20954. #undef JSON_HEDLEY_CONCAT
  20955. #undef JSON_HEDLEY_CONCAT3
  20956. #undef JSON_HEDLEY_CONCAT3_EX
  20957. #undef JSON_HEDLEY_CONCAT_EX
  20958. #undef JSON_HEDLEY_CONST
  20959. #undef JSON_HEDLEY_CONSTEXPR
  20960. #undef JSON_HEDLEY_CONST_CAST
  20961. #undef JSON_HEDLEY_CPP_CAST
  20962. #undef JSON_HEDLEY_CRAY_VERSION
  20963. #undef JSON_HEDLEY_CRAY_VERSION_CHECK
  20964. #undef JSON_HEDLEY_C_DECL
  20965. #undef JSON_HEDLEY_DEPRECATED
  20966. #undef JSON_HEDLEY_DEPRECATED_FOR
  20967. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL
  20968. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_
  20969. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED
  20970. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES
  20971. #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS
  20972. #undef JSON_HEDLEY_DIAGNOSTIC_POP
  20973. #undef JSON_HEDLEY_DIAGNOSTIC_PUSH
  20974. #undef JSON_HEDLEY_DMC_VERSION
  20975. #undef JSON_HEDLEY_DMC_VERSION_CHECK
  20976. #undef JSON_HEDLEY_EMPTY_BASES
  20977. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION
  20978. #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK
  20979. #undef JSON_HEDLEY_END_C_DECLS
  20980. #undef JSON_HEDLEY_FLAGS
  20981. #undef JSON_HEDLEY_FLAGS_CAST
  20982. #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE
  20983. #undef JSON_HEDLEY_GCC_HAS_BUILTIN
  20984. #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE
  20985. #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE
  20986. #undef JSON_HEDLEY_GCC_HAS_EXTENSION
  20987. #undef JSON_HEDLEY_GCC_HAS_FEATURE
  20988. #undef JSON_HEDLEY_GCC_HAS_WARNING
  20989. #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK
  20990. #undef JSON_HEDLEY_GCC_VERSION
  20991. #undef JSON_HEDLEY_GCC_VERSION_CHECK
  20992. #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE
  20993. #undef JSON_HEDLEY_GNUC_HAS_BUILTIN
  20994. #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE
  20995. #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE
  20996. #undef JSON_HEDLEY_GNUC_HAS_EXTENSION
  20997. #undef JSON_HEDLEY_GNUC_HAS_FEATURE
  20998. #undef JSON_HEDLEY_GNUC_HAS_WARNING
  20999. #undef JSON_HEDLEY_GNUC_VERSION
  21000. #undef JSON_HEDLEY_GNUC_VERSION_CHECK
  21001. #undef JSON_HEDLEY_HAS_ATTRIBUTE
  21002. #undef JSON_HEDLEY_HAS_BUILTIN
  21003. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE
  21004. #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS
  21005. #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE
  21006. #undef JSON_HEDLEY_HAS_EXTENSION
  21007. #undef JSON_HEDLEY_HAS_FEATURE
  21008. #undef JSON_HEDLEY_HAS_WARNING
  21009. #undef JSON_HEDLEY_IAR_VERSION
  21010. #undef JSON_HEDLEY_IAR_VERSION_CHECK
  21011. #undef JSON_HEDLEY_IBM_VERSION
  21012. #undef JSON_HEDLEY_IBM_VERSION_CHECK
  21013. #undef JSON_HEDLEY_IMPORT
  21014. #undef JSON_HEDLEY_INLINE
  21015. #undef JSON_HEDLEY_INTEL_VERSION
  21016. #undef JSON_HEDLEY_INTEL_VERSION_CHECK
  21017. #undef JSON_HEDLEY_IS_CONSTANT
  21018. #undef JSON_HEDLEY_IS_CONSTEXPR_
  21019. #undef JSON_HEDLEY_LIKELY
  21020. #undef JSON_HEDLEY_MALLOC
  21021. #undef JSON_HEDLEY_MESSAGE
  21022. #undef JSON_HEDLEY_MSVC_VERSION
  21023. #undef JSON_HEDLEY_MSVC_VERSION_CHECK
  21024. #undef JSON_HEDLEY_NEVER_INLINE
  21025. #undef JSON_HEDLEY_NON_NULL
  21026. #undef JSON_HEDLEY_NO_ESCAPE
  21027. #undef JSON_HEDLEY_NO_RETURN
  21028. #undef JSON_HEDLEY_NO_THROW
  21029. #undef JSON_HEDLEY_NULL
  21030. #undef JSON_HEDLEY_PELLES_VERSION
  21031. #undef JSON_HEDLEY_PELLES_VERSION_CHECK
  21032. #undef JSON_HEDLEY_PGI_VERSION
  21033. #undef JSON_HEDLEY_PGI_VERSION_CHECK
  21034. #undef JSON_HEDLEY_PREDICT
  21035. #undef JSON_HEDLEY_PRINTF_FORMAT
  21036. #undef JSON_HEDLEY_PRIVATE
  21037. #undef JSON_HEDLEY_PUBLIC
  21038. #undef JSON_HEDLEY_PURE
  21039. #undef JSON_HEDLEY_REINTERPRET_CAST
  21040. #undef JSON_HEDLEY_REQUIRE
  21041. #undef JSON_HEDLEY_REQUIRE_CONSTEXPR
  21042. #undef JSON_HEDLEY_REQUIRE_MSG
  21043. #undef JSON_HEDLEY_RESTRICT
  21044. #undef JSON_HEDLEY_RETURNS_NON_NULL
  21045. #undef JSON_HEDLEY_SENTINEL
  21046. #undef JSON_HEDLEY_STATIC_ASSERT
  21047. #undef JSON_HEDLEY_STATIC_CAST
  21048. #undef JSON_HEDLEY_STRINGIFY
  21049. #undef JSON_HEDLEY_STRINGIFY_EX
  21050. #undef JSON_HEDLEY_SUNPRO_VERSION
  21051. #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK
  21052. #undef JSON_HEDLEY_TINYC_VERSION
  21053. #undef JSON_HEDLEY_TINYC_VERSION_CHECK
  21054. #undef JSON_HEDLEY_TI_ARMCL_VERSION
  21055. #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK
  21056. #undef JSON_HEDLEY_TI_CL2000_VERSION
  21057. #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK
  21058. #undef JSON_HEDLEY_TI_CL430_VERSION
  21059. #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK
  21060. #undef JSON_HEDLEY_TI_CL6X_VERSION
  21061. #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK
  21062. #undef JSON_HEDLEY_TI_CL7X_VERSION
  21063. #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK
  21064. #undef JSON_HEDLEY_TI_CLPRU_VERSION
  21065. #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK
  21066. #undef JSON_HEDLEY_TI_VERSION
  21067. #undef JSON_HEDLEY_TI_VERSION_CHECK
  21068. #undef JSON_HEDLEY_UNAVAILABLE
  21069. #undef JSON_HEDLEY_UNLIKELY
  21070. #undef JSON_HEDLEY_UNPREDICTABLE
  21071. #undef JSON_HEDLEY_UNREACHABLE
  21072. #undef JSON_HEDLEY_UNREACHABLE_RETURN
  21073. #undef JSON_HEDLEY_VERSION
  21074. #undef JSON_HEDLEY_VERSION_DECODE_MAJOR
  21075. #undef JSON_HEDLEY_VERSION_DECODE_MINOR
  21076. #undef JSON_HEDLEY_VERSION_DECODE_REVISION
  21077. #undef JSON_HEDLEY_VERSION_ENCODE
  21078. #undef JSON_HEDLEY_WARNING
  21079. #undef JSON_HEDLEY_WARN_UNUSED_RESULT
  21080. #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG
  21081. #undef JSON_HEDLEY_FALL_THROUGH
  21082. #endif // INCLUDE_NLOHMANN_JSON_HPP_