1
0

json.hpp 711 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.6.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. #ifndef INCLUDE_NLOHMANN_JSON_HPP_
  26. #define INCLUDE_NLOHMANN_JSON_HPP_
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 6
  29. #define NLOHMANN_JSON_VERSION_PATCH 1
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  37. #include <iterator> // random_access_iterator_tag
  38. #include <memory> // unique_ptr
  39. #include <numeric> // accumulate
  40. #include <string> // string, stoi, to_string
  41. #include <utility> // declval, forward, move, pair, swap
  42. #include <vector> // vector
  43. // #include <nlohmann/adl_serializer.hpp>
  44. #include <utility>
  45. // #include <nlohmann/detail/conversions/from_json.hpp>
  46. #include <algorithm> // transform
  47. #include <array> // array
  48. #include <ciso646> // and, not
  49. #include <forward_list> // forward_list
  50. #include <iterator> // inserter, front_inserter, end
  51. #include <map> // map
  52. #include <string> // string
  53. #include <tuple> // tuple, make_tuple
  54. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  55. #include <unordered_map> // unordered_map
  56. #include <utility> // pair, declval
  57. #include <valarray> // valarray
  58. // #include <nlohmann/detail/exceptions.hpp>
  59. #include <exception> // exception
  60. #include <stdexcept> // runtime_error
  61. #include <string> // to_string
  62. // #include <nlohmann/detail/input/position_t.hpp>
  63. #include <cstddef> // size_t
  64. namespace nlohmann
  65. {
  66. namespace detail
  67. {
  68. /// struct to capture the start position of the current token
  69. struct position_t
  70. {
  71. /// the total number of characters read
  72. std::size_t chars_read_total = 0;
  73. /// the number of characters read in the current line
  74. std::size_t chars_read_current_line = 0;
  75. /// the number of lines read
  76. std::size_t lines_read = 0;
  77. /// conversion to size_t to preserve SAX interface
  78. constexpr operator size_t() const
  79. {
  80. return chars_read_total;
  81. }
  82. };
  83. } // namespace detail
  84. } // namespace nlohmann
  85. namespace nlohmann
  86. {
  87. namespace detail
  88. {
  89. ////////////////
  90. // exceptions //
  91. ////////////////
  92. /*!
  93. @brief general exception of the @ref basic_json class
  94. This class is an extension of `std::exception` objects with a member @a id for
  95. exception ids. It is used as the base class for all exceptions thrown by the
  96. @ref basic_json class. This class can hence be used as "wildcard" to catch
  97. exceptions.
  98. Subclasses:
  99. - @ref parse_error for exceptions indicating a parse error
  100. - @ref invalid_iterator for exceptions indicating errors with iterators
  101. - @ref type_error for exceptions indicating executing a member function with
  102. a wrong type
  103. - @ref out_of_range for exceptions indicating access out of the defined range
  104. - @ref other_error for exceptions indicating other library errors
  105. @internal
  106. @note To have nothrow-copy-constructible exceptions, we internally use
  107. `std::runtime_error` which can cope with arbitrary-length error messages.
  108. Intermediate strings are built with static functions and then passed to
  109. the actual constructor.
  110. @endinternal
  111. @liveexample{The following code shows how arbitrary library exceptions can be
  112. caught.,exception}
  113. @since version 3.0.0
  114. */
  115. class exception : public std::exception
  116. {
  117. public:
  118. /// returns the explanatory string
  119. const char* what() const noexcept override
  120. {
  121. return m.what();
  122. }
  123. /// the id of the exception
  124. const int id;
  125. protected:
  126. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  127. static std::string name(const std::string& ename, int id_)
  128. {
  129. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  130. }
  131. private:
  132. /// an exception object as storage for error messages
  133. std::runtime_error m;
  134. };
  135. /*!
  136. @brief exception indicating a parse error
  137. This exception is thrown by the library when a parse error occurs. Parse errors
  138. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  139. as when using JSON Patch.
  140. Member @a byte holds the byte index of the last read character in the input
  141. file.
  142. Exceptions have ids 1xx.
  143. name / id | example message | description
  144. ------------------------------ | --------------- | -------------------------
  145. 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.
  146. 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.
  147. 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.
  148. 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.
  149. 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.
  150. 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`.
  151. 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.
  152. 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.
  153. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  154. 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.
  155. 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.
  156. 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.
  157. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet).
  158. @note For an input with n bytes, 1 is the index of the first character and n+1
  159. is the index of the terminating null byte or the end of file. This also
  160. holds true when reading a byte vector (CBOR or MessagePack).
  161. @liveexample{The following code shows how a `parse_error` exception can be
  162. caught.,parse_error}
  163. @sa - @ref exception for the base class of the library exceptions
  164. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  165. @sa - @ref type_error for exceptions indicating executing a member function with
  166. a wrong type
  167. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  168. @sa - @ref other_error for exceptions indicating other library errors
  169. @since version 3.0.0
  170. */
  171. class parse_error : public exception
  172. {
  173. public:
  174. /*!
  175. @brief create a parse error exception
  176. @param[in] id_ the id of the exception
  177. @param[in] pos the position where the error occurred (or with
  178. chars_read_total=0 if the position cannot be
  179. determined)
  180. @param[in] what_arg the explanatory string
  181. @return parse_error object
  182. */
  183. static parse_error create(int id_, const position_t& pos, const std::string& what_arg)
  184. {
  185. std::string w = exception::name("parse_error", id_) + "parse error" +
  186. position_string(pos) + ": " + what_arg;
  187. return parse_error(id_, pos.chars_read_total, w.c_str());
  188. }
  189. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  190. {
  191. std::string w = exception::name("parse_error", id_) + "parse error" +
  192. (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") +
  193. ": " + what_arg;
  194. return parse_error(id_, byte_, w.c_str());
  195. }
  196. /*!
  197. @brief byte index of the parse error
  198. The byte index of the last read character in the input file.
  199. @note For an input with n bytes, 1 is the index of the first character and
  200. n+1 is the index of the terminating null byte or the end of file.
  201. This also holds true when reading a byte vector (CBOR or MessagePack).
  202. */
  203. const std::size_t byte;
  204. private:
  205. parse_error(int id_, std::size_t byte_, const char* what_arg)
  206. : exception(id_, what_arg), byte(byte_) {}
  207. static std::string position_string(const position_t& pos)
  208. {
  209. return " at line " + std::to_string(pos.lines_read + 1) +
  210. ", column " + std::to_string(pos.chars_read_current_line);
  211. }
  212. };
  213. /*!
  214. @brief exception indicating errors with iterators
  215. This exception is thrown if iterators passed to a library function do not match
  216. the expected semantics.
  217. Exceptions have ids 2xx.
  218. name / id | example message | description
  219. ----------------------------------- | --------------- | -------------------------
  220. 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.
  221. 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.
  222. 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.
  223. 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.
  224. 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.
  225. 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.
  226. 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.
  227. 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.
  228. 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.
  229. 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.
  230. 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.
  231. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  232. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  233. 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().
  234. @liveexample{The following code shows how an `invalid_iterator` exception can be
  235. caught.,invalid_iterator}
  236. @sa - @ref exception for the base class of the library exceptions
  237. @sa - @ref parse_error for exceptions indicating a parse error
  238. @sa - @ref type_error for exceptions indicating executing a member function with
  239. a wrong type
  240. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  241. @sa - @ref other_error for exceptions indicating other library errors
  242. @since version 3.0.0
  243. */
  244. class invalid_iterator : public exception
  245. {
  246. public:
  247. static invalid_iterator create(int id_, const std::string& what_arg)
  248. {
  249. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  250. return invalid_iterator(id_, w.c_str());
  251. }
  252. private:
  253. invalid_iterator(int id_, const char* what_arg)
  254. : exception(id_, what_arg) {}
  255. };
  256. /*!
  257. @brief exception indicating executing a member function with a wrong type
  258. This exception is thrown in case of a type error; that is, a library function is
  259. executed on a JSON value whose type does not match the expected semantics.
  260. Exceptions have ids 3xx.
  261. name / id | example message | description
  262. ----------------------------- | --------------- | -------------------------
  263. 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.
  264. 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.
  265. 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 &.
  266. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  267. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  268. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  269. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  270. 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.
  271. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  272. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  273. 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.
  274. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  275. 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.
  276. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  277. 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.
  278. 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. |
  279. 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) |
  280. @liveexample{The following code shows how a `type_error` exception can be
  281. caught.,type_error}
  282. @sa - @ref exception for the base class of the library exceptions
  283. @sa - @ref parse_error for exceptions indicating a parse error
  284. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  285. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  286. @sa - @ref other_error for exceptions indicating other library errors
  287. @since version 3.0.0
  288. */
  289. class type_error : public exception
  290. {
  291. public:
  292. static type_error create(int id_, const std::string& what_arg)
  293. {
  294. std::string w = exception::name("type_error", id_) + what_arg;
  295. return type_error(id_, w.c_str());
  296. }
  297. private:
  298. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  299. };
  300. /*!
  301. @brief exception indicating access out of the defined range
  302. This exception is thrown in case a library function is called on an input
  303. parameter that exceeds the expected range, for instance in case of array
  304. indices or nonexisting object keys.
  305. Exceptions have ids 4xx.
  306. name / id | example message | description
  307. ------------------------------- | --------------- | -------------------------
  308. 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.
  309. 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.
  310. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  311. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  312. 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.
  313. 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.
  314. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. |
  315. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  316. 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 |
  317. @liveexample{The following code shows how an `out_of_range` exception can be
  318. caught.,out_of_range}
  319. @sa - @ref exception for the base class of the library exceptions
  320. @sa - @ref parse_error for exceptions indicating a parse error
  321. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  322. @sa - @ref type_error for exceptions indicating executing a member function with
  323. a wrong type
  324. @sa - @ref other_error for exceptions indicating other library errors
  325. @since version 3.0.0
  326. */
  327. class out_of_range : public exception
  328. {
  329. public:
  330. static out_of_range create(int id_, const std::string& what_arg)
  331. {
  332. std::string w = exception::name("out_of_range", id_) + what_arg;
  333. return out_of_range(id_, w.c_str());
  334. }
  335. private:
  336. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  337. };
  338. /*!
  339. @brief exception indicating other library errors
  340. This exception is thrown in case of errors that cannot be classified with the
  341. other exception types.
  342. Exceptions have ids 5xx.
  343. name / id | example message | description
  344. ------------------------------ | --------------- | -------------------------
  345. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  346. @sa - @ref exception for the base class of the library exceptions
  347. @sa - @ref parse_error for exceptions indicating a parse error
  348. @sa - @ref invalid_iterator for exceptions indicating errors with iterators
  349. @sa - @ref type_error for exceptions indicating executing a member function with
  350. a wrong type
  351. @sa - @ref out_of_range for exceptions indicating access out of the defined range
  352. @liveexample{The following code shows how an `other_error` exception can be
  353. caught.,other_error}
  354. @since version 3.0.0
  355. */
  356. class other_error : public exception
  357. {
  358. public:
  359. static other_error create(int id_, const std::string& what_arg)
  360. {
  361. std::string w = exception::name("other_error", id_) + what_arg;
  362. return other_error(id_, w.c_str());
  363. }
  364. private:
  365. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  366. };
  367. } // namespace detail
  368. } // namespace nlohmann
  369. // #include <nlohmann/detail/macro_scope.hpp>
  370. #include <utility> // pair
  371. // This file contains all internal macro definitions
  372. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  373. // exclude unsupported compilers
  374. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  375. #if defined(__clang__)
  376. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  377. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  378. #endif
  379. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  380. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800
  381. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  382. #endif
  383. #endif
  384. #endif
  385. // disable float-equal warnings on GCC/clang
  386. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  387. #pragma GCC diagnostic push
  388. #pragma GCC diagnostic ignored "-Wfloat-equal"
  389. #endif
  390. // disable documentation warnings on clang
  391. #if defined(__clang__)
  392. #pragma GCC diagnostic push
  393. #pragma GCC diagnostic ignored "-Wdocumentation"
  394. #endif
  395. // allow for portable deprecation warnings
  396. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  397. #define JSON_DEPRECATED __attribute__((deprecated))
  398. #elif defined(_MSC_VER)
  399. #define JSON_DEPRECATED __declspec(deprecated)
  400. #else
  401. #define JSON_DEPRECATED
  402. #endif
  403. // allow for portable nodiscard warnings
  404. #if defined(__has_cpp_attribute)
  405. #if __has_cpp_attribute(nodiscard)
  406. #define JSON_NODISCARD [[nodiscard]]
  407. #elif __has_cpp_attribute(gnu::warn_unused_result)
  408. #define JSON_NODISCARD [[gnu::warn_unused_result]]
  409. #else
  410. #define JSON_NODISCARD
  411. #endif
  412. #else
  413. #define JSON_NODISCARD
  414. #endif
  415. // allow to disable exceptions
  416. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  417. #define JSON_THROW(exception) throw exception
  418. #define JSON_TRY try
  419. #define JSON_CATCH(exception) catch(exception)
  420. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  421. #else
  422. #include <cstdlib>
  423. #define JSON_THROW(exception) std::abort()
  424. #define JSON_TRY if(true)
  425. #define JSON_CATCH(exception) if(false)
  426. #define JSON_INTERNAL_CATCH(exception) if(false)
  427. #endif
  428. // override exception macros
  429. #if defined(JSON_THROW_USER)
  430. #undef JSON_THROW
  431. #define JSON_THROW JSON_THROW_USER
  432. #endif
  433. #if defined(JSON_TRY_USER)
  434. #undef JSON_TRY
  435. #define JSON_TRY JSON_TRY_USER
  436. #endif
  437. #if defined(JSON_CATCH_USER)
  438. #undef JSON_CATCH
  439. #define JSON_CATCH JSON_CATCH_USER
  440. #undef JSON_INTERNAL_CATCH
  441. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  442. #endif
  443. #if defined(JSON_INTERNAL_CATCH_USER)
  444. #undef JSON_INTERNAL_CATCH
  445. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  446. #endif
  447. // manual branch prediction
  448. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  449. #define JSON_LIKELY(x) __builtin_expect(x, 1)
  450. #define JSON_UNLIKELY(x) __builtin_expect(x, 0)
  451. #else
  452. #define JSON_LIKELY(x) x
  453. #define JSON_UNLIKELY(x) x
  454. #endif
  455. // C++ language standard detection
  456. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  457. #define JSON_HAS_CPP_17
  458. #define JSON_HAS_CPP_14
  459. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  460. #define JSON_HAS_CPP_14
  461. #endif
  462. /*!
  463. @brief macro to briefly define a mapping between an enum and JSON
  464. @def NLOHMANN_JSON_SERIALIZE_ENUM
  465. @since version 3.4.0
  466. */
  467. #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \
  468. template<typename BasicJsonType> \
  469. inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \
  470. { \
  471. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  472. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  473. auto it = std::find_if(std::begin(m), std::end(m), \
  474. [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  475. { \
  476. return ej_pair.first == e; \
  477. }); \
  478. j = ((it != std::end(m)) ? it : std::begin(m))->second; \
  479. } \
  480. template<typename BasicJsonType> \
  481. inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \
  482. { \
  483. static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \
  484. static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
  485. auto it = std::find_if(std::begin(m), std::end(m), \
  486. [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \
  487. { \
  488. return ej_pair.second == j; \
  489. }); \
  490. e = ((it != std::end(m)) ? it : std::begin(m))->first; \
  491. }
  492. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  493. // may be removed in the future once the class is split.
  494. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  495. template<template<typename, typename, typename...> class ObjectType, \
  496. template<typename, typename...> class ArrayType, \
  497. class StringType, class BooleanType, class NumberIntegerType, \
  498. class NumberUnsignedType, class NumberFloatType, \
  499. template<typename> class AllocatorType, \
  500. template<typename, typename = void> class JSONSerializer>
  501. #define NLOHMANN_BASIC_JSON_TPL \
  502. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  503. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  504. AllocatorType, JSONSerializer>
  505. // #include <nlohmann/detail/meta/cpp_future.hpp>
  506. #include <ciso646> // not
  507. #include <cstddef> // size_t
  508. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  509. namespace nlohmann
  510. {
  511. namespace detail
  512. {
  513. // alias templates to reduce boilerplate
  514. template<bool B, typename T = void>
  515. using enable_if_t = typename std::enable_if<B, T>::type;
  516. template<typename T>
  517. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  518. // implementation of C++14 index_sequence and affiliates
  519. // source: https://stackoverflow.com/a/32223343
  520. template<std::size_t... Ints>
  521. struct index_sequence
  522. {
  523. using type = index_sequence;
  524. using value_type = std::size_t;
  525. static constexpr std::size_t size() noexcept
  526. {
  527. return sizeof...(Ints);
  528. }
  529. };
  530. template<class Sequence1, class Sequence2>
  531. struct merge_and_renumber;
  532. template<std::size_t... I1, std::size_t... I2>
  533. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  534. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  535. template<std::size_t N>
  536. struct make_index_sequence
  537. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  538. typename make_index_sequence < N - N / 2 >::type > {};
  539. template<> struct make_index_sequence<0> : index_sequence<> {};
  540. template<> struct make_index_sequence<1> : index_sequence<0> {};
  541. template<typename... Ts>
  542. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  543. // dispatch utility (taken from ranges-v3)
  544. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  545. template<> struct priority_tag<0> {};
  546. // taken from ranges-v3
  547. template<typename T>
  548. struct static_const
  549. {
  550. static constexpr T value{};
  551. };
  552. template<typename T>
  553. constexpr T static_const<T>::value;
  554. } // namespace detail
  555. } // namespace nlohmann
  556. // #include <nlohmann/detail/meta/type_traits.hpp>
  557. #include <ciso646> // not
  558. #include <limits> // numeric_limits
  559. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  560. #include <utility> // declval
  561. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  562. #include <iterator> // random_access_iterator_tag
  563. // #include <nlohmann/detail/meta/void_t.hpp>
  564. namespace nlohmann
  565. {
  566. namespace detail
  567. {
  568. template <typename ...Ts> struct make_void
  569. {
  570. using type = void;
  571. };
  572. template <typename ...Ts> using void_t = typename make_void<Ts...>::type;
  573. } // namespace detail
  574. } // namespace nlohmann
  575. // #include <nlohmann/detail/meta/cpp_future.hpp>
  576. namespace nlohmann
  577. {
  578. namespace detail
  579. {
  580. template <typename It, typename = void>
  581. struct iterator_types {};
  582. template <typename It>
  583. struct iterator_types <
  584. It,
  585. void_t<typename It::difference_type, typename It::value_type, typename It::pointer,
  586. typename It::reference, typename It::iterator_category >>
  587. {
  588. using difference_type = typename It::difference_type;
  589. using value_type = typename It::value_type;
  590. using pointer = typename It::pointer;
  591. using reference = typename It::reference;
  592. using iterator_category = typename It::iterator_category;
  593. };
  594. // This is required as some compilers implement std::iterator_traits in a way that
  595. // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341.
  596. template <typename T, typename = void>
  597. struct iterator_traits
  598. {
  599. };
  600. template <typename T>
  601. struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >>
  602. : iterator_types<T>
  603. {
  604. };
  605. template <typename T>
  606. struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>>
  607. {
  608. using iterator_category = std::random_access_iterator_tag;
  609. using value_type = T;
  610. using difference_type = ptrdiff_t;
  611. using pointer = T*;
  612. using reference = T&;
  613. };
  614. } // namespace detail
  615. } // namespace nlohmann
  616. // #include <nlohmann/detail/macro_scope.hpp>
  617. // #include <nlohmann/detail/meta/cpp_future.hpp>
  618. // #include <nlohmann/detail/meta/detected.hpp>
  619. #include <type_traits>
  620. // #include <nlohmann/detail/meta/void_t.hpp>
  621. // http://en.cppreference.com/w/cpp/experimental/is_detected
  622. namespace nlohmann
  623. {
  624. namespace detail
  625. {
  626. struct nonesuch
  627. {
  628. nonesuch() = delete;
  629. ~nonesuch() = delete;
  630. nonesuch(nonesuch const&) = delete;
  631. nonesuch(nonesuch const&&) = delete;
  632. void operator=(nonesuch const&) = delete;
  633. void operator=(nonesuch&&) = delete;
  634. };
  635. template <class Default,
  636. class AlwaysVoid,
  637. template <class...> class Op,
  638. class... Args>
  639. struct detector
  640. {
  641. using value_t = std::false_type;
  642. using type = Default;
  643. };
  644. template <class Default, template <class...> class Op, class... Args>
  645. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  646. {
  647. using value_t = std::true_type;
  648. using type = Op<Args...>;
  649. };
  650. template <template <class...> class Op, class... Args>
  651. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  652. template <template <class...> class Op, class... Args>
  653. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  654. template <class Default, template <class...> class Op, class... Args>
  655. using detected_or = detector<Default, void, Op, Args...>;
  656. template <class Default, template <class...> class Op, class... Args>
  657. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  658. template <class Expected, template <class...> class Op, class... Args>
  659. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  660. template <class To, template <class...> class Op, class... Args>
  661. using is_detected_convertible =
  662. std::is_convertible<detected_t<Op, Args...>, To>;
  663. } // namespace detail
  664. } // namespace nlohmann
  665. // #include <nlohmann/json_fwd.hpp>
  666. #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
  667. #define INCLUDE_NLOHMANN_JSON_FWD_HPP_
  668. #include <cstdint> // int64_t, uint64_t
  669. #include <map> // map
  670. #include <memory> // allocator
  671. #include <string> // string
  672. #include <vector> // vector
  673. /*!
  674. @brief namespace for Niels Lohmann
  675. @see https://github.com/nlohmann
  676. @since version 1.0.0
  677. */
  678. namespace nlohmann
  679. {
  680. /*!
  681. @brief default JSONSerializer template argument
  682. This serializer ignores the template arguments and uses ADL
  683. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  684. for serialization.
  685. */
  686. template<typename T = void, typename SFINAE = void>
  687. struct adl_serializer;
  688. template<template<typename U, typename V, typename... Args> class ObjectType =
  689. std::map,
  690. template<typename U, typename... Args> class ArrayType = std::vector,
  691. class StringType = std::string, class BooleanType = bool,
  692. class NumberIntegerType = std::int64_t,
  693. class NumberUnsignedType = std::uint64_t,
  694. class NumberFloatType = double,
  695. template<typename U> class AllocatorType = std::allocator,
  696. template<typename T, typename SFINAE = void> class JSONSerializer =
  697. adl_serializer>
  698. class basic_json;
  699. /*!
  700. @brief JSON Pointer
  701. A JSON pointer defines a string syntax for identifying a specific value
  702. within a JSON document. It can be used with functions `at` and
  703. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  704. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  705. @since version 2.0.0
  706. */
  707. template<typename BasicJsonType>
  708. class json_pointer;
  709. /*!
  710. @brief default JSON class
  711. This type is the default specialization of the @ref basic_json class which
  712. uses the standard template types.
  713. @since version 1.0.0
  714. */
  715. using json = basic_json<>;
  716. } // namespace nlohmann
  717. #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_
  718. namespace nlohmann
  719. {
  720. /*!
  721. @brief detail namespace with internal helper functions
  722. This namespace collects functions that should not be exposed,
  723. implementations of some @ref basic_json methods, and meta-programming helpers.
  724. @since version 2.1.0
  725. */
  726. namespace detail
  727. {
  728. /////////////
  729. // helpers //
  730. /////////////
  731. // Note to maintainers:
  732. //
  733. // Every trait in this file expects a non CV-qualified type.
  734. // The only exceptions are in the 'aliases for detected' section
  735. // (i.e. those of the form: decltype(T::member_function(std::declval<T>())))
  736. //
  737. // In this case, T has to be properly CV-qualified to constraint the function arguments
  738. // (e.g. to_json(BasicJsonType&, const T&))
  739. template<typename> struct is_basic_json : std::false_type {};
  740. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  741. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  742. //////////////////////////
  743. // aliases for detected //
  744. //////////////////////////
  745. template <typename T>
  746. using mapped_type_t = typename T::mapped_type;
  747. template <typename T>
  748. using key_type_t = typename T::key_type;
  749. template <typename T>
  750. using value_type_t = typename T::value_type;
  751. template <typename T>
  752. using difference_type_t = typename T::difference_type;
  753. template <typename T>
  754. using pointer_t = typename T::pointer;
  755. template <typename T>
  756. using reference_t = typename T::reference;
  757. template <typename T>
  758. using iterator_category_t = typename T::iterator_category;
  759. template <typename T>
  760. using iterator_t = typename T::iterator;
  761. template <typename T, typename... Args>
  762. using to_json_function = decltype(T::to_json(std::declval<Args>()...));
  763. template <typename T, typename... Args>
  764. using from_json_function = decltype(T::from_json(std::declval<Args>()...));
  765. template <typename T, typename U>
  766. using get_template_function = decltype(std::declval<T>().template get<U>());
  767. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  768. template <typename BasicJsonType, typename T, typename = void>
  769. struct has_from_json : std::false_type {};
  770. template <typename BasicJsonType, typename T>
  771. struct has_from_json<BasicJsonType, T,
  772. enable_if_t<not is_basic_json<T>::value>>
  773. {
  774. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  775. static constexpr bool value =
  776. is_detected_exact<void, from_json_function, serializer,
  777. const BasicJsonType&, T&>::value;
  778. };
  779. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  780. // this overload is used for non-default-constructible user-defined-types
  781. template <typename BasicJsonType, typename T, typename = void>
  782. struct has_non_default_from_json : std::false_type {};
  783. template<typename BasicJsonType, typename T>
  784. struct has_non_default_from_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  785. {
  786. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  787. static constexpr bool value =
  788. is_detected_exact<T, from_json_function, serializer,
  789. const BasicJsonType&>::value;
  790. };
  791. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  792. // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion.
  793. template <typename BasicJsonType, typename T, typename = void>
  794. struct has_to_json : std::false_type {};
  795. template <typename BasicJsonType, typename T>
  796. struct has_to_json<BasicJsonType, T, enable_if_t<not is_basic_json<T>::value>>
  797. {
  798. using serializer = typename BasicJsonType::template json_serializer<T, void>;
  799. static constexpr bool value =
  800. is_detected_exact<void, to_json_function, serializer, BasicJsonType&,
  801. T>::value;
  802. };
  803. ///////////////////
  804. // is_ functions //
  805. ///////////////////
  806. template <typename T, typename = void>
  807. struct is_iterator_traits : std::false_type {};
  808. template <typename T>
  809. struct is_iterator_traits<iterator_traits<T>>
  810. {
  811. private:
  812. using traits = iterator_traits<T>;
  813. public:
  814. static constexpr auto value =
  815. is_detected<value_type_t, traits>::value &&
  816. is_detected<difference_type_t, traits>::value &&
  817. is_detected<pointer_t, traits>::value &&
  818. is_detected<iterator_category_t, traits>::value &&
  819. is_detected<reference_t, traits>::value;
  820. };
  821. // source: https://stackoverflow.com/a/37193089/4116453
  822. template <typename T, typename = void>
  823. struct is_complete_type : std::false_type {};
  824. template <typename T>
  825. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  826. template <typename BasicJsonType, typename CompatibleObjectType,
  827. typename = void>
  828. struct is_compatible_object_type_impl : std::false_type {};
  829. template <typename BasicJsonType, typename CompatibleObjectType>
  830. struct is_compatible_object_type_impl <
  831. BasicJsonType, CompatibleObjectType,
  832. enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value and
  833. is_detected<key_type_t, CompatibleObjectType>::value >>
  834. {
  835. using object_t = typename BasicJsonType::object_t;
  836. // macOS's is_constructible does not play well with nonesuch...
  837. static constexpr bool value =
  838. std::is_constructible<typename object_t::key_type,
  839. typename CompatibleObjectType::key_type>::value and
  840. std::is_constructible<typename object_t::mapped_type,
  841. typename CompatibleObjectType::mapped_type>::value;
  842. };
  843. template <typename BasicJsonType, typename CompatibleObjectType>
  844. struct is_compatible_object_type
  845. : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
  846. template <typename BasicJsonType, typename ConstructibleObjectType,
  847. typename = void>
  848. struct is_constructible_object_type_impl : std::false_type {};
  849. template <typename BasicJsonType, typename ConstructibleObjectType>
  850. struct is_constructible_object_type_impl <
  851. BasicJsonType, ConstructibleObjectType,
  852. enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value and
  853. is_detected<key_type_t, ConstructibleObjectType>::value >>
  854. {
  855. using object_t = typename BasicJsonType::object_t;
  856. static constexpr bool value =
  857. (std::is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value and
  858. std::is_same<typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type>::value) or
  859. (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value or
  860. has_non_default_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type >::value);
  861. };
  862. template <typename BasicJsonType, typename ConstructibleObjectType>
  863. struct is_constructible_object_type
  864. : is_constructible_object_type_impl<BasicJsonType,
  865. ConstructibleObjectType> {};
  866. template <typename BasicJsonType, typename CompatibleStringType,
  867. typename = void>
  868. struct is_compatible_string_type_impl : std::false_type {};
  869. template <typename BasicJsonType, typename CompatibleStringType>
  870. struct is_compatible_string_type_impl <
  871. BasicJsonType, CompatibleStringType,
  872. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  873. value_type_t, CompatibleStringType>::value >>
  874. {
  875. static constexpr auto value =
  876. std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value;
  877. };
  878. template <typename BasicJsonType, typename ConstructibleStringType>
  879. struct is_compatible_string_type
  880. : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  881. template <typename BasicJsonType, typename ConstructibleStringType,
  882. typename = void>
  883. struct is_constructible_string_type_impl : std::false_type {};
  884. template <typename BasicJsonType, typename ConstructibleStringType>
  885. struct is_constructible_string_type_impl <
  886. BasicJsonType, ConstructibleStringType,
  887. enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type,
  888. value_type_t, ConstructibleStringType>::value >>
  889. {
  890. static constexpr auto value =
  891. std::is_constructible<ConstructibleStringType,
  892. typename BasicJsonType::string_t>::value;
  893. };
  894. template <typename BasicJsonType, typename ConstructibleStringType>
  895. struct is_constructible_string_type
  896. : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {};
  897. template <typename BasicJsonType, typename CompatibleArrayType, typename = void>
  898. struct is_compatible_array_type_impl : std::false_type {};
  899. template <typename BasicJsonType, typename CompatibleArrayType>
  900. struct is_compatible_array_type_impl <
  901. BasicJsonType, CompatibleArrayType,
  902. enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value and
  903. is_detected<iterator_t, CompatibleArrayType>::value and
  904. // This is needed because json_reverse_iterator has a ::iterator type...
  905. // Therefore it is detected as a CompatibleArrayType.
  906. // The real fix would be to have an Iterable concept.
  907. not is_iterator_traits<
  908. iterator_traits<CompatibleArrayType>>::value >>
  909. {
  910. static constexpr bool value =
  911. std::is_constructible<BasicJsonType,
  912. typename CompatibleArrayType::value_type>::value;
  913. };
  914. template <typename BasicJsonType, typename CompatibleArrayType>
  915. struct is_compatible_array_type
  916. : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {};
  917. template <typename BasicJsonType, typename ConstructibleArrayType, typename = void>
  918. struct is_constructible_array_type_impl : std::false_type {};
  919. template <typename BasicJsonType, typename ConstructibleArrayType>
  920. struct is_constructible_array_type_impl <
  921. BasicJsonType, ConstructibleArrayType,
  922. enable_if_t<std::is_same<ConstructibleArrayType,
  923. typename BasicJsonType::value_type>::value >>
  924. : std::true_type {};
  925. template <typename BasicJsonType, typename ConstructibleArrayType>
  926. struct is_constructible_array_type_impl <
  927. BasicJsonType, ConstructibleArrayType,
  928. enable_if_t<not std::is_same<ConstructibleArrayType,
  929. typename BasicJsonType::value_type>::value and
  930. is_detected<value_type_t, ConstructibleArrayType>::value and
  931. is_detected<iterator_t, ConstructibleArrayType>::value and
  932. is_complete_type<
  933. detected_t<value_type_t, ConstructibleArrayType>>::value >>
  934. {
  935. static constexpr bool value =
  936. // This is needed because json_reverse_iterator has a ::iterator type,
  937. // furthermore, std::back_insert_iterator (and other iterators) have a base class `iterator`...
  938. // Therefore it is detected as a ConstructibleArrayType.
  939. // The real fix would be to have an Iterable concept.
  940. not is_iterator_traits <
  941. iterator_traits<ConstructibleArrayType >>::value and
  942. (std::is_same<typename ConstructibleArrayType::value_type, typename BasicJsonType::array_t::value_type>::value or
  943. has_from_json<BasicJsonType,
  944. typename ConstructibleArrayType::value_type>::value or
  945. has_non_default_from_json <
  946. BasicJsonType, typename ConstructibleArrayType::value_type >::value);
  947. };
  948. template <typename BasicJsonType, typename ConstructibleArrayType>
  949. struct is_constructible_array_type
  950. : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {};
  951. template <typename RealIntegerType, typename CompatibleNumberIntegerType,
  952. typename = void>
  953. struct is_compatible_integer_type_impl : std::false_type {};
  954. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  955. struct is_compatible_integer_type_impl <
  956. RealIntegerType, CompatibleNumberIntegerType,
  957. enable_if_t<std::is_integral<RealIntegerType>::value and
  958. std::is_integral<CompatibleNumberIntegerType>::value and
  959. not std::is_same<bool, CompatibleNumberIntegerType>::value >>
  960. {
  961. // is there an assert somewhere on overflows?
  962. using RealLimits = std::numeric_limits<RealIntegerType>;
  963. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  964. static constexpr auto value =
  965. std::is_constructible<RealIntegerType,
  966. CompatibleNumberIntegerType>::value and
  967. CompatibleLimits::is_integer and
  968. RealLimits::is_signed == CompatibleLimits::is_signed;
  969. };
  970. template <typename RealIntegerType, typename CompatibleNumberIntegerType>
  971. struct is_compatible_integer_type
  972. : is_compatible_integer_type_impl<RealIntegerType,
  973. CompatibleNumberIntegerType> {};
  974. template <typename BasicJsonType, typename CompatibleType, typename = void>
  975. struct is_compatible_type_impl: std::false_type {};
  976. template <typename BasicJsonType, typename CompatibleType>
  977. struct is_compatible_type_impl <
  978. BasicJsonType, CompatibleType,
  979. enable_if_t<is_complete_type<CompatibleType>::value >>
  980. {
  981. static constexpr bool value =
  982. has_to_json<BasicJsonType, CompatibleType>::value;
  983. };
  984. template <typename BasicJsonType, typename CompatibleType>
  985. struct is_compatible_type
  986. : is_compatible_type_impl<BasicJsonType, CompatibleType> {};
  987. } // namespace detail
  988. } // namespace nlohmann
  989. // #include <nlohmann/detail/value_t.hpp>
  990. #include <array> // array
  991. #include <ciso646> // and
  992. #include <cstddef> // size_t
  993. #include <cstdint> // uint8_t
  994. #include <string> // string
  995. namespace nlohmann
  996. {
  997. namespace detail
  998. {
  999. ///////////////////////////
  1000. // JSON type enumeration //
  1001. ///////////////////////////
  1002. /*!
  1003. @brief the JSON type enumeration
  1004. This enumeration collects the different JSON types. It is internally used to
  1005. distinguish the stored values, and the functions @ref basic_json::is_null(),
  1006. @ref basic_json::is_object(), @ref basic_json::is_array(),
  1007. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  1008. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  1009. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  1010. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  1011. @ref basic_json::is_structured() rely on it.
  1012. @note There are three enumeration entries (number_integer, number_unsigned, and
  1013. number_float), because the library distinguishes these three types for numbers:
  1014. @ref basic_json::number_unsigned_t is used for unsigned integers,
  1015. @ref basic_json::number_integer_t is used for signed integers, and
  1016. @ref basic_json::number_float_t is used for floating-point numbers or to
  1017. approximate integers which do not fit in the limits of their respective type.
  1018. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  1019. value with the default value for a given type
  1020. @since version 1.0.0
  1021. */
  1022. enum class value_t : std::uint8_t
  1023. {
  1024. null, ///< null value
  1025. object, ///< object (unordered set of name/value pairs)
  1026. array, ///< array (ordered collection of values)
  1027. string, ///< string value
  1028. boolean, ///< boolean value
  1029. number_integer, ///< number value (signed integer)
  1030. number_unsigned, ///< number value (unsigned integer)
  1031. number_float, ///< number value (floating-point)
  1032. discarded ///< discarded by the the parser callback function
  1033. };
  1034. /*!
  1035. @brief comparison operator for JSON types
  1036. Returns an ordering that is similar to Python:
  1037. - order: null < boolean < number < object < array < string
  1038. - furthermore, each type is not smaller than itself
  1039. - discarded values are not comparable
  1040. @since version 1.0.0
  1041. */
  1042. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  1043. {
  1044. static constexpr std::array<std::uint8_t, 8> order = {{
  1045. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  1046. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  1047. }
  1048. };
  1049. const auto l_index = static_cast<std::size_t>(lhs);
  1050. const auto r_index = static_cast<std::size_t>(rhs);
  1051. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  1052. }
  1053. } // namespace detail
  1054. } // namespace nlohmann
  1055. namespace nlohmann
  1056. {
  1057. namespace detail
  1058. {
  1059. template<typename BasicJsonType>
  1060. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  1061. {
  1062. if (JSON_UNLIKELY(not j.is_null()))
  1063. {
  1064. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  1065. }
  1066. n = nullptr;
  1067. }
  1068. // overloads for basic_json template parameters
  1069. template<typename BasicJsonType, typename ArithmeticType,
  1070. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  1071. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1072. int> = 0>
  1073. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  1074. {
  1075. switch (static_cast<value_t>(j))
  1076. {
  1077. case value_t::number_unsigned:
  1078. {
  1079. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1080. break;
  1081. }
  1082. case value_t::number_integer:
  1083. {
  1084. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1085. break;
  1086. }
  1087. case value_t::number_float:
  1088. {
  1089. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1090. break;
  1091. }
  1092. default:
  1093. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1094. }
  1095. }
  1096. template<typename BasicJsonType>
  1097. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  1098. {
  1099. if (JSON_UNLIKELY(not j.is_boolean()))
  1100. {
  1101. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  1102. }
  1103. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  1104. }
  1105. template<typename BasicJsonType>
  1106. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  1107. {
  1108. if (JSON_UNLIKELY(not j.is_string()))
  1109. {
  1110. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1111. }
  1112. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1113. }
  1114. template <
  1115. typename BasicJsonType, typename ConstructibleStringType,
  1116. enable_if_t <
  1117. is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and
  1118. not std::is_same<typename BasicJsonType::string_t,
  1119. ConstructibleStringType>::value,
  1120. int > = 0 >
  1121. void from_json(const BasicJsonType& j, ConstructibleStringType& s)
  1122. {
  1123. if (JSON_UNLIKELY(not j.is_string()))
  1124. {
  1125. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  1126. }
  1127. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  1128. }
  1129. template<typename BasicJsonType>
  1130. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  1131. {
  1132. get_arithmetic_value(j, val);
  1133. }
  1134. template<typename BasicJsonType>
  1135. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  1136. {
  1137. get_arithmetic_value(j, val);
  1138. }
  1139. template<typename BasicJsonType>
  1140. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  1141. {
  1142. get_arithmetic_value(j, val);
  1143. }
  1144. template<typename BasicJsonType, typename EnumType,
  1145. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1146. void from_json(const BasicJsonType& j, EnumType& e)
  1147. {
  1148. typename std::underlying_type<EnumType>::type val;
  1149. get_arithmetic_value(j, val);
  1150. e = static_cast<EnumType>(val);
  1151. }
  1152. // forward_list doesn't have an insert method
  1153. template<typename BasicJsonType, typename T, typename Allocator,
  1154. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1155. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  1156. {
  1157. if (JSON_UNLIKELY(not j.is_array()))
  1158. {
  1159. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1160. }
  1161. std::transform(j.rbegin(), j.rend(),
  1162. std::front_inserter(l), [](const BasicJsonType & i)
  1163. {
  1164. return i.template get<T>();
  1165. });
  1166. }
  1167. // valarray doesn't have an insert method
  1168. template<typename BasicJsonType, typename T,
  1169. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1170. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  1171. {
  1172. if (JSON_UNLIKELY(not j.is_array()))
  1173. {
  1174. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1175. }
  1176. l.resize(j.size());
  1177. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  1178. }
  1179. template<typename BasicJsonType>
  1180. void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
  1181. {
  1182. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  1183. }
  1184. template <typename BasicJsonType, typename T, std::size_t N>
  1185. auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
  1186. priority_tag<2> /*unused*/)
  1187. -> decltype(j.template get<T>(), void())
  1188. {
  1189. for (std::size_t i = 0; i < N; ++i)
  1190. {
  1191. arr[i] = j.at(i).template get<T>();
  1192. }
  1193. }
  1194. template<typename BasicJsonType, typename ConstructibleArrayType>
  1195. auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
  1196. -> decltype(
  1197. arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
  1198. j.template get<typename ConstructibleArrayType::value_type>(),
  1199. void())
  1200. {
  1201. using std::end;
  1202. arr.reserve(j.size());
  1203. std::transform(j.begin(), j.end(),
  1204. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1205. {
  1206. // get<BasicJsonType>() returns *this, this won't call a from_json
  1207. // method when value_type is BasicJsonType
  1208. return i.template get<typename ConstructibleArrayType::value_type>();
  1209. });
  1210. }
  1211. template <typename BasicJsonType, typename ConstructibleArrayType>
  1212. void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
  1213. priority_tag<0> /*unused*/)
  1214. {
  1215. using std::end;
  1216. std::transform(
  1217. j.begin(), j.end(), std::inserter(arr, end(arr)),
  1218. [](const BasicJsonType & i)
  1219. {
  1220. // get<BasicJsonType>() returns *this, this won't call a from_json
  1221. // method when value_type is BasicJsonType
  1222. return i.template get<typename ConstructibleArrayType::value_type>();
  1223. });
  1224. }
  1225. template <typename BasicJsonType, typename ConstructibleArrayType,
  1226. enable_if_t <
  1227. is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and
  1228. not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and
  1229. not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and
  1230. not is_basic_json<ConstructibleArrayType>::value,
  1231. int > = 0 >
  1232. auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
  1233. -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
  1234. j.template get<typename ConstructibleArrayType::value_type>(),
  1235. void())
  1236. {
  1237. if (JSON_UNLIKELY(not j.is_array()))
  1238. {
  1239. JSON_THROW(type_error::create(302, "type must be array, but is " +
  1240. std::string(j.type_name())));
  1241. }
  1242. from_json_array_impl(j, arr, priority_tag<3> {});
  1243. }
  1244. template<typename BasicJsonType, typename ConstructibleObjectType,
  1245. enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
  1246. void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
  1247. {
  1248. if (JSON_UNLIKELY(not j.is_object()))
  1249. {
  1250. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  1251. }
  1252. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  1253. using value_type = typename ConstructibleObjectType::value_type;
  1254. std::transform(
  1255. inner_object->begin(), inner_object->end(),
  1256. std::inserter(obj, obj.begin()),
  1257. [](typename BasicJsonType::object_t::value_type const & p)
  1258. {
  1259. return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
  1260. });
  1261. }
  1262. // overload for arithmetic types, not chosen for basic_json template arguments
  1263. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1264. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1265. // an arithmetic type?
  1266. template<typename BasicJsonType, typename ArithmeticType,
  1267. enable_if_t <
  1268. std::is_arithmetic<ArithmeticType>::value and
  1269. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1270. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1271. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1272. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1273. int> = 0>
  1274. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1275. {
  1276. switch (static_cast<value_t>(j))
  1277. {
  1278. case value_t::number_unsigned:
  1279. {
  1280. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1281. break;
  1282. }
  1283. case value_t::number_integer:
  1284. {
  1285. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1286. break;
  1287. }
  1288. case value_t::number_float:
  1289. {
  1290. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1291. break;
  1292. }
  1293. case value_t::boolean:
  1294. {
  1295. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1296. break;
  1297. }
  1298. default:
  1299. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1300. }
  1301. }
  1302. template<typename BasicJsonType, typename A1, typename A2>
  1303. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1304. {
  1305. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1306. }
  1307. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1308. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/)
  1309. {
  1310. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1311. }
  1312. template<typename BasicJsonType, typename... Args>
  1313. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1314. {
  1315. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1316. }
  1317. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  1318. typename = enable_if_t<not std::is_constructible<
  1319. typename BasicJsonType::string_t, Key>::value>>
  1320. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  1321. {
  1322. if (JSON_UNLIKELY(not j.is_array()))
  1323. {
  1324. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1325. }
  1326. for (const auto& p : j)
  1327. {
  1328. if (JSON_UNLIKELY(not p.is_array()))
  1329. {
  1330. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1331. }
  1332. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1333. }
  1334. }
  1335. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  1336. typename = enable_if_t<not std::is_constructible<
  1337. typename BasicJsonType::string_t, Key>::value>>
  1338. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  1339. {
  1340. if (JSON_UNLIKELY(not j.is_array()))
  1341. {
  1342. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1343. }
  1344. for (const auto& p : j)
  1345. {
  1346. if (JSON_UNLIKELY(not p.is_array()))
  1347. {
  1348. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1349. }
  1350. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1351. }
  1352. }
  1353. struct from_json_fn
  1354. {
  1355. template<typename BasicJsonType, typename T>
  1356. auto operator()(const BasicJsonType& j, T& val) const
  1357. noexcept(noexcept(from_json(j, val)))
  1358. -> decltype(from_json(j, val), void())
  1359. {
  1360. return from_json(j, val);
  1361. }
  1362. };
  1363. } // namespace detail
  1364. /// namespace to hold default `from_json` function
  1365. /// to see why this is required:
  1366. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  1367. namespace
  1368. {
  1369. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1370. } // namespace
  1371. } // namespace nlohmann
  1372. // #include <nlohmann/detail/conversions/to_json.hpp>
  1373. #include <algorithm> // copy
  1374. #include <ciso646> // or, and, not
  1375. #include <iterator> // begin, end
  1376. #include <string> // string
  1377. #include <tuple> // tuple, get
  1378. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  1379. #include <utility> // move, forward, declval, pair
  1380. #include <valarray> // valarray
  1381. #include <vector> // vector
  1382. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  1383. #include <cstddef> // size_t
  1384. #include <iterator> // input_iterator_tag
  1385. #include <string> // string, to_string
  1386. #include <tuple> // tuple_size, get, tuple_element
  1387. // #include <nlohmann/detail/meta/type_traits.hpp>
  1388. // #include <nlohmann/detail/value_t.hpp>
  1389. namespace nlohmann
  1390. {
  1391. namespace detail
  1392. {
  1393. template <typename IteratorType> class iteration_proxy_value
  1394. {
  1395. public:
  1396. using difference_type = std::ptrdiff_t;
  1397. using value_type = iteration_proxy_value;
  1398. using pointer = value_type * ;
  1399. using reference = value_type & ;
  1400. using iterator_category = std::input_iterator_tag;
  1401. private:
  1402. /// the iterator
  1403. IteratorType anchor;
  1404. /// an index for arrays (used to create key names)
  1405. std::size_t array_index = 0;
  1406. /// last stringified array index
  1407. mutable std::size_t array_index_last = 0;
  1408. /// a string representation of the array index
  1409. mutable std::string array_index_str = "0";
  1410. /// an empty string (to return a reference for primitive values)
  1411. const std::string empty_str = "";
  1412. public:
  1413. explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {}
  1414. /// dereference operator (needed for range-based for)
  1415. iteration_proxy_value& operator*()
  1416. {
  1417. return *this;
  1418. }
  1419. /// increment operator (needed for range-based for)
  1420. iteration_proxy_value& operator++()
  1421. {
  1422. ++anchor;
  1423. ++array_index;
  1424. return *this;
  1425. }
  1426. /// equality operator (needed for InputIterator)
  1427. bool operator==(const iteration_proxy_value& o) const
  1428. {
  1429. return anchor == o.anchor;
  1430. }
  1431. /// inequality operator (needed for range-based for)
  1432. bool operator!=(const iteration_proxy_value& o) const
  1433. {
  1434. return anchor != o.anchor;
  1435. }
  1436. /// return key of the iterator
  1437. const std::string& key() const
  1438. {
  1439. assert(anchor.m_object != nullptr);
  1440. switch (anchor.m_object->type())
  1441. {
  1442. // use integer array index as key
  1443. case value_t::array:
  1444. {
  1445. if (array_index != array_index_last)
  1446. {
  1447. array_index_str = std::to_string(array_index);
  1448. array_index_last = array_index;
  1449. }
  1450. return array_index_str;
  1451. }
  1452. // use key from the object
  1453. case value_t::object:
  1454. return anchor.key();
  1455. // use an empty key for all primitive types
  1456. default:
  1457. return empty_str;
  1458. }
  1459. }
  1460. /// return value of the iterator
  1461. typename IteratorType::reference value() const
  1462. {
  1463. return anchor.value();
  1464. }
  1465. };
  1466. /// proxy class for the items() function
  1467. template<typename IteratorType> class iteration_proxy
  1468. {
  1469. private:
  1470. /// the container to iterate
  1471. typename IteratorType::reference container;
  1472. public:
  1473. /// construct iteration proxy from a container
  1474. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  1475. : container(cont) {}
  1476. /// return iterator begin (needed for range-based for)
  1477. iteration_proxy_value<IteratorType> begin() noexcept
  1478. {
  1479. return iteration_proxy_value<IteratorType>(container.begin());
  1480. }
  1481. /// return iterator end (needed for range-based for)
  1482. iteration_proxy_value<IteratorType> end() noexcept
  1483. {
  1484. return iteration_proxy_value<IteratorType>(container.end());
  1485. }
  1486. };
  1487. // Structured Bindings Support
  1488. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1489. // And see https://github.com/nlohmann/json/pull/1391
  1490. template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0>
  1491. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key())
  1492. {
  1493. return i.key();
  1494. }
  1495. // Structured Bindings Support
  1496. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1497. // And see https://github.com/nlohmann/json/pull/1391
  1498. template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0>
  1499. auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value())
  1500. {
  1501. return i.value();
  1502. }
  1503. } // namespace detail
  1504. } // namespace nlohmann
  1505. // The Addition to the STD Namespace is required to add
  1506. // Structured Bindings Support to the iteration_proxy_value class
  1507. // For further reference see https://blog.tartanllama.xyz/structured-bindings/
  1508. // And see https://github.com/nlohmann/json/pull/1391
  1509. namespace std
  1510. {
  1511. #if defined(__clang__)
  1512. // Fix: https://github.com/nlohmann/json/issues/1401
  1513. #pragma clang diagnostic push
  1514. #pragma clang diagnostic ignored "-Wmismatched-tags"
  1515. #endif
  1516. template <typename IteratorType>
  1517. class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>>
  1518. : public std::integral_constant<std::size_t, 2> {};
  1519. template <std::size_t N, typename IteratorType>
  1520. class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >>
  1521. {
  1522. public:
  1523. using type = decltype(
  1524. get<N>(std::declval <
  1525. ::nlohmann::detail::iteration_proxy_value<IteratorType >> ()));
  1526. };
  1527. #if defined(__clang__)
  1528. #pragma clang diagnostic pop
  1529. #endif
  1530. } // namespace std
  1531. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1532. // #include <nlohmann/detail/meta/type_traits.hpp>
  1533. // #include <nlohmann/detail/value_t.hpp>
  1534. namespace nlohmann
  1535. {
  1536. namespace detail
  1537. {
  1538. //////////////////
  1539. // constructors //
  1540. //////////////////
  1541. template<value_t> struct external_constructor;
  1542. template<>
  1543. struct external_constructor<value_t::boolean>
  1544. {
  1545. template<typename BasicJsonType>
  1546. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  1547. {
  1548. j.m_type = value_t::boolean;
  1549. j.m_value = b;
  1550. j.assert_invariant();
  1551. }
  1552. };
  1553. template<>
  1554. struct external_constructor<value_t::string>
  1555. {
  1556. template<typename BasicJsonType>
  1557. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  1558. {
  1559. j.m_type = value_t::string;
  1560. j.m_value = s;
  1561. j.assert_invariant();
  1562. }
  1563. template<typename BasicJsonType>
  1564. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1565. {
  1566. j.m_type = value_t::string;
  1567. j.m_value = std::move(s);
  1568. j.assert_invariant();
  1569. }
  1570. template<typename BasicJsonType, typename CompatibleStringType,
  1571. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  1572. int> = 0>
  1573. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  1574. {
  1575. j.m_type = value_t::string;
  1576. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  1577. j.assert_invariant();
  1578. }
  1579. };
  1580. template<>
  1581. struct external_constructor<value_t::number_float>
  1582. {
  1583. template<typename BasicJsonType>
  1584. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  1585. {
  1586. j.m_type = value_t::number_float;
  1587. j.m_value = val;
  1588. j.assert_invariant();
  1589. }
  1590. };
  1591. template<>
  1592. struct external_constructor<value_t::number_unsigned>
  1593. {
  1594. template<typename BasicJsonType>
  1595. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  1596. {
  1597. j.m_type = value_t::number_unsigned;
  1598. j.m_value = val;
  1599. j.assert_invariant();
  1600. }
  1601. };
  1602. template<>
  1603. struct external_constructor<value_t::number_integer>
  1604. {
  1605. template<typename BasicJsonType>
  1606. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  1607. {
  1608. j.m_type = value_t::number_integer;
  1609. j.m_value = val;
  1610. j.assert_invariant();
  1611. }
  1612. };
  1613. template<>
  1614. struct external_constructor<value_t::array>
  1615. {
  1616. template<typename BasicJsonType>
  1617. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  1618. {
  1619. j.m_type = value_t::array;
  1620. j.m_value = arr;
  1621. j.assert_invariant();
  1622. }
  1623. template<typename BasicJsonType>
  1624. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1625. {
  1626. j.m_type = value_t::array;
  1627. j.m_value = std::move(arr);
  1628. j.assert_invariant();
  1629. }
  1630. template<typename BasicJsonType, typename CompatibleArrayType,
  1631. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  1632. int> = 0>
  1633. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  1634. {
  1635. using std::begin;
  1636. using std::end;
  1637. j.m_type = value_t::array;
  1638. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  1639. j.assert_invariant();
  1640. }
  1641. template<typename BasicJsonType>
  1642. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  1643. {
  1644. j.m_type = value_t::array;
  1645. j.m_value = value_t::array;
  1646. j.m_value.array->reserve(arr.size());
  1647. for (const bool x : arr)
  1648. {
  1649. j.m_value.array->push_back(x);
  1650. }
  1651. j.assert_invariant();
  1652. }
  1653. template<typename BasicJsonType, typename T,
  1654. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1655. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  1656. {
  1657. j.m_type = value_t::array;
  1658. j.m_value = value_t::array;
  1659. j.m_value.array->resize(arr.size());
  1660. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  1661. j.assert_invariant();
  1662. }
  1663. };
  1664. template<>
  1665. struct external_constructor<value_t::object>
  1666. {
  1667. template<typename BasicJsonType>
  1668. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  1669. {
  1670. j.m_type = value_t::object;
  1671. j.m_value = obj;
  1672. j.assert_invariant();
  1673. }
  1674. template<typename BasicJsonType>
  1675. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1676. {
  1677. j.m_type = value_t::object;
  1678. j.m_value = std::move(obj);
  1679. j.assert_invariant();
  1680. }
  1681. template<typename BasicJsonType, typename CompatibleObjectType,
  1682. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  1683. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  1684. {
  1685. using std::begin;
  1686. using std::end;
  1687. j.m_type = value_t::object;
  1688. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  1689. j.assert_invariant();
  1690. }
  1691. };
  1692. /////////////
  1693. // to_json //
  1694. /////////////
  1695. template<typename BasicJsonType, typename T,
  1696. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  1697. void to_json(BasicJsonType& j, T b) noexcept
  1698. {
  1699. external_constructor<value_t::boolean>::construct(j, b);
  1700. }
  1701. template<typename BasicJsonType, typename CompatibleString,
  1702. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  1703. void to_json(BasicJsonType& j, const CompatibleString& s)
  1704. {
  1705. external_constructor<value_t::string>::construct(j, s);
  1706. }
  1707. template<typename BasicJsonType>
  1708. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1709. {
  1710. external_constructor<value_t::string>::construct(j, std::move(s));
  1711. }
  1712. template<typename BasicJsonType, typename FloatType,
  1713. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  1714. void to_json(BasicJsonType& j, FloatType val) noexcept
  1715. {
  1716. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  1717. }
  1718. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  1719. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  1720. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  1721. {
  1722. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  1723. }
  1724. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  1725. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  1726. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  1727. {
  1728. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  1729. }
  1730. template<typename BasicJsonType, typename EnumType,
  1731. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1732. void to_json(BasicJsonType& j, EnumType e) noexcept
  1733. {
  1734. using underlying_type = typename std::underlying_type<EnumType>::type;
  1735. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  1736. }
  1737. template<typename BasicJsonType>
  1738. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  1739. {
  1740. external_constructor<value_t::array>::construct(j, e);
  1741. }
  1742. template <typename BasicJsonType, typename CompatibleArrayType,
  1743. enable_if_t<is_compatible_array_type<BasicJsonType,
  1744. CompatibleArrayType>::value and
  1745. not is_compatible_object_type<
  1746. BasicJsonType, CompatibleArrayType>::value and
  1747. not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and
  1748. not is_basic_json<CompatibleArrayType>::value,
  1749. int> = 0>
  1750. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  1751. {
  1752. external_constructor<value_t::array>::construct(j, arr);
  1753. }
  1754. template<typename BasicJsonType, typename T,
  1755. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1756. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  1757. {
  1758. external_constructor<value_t::array>::construct(j, std::move(arr));
  1759. }
  1760. template<typename BasicJsonType>
  1761. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1762. {
  1763. external_constructor<value_t::array>::construct(j, std::move(arr));
  1764. }
  1765. template<typename BasicJsonType, typename CompatibleObjectType,
  1766. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0>
  1767. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  1768. {
  1769. external_constructor<value_t::object>::construct(j, obj);
  1770. }
  1771. template<typename BasicJsonType>
  1772. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1773. {
  1774. external_constructor<value_t::object>::construct(j, std::move(obj));
  1775. }
  1776. template <
  1777. typename BasicJsonType, typename T, std::size_t N,
  1778. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t,
  1779. const T(&)[N]>::value,
  1780. int> = 0 >
  1781. void to_json(BasicJsonType& j, const T(&arr)[N])
  1782. {
  1783. external_constructor<value_t::array>::construct(j, arr);
  1784. }
  1785. template<typename BasicJsonType, typename... Args>
  1786. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  1787. {
  1788. j = { p.first, p.second };
  1789. }
  1790. // for https://github.com/nlohmann/json/pull/1134
  1791. template < typename BasicJsonType, typename T,
  1792. enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
  1793. void to_json(BasicJsonType& j, const T& b)
  1794. {
  1795. j = { {b.key(), b.value()} };
  1796. }
  1797. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1798. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/)
  1799. {
  1800. j = { std::get<Idx>(t)... };
  1801. }
  1802. template<typename BasicJsonType, typename... Args>
  1803. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  1804. {
  1805. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1806. }
  1807. struct to_json_fn
  1808. {
  1809. template<typename BasicJsonType, typename T>
  1810. auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1811. -> decltype(to_json(j, std::forward<T>(val)), void())
  1812. {
  1813. return to_json(j, std::forward<T>(val));
  1814. }
  1815. };
  1816. } // namespace detail
  1817. /// namespace to hold default `to_json` function
  1818. namespace
  1819. {
  1820. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1821. } // namespace
  1822. } // namespace nlohmann
  1823. namespace nlohmann
  1824. {
  1825. template<typename, typename>
  1826. struct adl_serializer
  1827. {
  1828. /*!
  1829. @brief convert a JSON value to any value type
  1830. This function is usually called by the `get()` function of the
  1831. @ref basic_json class (either explicit or via conversion operators).
  1832. @param[in] j JSON value to read from
  1833. @param[in,out] val value to write to
  1834. */
  1835. template<typename BasicJsonType, typename ValueType>
  1836. static auto from_json(BasicJsonType&& j, ValueType& val) noexcept(
  1837. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  1838. -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void())
  1839. {
  1840. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  1841. }
  1842. /*!
  1843. @brief convert any value type to a JSON value
  1844. This function is usually called by the constructors of the @ref basic_json
  1845. class.
  1846. @param[in,out] j JSON value to write to
  1847. @param[in] val value to read from
  1848. */
  1849. template <typename BasicJsonType, typename ValueType>
  1850. static auto to_json(BasicJsonType& j, ValueType&& val) noexcept(
  1851. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  1852. -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void())
  1853. {
  1854. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  1855. }
  1856. };
  1857. } // namespace nlohmann
  1858. // #include <nlohmann/detail/conversions/from_json.hpp>
  1859. // #include <nlohmann/detail/conversions/to_json.hpp>
  1860. // #include <nlohmann/detail/exceptions.hpp>
  1861. // #include <nlohmann/detail/input/binary_reader.hpp>
  1862. #include <algorithm> // generate_n
  1863. #include <array> // array
  1864. #include <cassert> // assert
  1865. #include <cmath> // ldexp
  1866. #include <cstddef> // size_t
  1867. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  1868. #include <cstdio> // snprintf
  1869. #include <cstring> // memcpy
  1870. #include <iterator> // back_inserter
  1871. #include <limits> // numeric_limits
  1872. #include <string> // char_traits, string
  1873. #include <utility> // make_pair, move
  1874. // #include <nlohmann/detail/exceptions.hpp>
  1875. // #include <nlohmann/detail/input/input_adapters.hpp>
  1876. #include <array> // array
  1877. #include <cassert> // assert
  1878. #include <cstddef> // size_t
  1879. #include <cstdio> //FILE *
  1880. #include <cstring> // strlen
  1881. #include <istream> // istream
  1882. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  1883. #include <memory> // shared_ptr, make_shared, addressof
  1884. #include <numeric> // accumulate
  1885. #include <string> // string, char_traits
  1886. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  1887. #include <utility> // pair, declval
  1888. // #include <nlohmann/detail/iterators/iterator_traits.hpp>
  1889. // #include <nlohmann/detail/macro_scope.hpp>
  1890. namespace nlohmann
  1891. {
  1892. namespace detail
  1893. {
  1894. /// the supported input formats
  1895. enum class input_format_t { json, cbor, msgpack, ubjson, bson };
  1896. ////////////////////
  1897. // input adapters //
  1898. ////////////////////
  1899. /*!
  1900. @brief abstract input adapter interface
  1901. Produces a stream of std::char_traits<char>::int_type characters from a
  1902. std::istream, a buffer, or some other input type. Accepts the return of
  1903. exactly one non-EOF character for future input. The int_type characters
  1904. returned consist of all valid char values as positive values (typically
  1905. unsigned char), plus an EOF value outside that range, specified by the value
  1906. of the function std::char_traits<char>::eof(). This value is typically -1, but
  1907. could be any arbitrary value which is not a valid char value.
  1908. */
  1909. struct input_adapter_protocol
  1910. {
  1911. /// get a character [0,255] or std::char_traits<char>::eof().
  1912. virtual std::char_traits<char>::int_type get_character() = 0;
  1913. virtual ~input_adapter_protocol() = default;
  1914. };
  1915. /// a type to simplify interfaces
  1916. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1917. /*!
  1918. Input adapter for stdio file access. This adapter read only 1 byte and do not use any
  1919. buffer. This adapter is a very low level adapter.
  1920. */
  1921. class file_input_adapter : public input_adapter_protocol
  1922. {
  1923. public:
  1924. explicit file_input_adapter(std::FILE* f) noexcept
  1925. : m_file(f)
  1926. {}
  1927. // make class move-only
  1928. file_input_adapter(const file_input_adapter&) = delete;
  1929. file_input_adapter(file_input_adapter&&) = default;
  1930. file_input_adapter& operator=(const file_input_adapter&) = delete;
  1931. file_input_adapter& operator=(file_input_adapter&&) = default;
  1932. ~file_input_adapter() override = default;
  1933. std::char_traits<char>::int_type get_character() noexcept override
  1934. {
  1935. return std::fgetc(m_file);
  1936. }
  1937. private:
  1938. /// the file pointer to read from
  1939. std::FILE* m_file;
  1940. };
  1941. /*!
  1942. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1943. beginning of input. Does not support changing the underlying std::streambuf
  1944. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1945. subsequent use of standard std::istream operations to process any input
  1946. characters following those used in parsing the JSON input. Clears the
  1947. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1948. subsequent call for input from the std::istream.
  1949. */
  1950. class input_stream_adapter : public input_adapter_protocol
  1951. {
  1952. public:
  1953. ~input_stream_adapter() override
  1954. {
  1955. // clear stream flags; we use underlying streambuf I/O, do not
  1956. // maintain ifstream flags, except eof
  1957. is.clear(is.rdstate() & std::ios::eofbit);
  1958. }
  1959. explicit input_stream_adapter(std::istream& i)
  1960. : is(i), sb(*i.rdbuf())
  1961. {}
  1962. // delete because of pointer members
  1963. input_stream_adapter(const input_stream_adapter&) = delete;
  1964. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  1965. input_stream_adapter(input_stream_adapter&&) = delete;
  1966. input_stream_adapter& operator=(input_stream_adapter&&) = delete;
  1967. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  1968. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  1969. // end up as the same value, eg. 0xFFFFFFFF.
  1970. std::char_traits<char>::int_type get_character() override
  1971. {
  1972. auto res = sb.sbumpc();
  1973. // set eof manually, as we don't use the istream interface.
  1974. if (res == EOF)
  1975. {
  1976. is.clear(is.rdstate() | std::ios::eofbit);
  1977. }
  1978. return res;
  1979. }
  1980. private:
  1981. /// the associated input stream
  1982. std::istream& is;
  1983. std::streambuf& sb;
  1984. };
  1985. /// input adapter for buffer input
  1986. class input_buffer_adapter : public input_adapter_protocol
  1987. {
  1988. public:
  1989. input_buffer_adapter(const char* b, const std::size_t l) noexcept
  1990. : cursor(b), limit(b + l)
  1991. {}
  1992. // delete because of pointer members
  1993. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1994. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1995. input_buffer_adapter(input_buffer_adapter&&) = delete;
  1996. input_buffer_adapter& operator=(input_buffer_adapter&&) = delete;
  1997. ~input_buffer_adapter() override = default;
  1998. std::char_traits<char>::int_type get_character() noexcept override
  1999. {
  2000. if (JSON_LIKELY(cursor < limit))
  2001. {
  2002. return std::char_traits<char>::to_int_type(*(cursor++));
  2003. }
  2004. return std::char_traits<char>::eof();
  2005. }
  2006. private:
  2007. /// pointer to the current character
  2008. const char* cursor;
  2009. /// pointer past the last character
  2010. const char* const limit;
  2011. };
  2012. template<typename WideStringType, size_t T>
  2013. struct wide_string_input_helper
  2014. {
  2015. // UTF-32
  2016. static void fill_buffer(const WideStringType& str,
  2017. size_t& current_wchar,
  2018. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  2019. size_t& utf8_bytes_index,
  2020. size_t& utf8_bytes_filled)
  2021. {
  2022. utf8_bytes_index = 0;
  2023. if (current_wchar == str.size())
  2024. {
  2025. utf8_bytes[0] = std::char_traits<char>::eof();
  2026. utf8_bytes_filled = 1;
  2027. }
  2028. else
  2029. {
  2030. // get the current character
  2031. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  2032. // UTF-32 to UTF-8 encoding
  2033. if (wc < 0x80)
  2034. {
  2035. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2036. utf8_bytes_filled = 1;
  2037. }
  2038. else if (wc <= 0x7FF)
  2039. {
  2040. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u) & 0x1Fu));
  2041. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2042. utf8_bytes_filled = 2;
  2043. }
  2044. else if (wc <= 0xFFFF)
  2045. {
  2046. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u) & 0x0Fu));
  2047. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2048. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2049. utf8_bytes_filled = 3;
  2050. }
  2051. else if (wc <= 0x10FFFF)
  2052. {
  2053. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | ((wc >> 18u) & 0x07u));
  2054. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 12u) & 0x3Fu));
  2055. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2056. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2057. utf8_bytes_filled = 4;
  2058. }
  2059. else
  2060. {
  2061. // unknown character
  2062. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2063. utf8_bytes_filled = 1;
  2064. }
  2065. }
  2066. }
  2067. };
  2068. template<typename WideStringType>
  2069. struct wide_string_input_helper<WideStringType, 2>
  2070. {
  2071. // UTF-16
  2072. static void fill_buffer(const WideStringType& str,
  2073. size_t& current_wchar,
  2074. std::array<std::char_traits<char>::int_type, 4>& utf8_bytes,
  2075. size_t& utf8_bytes_index,
  2076. size_t& utf8_bytes_filled)
  2077. {
  2078. utf8_bytes_index = 0;
  2079. if (current_wchar == str.size())
  2080. {
  2081. utf8_bytes[0] = std::char_traits<char>::eof();
  2082. utf8_bytes_filled = 1;
  2083. }
  2084. else
  2085. {
  2086. // get the current character
  2087. const auto wc = static_cast<unsigned int>(str[current_wchar++]);
  2088. // UTF-16 to UTF-8 encoding
  2089. if (wc < 0x80)
  2090. {
  2091. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2092. utf8_bytes_filled = 1;
  2093. }
  2094. else if (wc <= 0x7FF)
  2095. {
  2096. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xC0u | ((wc >> 6u)));
  2097. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2098. utf8_bytes_filled = 2;
  2099. }
  2100. else if (0xD800 > wc or wc >= 0xE000)
  2101. {
  2102. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xE0u | ((wc >> 12u)));
  2103. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((wc >> 6u) & 0x3Fu));
  2104. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | (wc & 0x3Fu));
  2105. utf8_bytes_filled = 3;
  2106. }
  2107. else
  2108. {
  2109. if (current_wchar < str.size())
  2110. {
  2111. const auto wc2 = static_cast<unsigned int>(str[current_wchar++]);
  2112. const auto charcode = 0x10000u + (((wc & 0x3FFu) << 10u) | (wc2 & 0x3FFu));
  2113. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(0xF0u | (charcode >> 18u));
  2114. utf8_bytes[1] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu));
  2115. utf8_bytes[2] = static_cast<std::char_traits<char>::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu));
  2116. utf8_bytes[3] = static_cast<std::char_traits<char>::int_type>(0x80u | (charcode & 0x3Fu));
  2117. utf8_bytes_filled = 4;
  2118. }
  2119. else
  2120. {
  2121. // unknown character
  2122. ++current_wchar;
  2123. utf8_bytes[0] = static_cast<std::char_traits<char>::int_type>(wc);
  2124. utf8_bytes_filled = 1;
  2125. }
  2126. }
  2127. }
  2128. }
  2129. };
  2130. template<typename WideStringType>
  2131. class wide_string_input_adapter : public input_adapter_protocol
  2132. {
  2133. public:
  2134. explicit wide_string_input_adapter(const WideStringType& w) noexcept
  2135. : str(w)
  2136. {}
  2137. std::char_traits<char>::int_type get_character() noexcept override
  2138. {
  2139. // check if buffer needs to be filled
  2140. if (utf8_bytes_index == utf8_bytes_filled)
  2141. {
  2142. fill_buffer<sizeof(typename WideStringType::value_type)>();
  2143. assert(utf8_bytes_filled > 0);
  2144. assert(utf8_bytes_index == 0);
  2145. }
  2146. // use buffer
  2147. assert(utf8_bytes_filled > 0);
  2148. assert(utf8_bytes_index < utf8_bytes_filled);
  2149. return utf8_bytes[utf8_bytes_index++];
  2150. }
  2151. private:
  2152. template<size_t T>
  2153. void fill_buffer()
  2154. {
  2155. wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled);
  2156. }
  2157. /// the wstring to process
  2158. const WideStringType& str;
  2159. /// index of the current wchar in str
  2160. std::size_t current_wchar = 0;
  2161. /// a buffer for UTF-8 bytes
  2162. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  2163. /// index to the utf8_codes array for the next valid byte
  2164. std::size_t utf8_bytes_index = 0;
  2165. /// number of valid bytes in the utf8_codes array
  2166. std::size_t utf8_bytes_filled = 0;
  2167. };
  2168. class input_adapter
  2169. {
  2170. public:
  2171. // native support
  2172. input_adapter(std::FILE* file)
  2173. : ia(std::make_shared<file_input_adapter>(file)) {}
  2174. /// input adapter for input stream
  2175. input_adapter(std::istream& i)
  2176. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2177. /// input adapter for input stream
  2178. input_adapter(std::istream&& i)
  2179. : ia(std::make_shared<input_stream_adapter>(i)) {}
  2180. input_adapter(const std::wstring& ws)
  2181. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  2182. input_adapter(const std::u16string& ws)
  2183. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  2184. input_adapter(const std::u32string& ws)
  2185. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  2186. /// input adapter for buffer
  2187. template<typename CharT,
  2188. typename std::enable_if<
  2189. std::is_pointer<CharT>::value and
  2190. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2191. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2192. int>::type = 0>
  2193. input_adapter(CharT b, std::size_t l)
  2194. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  2195. // derived support
  2196. /// input adapter for string literal
  2197. template<typename CharT,
  2198. typename std::enable_if<
  2199. std::is_pointer<CharT>::value and
  2200. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  2201. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  2202. int>::type = 0>
  2203. input_adapter(CharT b)
  2204. : input_adapter(reinterpret_cast<const char*>(b),
  2205. std::strlen(reinterpret_cast<const char*>(b))) {}
  2206. /// input adapter for iterator range with contiguous storage
  2207. template<class IteratorType,
  2208. typename std::enable_if<
  2209. std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  2210. int>::type = 0>
  2211. input_adapter(IteratorType first, IteratorType last)
  2212. {
  2213. #ifndef NDEBUG
  2214. // assertion to check that the iterator range is indeed contiguous,
  2215. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  2216. const auto is_contiguous = std::accumulate(
  2217. first, last, std::pair<bool, int>(true, 0),
  2218. [&first](std::pair<bool, int> res, decltype(*first) val)
  2219. {
  2220. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  2221. return res;
  2222. }).first;
  2223. assert(is_contiguous);
  2224. #endif
  2225. // assertion to check that each element is 1 byte long
  2226. static_assert(
  2227. sizeof(typename iterator_traits<IteratorType>::value_type) == 1,
  2228. "each element in the iterator range must have the size of 1 byte");
  2229. const auto len = static_cast<size_t>(std::distance(first, last));
  2230. if (JSON_LIKELY(len > 0))
  2231. {
  2232. // there is at least one element: use the address of first
  2233. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  2234. }
  2235. else
  2236. {
  2237. // the address of first cannot be used: use nullptr
  2238. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  2239. }
  2240. }
  2241. /// input adapter for array
  2242. template<class T, std::size_t N>
  2243. input_adapter(T (&array)[N])
  2244. : input_adapter(std::begin(array), std::end(array)) {}
  2245. /// input adapter for contiguous container
  2246. template<class ContiguousContainer, typename
  2247. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  2248. std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  2249. int>::type = 0>
  2250. input_adapter(const ContiguousContainer& c)
  2251. : input_adapter(std::begin(c), std::end(c)) {}
  2252. operator input_adapter_t()
  2253. {
  2254. return ia;
  2255. }
  2256. private:
  2257. /// the actual adapter
  2258. input_adapter_t ia = nullptr;
  2259. };
  2260. } // namespace detail
  2261. } // namespace nlohmann
  2262. // #include <nlohmann/detail/input/json_sax.hpp>
  2263. #include <cassert> // assert
  2264. #include <cstddef>
  2265. #include <string> // string
  2266. #include <utility> // move
  2267. #include <vector> // vector
  2268. // #include <nlohmann/detail/exceptions.hpp>
  2269. // #include <nlohmann/detail/macro_scope.hpp>
  2270. namespace nlohmann
  2271. {
  2272. /*!
  2273. @brief SAX interface
  2274. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  2275. Each function is called in different situations while the input is parsed. The
  2276. boolean return value informs the parser whether to continue processing the
  2277. input.
  2278. */
  2279. template<typename BasicJsonType>
  2280. struct json_sax
  2281. {
  2282. /// type for (signed) integers
  2283. using number_integer_t = typename BasicJsonType::number_integer_t;
  2284. /// type for unsigned integers
  2285. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2286. /// type for floating-point numbers
  2287. using number_float_t = typename BasicJsonType::number_float_t;
  2288. /// type for strings
  2289. using string_t = typename BasicJsonType::string_t;
  2290. /*!
  2291. @brief a null value was read
  2292. @return whether parsing should proceed
  2293. */
  2294. virtual bool null() = 0;
  2295. /*!
  2296. @brief a boolean value was read
  2297. @param[in] val boolean value
  2298. @return whether parsing should proceed
  2299. */
  2300. virtual bool boolean(bool val) = 0;
  2301. /*!
  2302. @brief an integer number was read
  2303. @param[in] val integer value
  2304. @return whether parsing should proceed
  2305. */
  2306. virtual bool number_integer(number_integer_t val) = 0;
  2307. /*!
  2308. @brief an unsigned integer number was read
  2309. @param[in] val unsigned integer value
  2310. @return whether parsing should proceed
  2311. */
  2312. virtual bool number_unsigned(number_unsigned_t val) = 0;
  2313. /*!
  2314. @brief an floating-point number was read
  2315. @param[in] val floating-point value
  2316. @param[in] s raw token value
  2317. @return whether parsing should proceed
  2318. */
  2319. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  2320. /*!
  2321. @brief a string was read
  2322. @param[in] val string value
  2323. @return whether parsing should proceed
  2324. @note It is safe to move the passed string.
  2325. */
  2326. virtual bool string(string_t& val) = 0;
  2327. /*!
  2328. @brief the beginning of an object was read
  2329. @param[in] elements number of object elements or -1 if unknown
  2330. @return whether parsing should proceed
  2331. @note binary formats may report the number of elements
  2332. */
  2333. virtual bool start_object(std::size_t elements) = 0;
  2334. /*!
  2335. @brief an object key was read
  2336. @param[in] val object key
  2337. @return whether parsing should proceed
  2338. @note It is safe to move the passed string.
  2339. */
  2340. virtual bool key(string_t& val) = 0;
  2341. /*!
  2342. @brief the end of an object was read
  2343. @return whether parsing should proceed
  2344. */
  2345. virtual bool end_object() = 0;
  2346. /*!
  2347. @brief the beginning of an array was read
  2348. @param[in] elements number of array elements or -1 if unknown
  2349. @return whether parsing should proceed
  2350. @note binary formats may report the number of elements
  2351. */
  2352. virtual bool start_array(std::size_t elements) = 0;
  2353. /*!
  2354. @brief the end of an array was read
  2355. @return whether parsing should proceed
  2356. */
  2357. virtual bool end_array() = 0;
  2358. /*!
  2359. @brief a parse error occurred
  2360. @param[in] position the position in the input where the error occurs
  2361. @param[in] last_token the last read token
  2362. @param[in] ex an exception object describing the error
  2363. @return whether parsing should proceed (must return false)
  2364. */
  2365. virtual bool parse_error(std::size_t position,
  2366. const std::string& last_token,
  2367. const detail::exception& ex) = 0;
  2368. virtual ~json_sax() = default;
  2369. };
  2370. namespace detail
  2371. {
  2372. /*!
  2373. @brief SAX implementation to create a JSON value from SAX events
  2374. This class implements the @ref json_sax interface and processes the SAX events
  2375. to create a JSON value which makes it basically a DOM parser. The structure or
  2376. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  2377. a pointer to the respective array or object for each recursion depth.
  2378. After successful parsing, the value that is passed by reference to the
  2379. constructor contains the parsed value.
  2380. @tparam BasicJsonType the JSON type
  2381. */
  2382. template<typename BasicJsonType>
  2383. class json_sax_dom_parser
  2384. {
  2385. public:
  2386. using number_integer_t = typename BasicJsonType::number_integer_t;
  2387. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2388. using number_float_t = typename BasicJsonType::number_float_t;
  2389. using string_t = typename BasicJsonType::string_t;
  2390. /*!
  2391. @param[in, out] r reference to a JSON value that is manipulated while
  2392. parsing
  2393. @param[in] allow_exceptions_ whether parse errors yield exceptions
  2394. */
  2395. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  2396. : root(r), allow_exceptions(allow_exceptions_)
  2397. {}
  2398. // make class move-only
  2399. json_sax_dom_parser(const json_sax_dom_parser&) = delete;
  2400. json_sax_dom_parser(json_sax_dom_parser&&) = default;
  2401. json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete;
  2402. json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default;
  2403. ~json_sax_dom_parser() = default;
  2404. bool null()
  2405. {
  2406. handle_value(nullptr);
  2407. return true;
  2408. }
  2409. bool boolean(bool val)
  2410. {
  2411. handle_value(val);
  2412. return true;
  2413. }
  2414. bool number_integer(number_integer_t val)
  2415. {
  2416. handle_value(val);
  2417. return true;
  2418. }
  2419. bool number_unsigned(number_unsigned_t val)
  2420. {
  2421. handle_value(val);
  2422. return true;
  2423. }
  2424. bool number_float(number_float_t val, const string_t& /*unused*/)
  2425. {
  2426. handle_value(val);
  2427. return true;
  2428. }
  2429. bool string(string_t& val)
  2430. {
  2431. handle_value(val);
  2432. return true;
  2433. }
  2434. bool start_object(std::size_t len)
  2435. {
  2436. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  2437. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2438. {
  2439. JSON_THROW(out_of_range::create(408,
  2440. "excessive object size: " + std::to_string(len)));
  2441. }
  2442. return true;
  2443. }
  2444. bool key(string_t& val)
  2445. {
  2446. // add null at given key and store the reference for later
  2447. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  2448. return true;
  2449. }
  2450. bool end_object()
  2451. {
  2452. ref_stack.pop_back();
  2453. return true;
  2454. }
  2455. bool start_array(std::size_t len)
  2456. {
  2457. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  2458. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2459. {
  2460. JSON_THROW(out_of_range::create(408,
  2461. "excessive array size: " + std::to_string(len)));
  2462. }
  2463. return true;
  2464. }
  2465. bool end_array()
  2466. {
  2467. ref_stack.pop_back();
  2468. return true;
  2469. }
  2470. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  2471. const detail::exception& ex)
  2472. {
  2473. errored = true;
  2474. if (allow_exceptions)
  2475. {
  2476. // determine the proper exception type from the id
  2477. switch ((ex.id / 100) % 100)
  2478. {
  2479. case 1:
  2480. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  2481. case 4:
  2482. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  2483. // LCOV_EXCL_START
  2484. case 2:
  2485. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  2486. case 3:
  2487. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  2488. case 5:
  2489. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  2490. default:
  2491. assert(false);
  2492. // LCOV_EXCL_STOP
  2493. }
  2494. }
  2495. return false;
  2496. }
  2497. constexpr bool is_errored() const
  2498. {
  2499. return errored;
  2500. }
  2501. private:
  2502. /*!
  2503. @invariant If the ref stack is empty, then the passed value will be the new
  2504. root.
  2505. @invariant If the ref stack contains a value, then it is an array or an
  2506. object to which we can add elements
  2507. */
  2508. template<typename Value>
  2509. BasicJsonType* handle_value(Value&& v)
  2510. {
  2511. if (ref_stack.empty())
  2512. {
  2513. root = BasicJsonType(std::forward<Value>(v));
  2514. return &root;
  2515. }
  2516. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  2517. if (ref_stack.back()->is_array())
  2518. {
  2519. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  2520. return &(ref_stack.back()->m_value.array->back());
  2521. }
  2522. assert(ref_stack.back()->is_object());
  2523. assert(object_element);
  2524. *object_element = BasicJsonType(std::forward<Value>(v));
  2525. return object_element;
  2526. }
  2527. /// the parsed JSON value
  2528. BasicJsonType& root;
  2529. /// stack to model hierarchy of values
  2530. std::vector<BasicJsonType*> ref_stack {};
  2531. /// helper to hold the reference for the next object element
  2532. BasicJsonType* object_element = nullptr;
  2533. /// whether a syntax error occurred
  2534. bool errored = false;
  2535. /// whether to throw exceptions in case of errors
  2536. const bool allow_exceptions = true;
  2537. };
  2538. template<typename BasicJsonType>
  2539. class json_sax_dom_callback_parser
  2540. {
  2541. public:
  2542. using number_integer_t = typename BasicJsonType::number_integer_t;
  2543. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2544. using number_float_t = typename BasicJsonType::number_float_t;
  2545. using string_t = typename BasicJsonType::string_t;
  2546. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  2547. using parse_event_t = typename BasicJsonType::parse_event_t;
  2548. json_sax_dom_callback_parser(BasicJsonType& r,
  2549. const parser_callback_t cb,
  2550. const bool allow_exceptions_ = true)
  2551. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  2552. {
  2553. keep_stack.push_back(true);
  2554. }
  2555. // make class move-only
  2556. json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete;
  2557. json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default;
  2558. json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete;
  2559. json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default;
  2560. ~json_sax_dom_callback_parser() = default;
  2561. bool null()
  2562. {
  2563. handle_value(nullptr);
  2564. return true;
  2565. }
  2566. bool boolean(bool val)
  2567. {
  2568. handle_value(val);
  2569. return true;
  2570. }
  2571. bool number_integer(number_integer_t val)
  2572. {
  2573. handle_value(val);
  2574. return true;
  2575. }
  2576. bool number_unsigned(number_unsigned_t val)
  2577. {
  2578. handle_value(val);
  2579. return true;
  2580. }
  2581. bool number_float(number_float_t val, const string_t& /*unused*/)
  2582. {
  2583. handle_value(val);
  2584. return true;
  2585. }
  2586. bool string(string_t& val)
  2587. {
  2588. handle_value(val);
  2589. return true;
  2590. }
  2591. bool start_object(std::size_t len)
  2592. {
  2593. // check callback for object start
  2594. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  2595. keep_stack.push_back(keep);
  2596. auto val = handle_value(BasicJsonType::value_t::object, true);
  2597. ref_stack.push_back(val.second);
  2598. // check object limit
  2599. if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2600. {
  2601. JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len)));
  2602. }
  2603. return true;
  2604. }
  2605. bool key(string_t& val)
  2606. {
  2607. BasicJsonType k = BasicJsonType(val);
  2608. // check callback for key
  2609. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  2610. key_keep_stack.push_back(keep);
  2611. // add discarded value at given key and store the reference for later
  2612. if (keep and ref_stack.back())
  2613. {
  2614. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  2615. }
  2616. return true;
  2617. }
  2618. bool end_object()
  2619. {
  2620. if (ref_stack.back() and not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  2621. {
  2622. // discard object
  2623. *ref_stack.back() = discarded;
  2624. }
  2625. assert(not ref_stack.empty());
  2626. assert(not keep_stack.empty());
  2627. ref_stack.pop_back();
  2628. keep_stack.pop_back();
  2629. if (not ref_stack.empty() and ref_stack.back() and ref_stack.back()->is_object())
  2630. {
  2631. // remove discarded value
  2632. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  2633. {
  2634. if (it->is_discarded())
  2635. {
  2636. ref_stack.back()->erase(it);
  2637. break;
  2638. }
  2639. }
  2640. }
  2641. return true;
  2642. }
  2643. bool start_array(std::size_t len)
  2644. {
  2645. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  2646. keep_stack.push_back(keep);
  2647. auto val = handle_value(BasicJsonType::value_t::array, true);
  2648. ref_stack.push_back(val.second);
  2649. // check array limit
  2650. if (ref_stack.back() and JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  2651. {
  2652. JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len)));
  2653. }
  2654. return true;
  2655. }
  2656. bool end_array()
  2657. {
  2658. bool keep = true;
  2659. if (ref_stack.back())
  2660. {
  2661. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  2662. if (not keep)
  2663. {
  2664. // discard array
  2665. *ref_stack.back() = discarded;
  2666. }
  2667. }
  2668. assert(not ref_stack.empty());
  2669. assert(not keep_stack.empty());
  2670. ref_stack.pop_back();
  2671. keep_stack.pop_back();
  2672. // remove discarded value
  2673. if (not keep and not ref_stack.empty() and ref_stack.back()->is_array())
  2674. {
  2675. ref_stack.back()->m_value.array->pop_back();
  2676. }
  2677. return true;
  2678. }
  2679. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/,
  2680. const detail::exception& ex)
  2681. {
  2682. errored = true;
  2683. if (allow_exceptions)
  2684. {
  2685. // determine the proper exception type from the id
  2686. switch ((ex.id / 100) % 100)
  2687. {
  2688. case 1:
  2689. JSON_THROW(*static_cast<const detail::parse_error*>(&ex));
  2690. case 4:
  2691. JSON_THROW(*static_cast<const detail::out_of_range*>(&ex));
  2692. // LCOV_EXCL_START
  2693. case 2:
  2694. JSON_THROW(*static_cast<const detail::invalid_iterator*>(&ex));
  2695. case 3:
  2696. JSON_THROW(*static_cast<const detail::type_error*>(&ex));
  2697. case 5:
  2698. JSON_THROW(*static_cast<const detail::other_error*>(&ex));
  2699. default:
  2700. assert(false);
  2701. // LCOV_EXCL_STOP
  2702. }
  2703. }
  2704. return false;
  2705. }
  2706. constexpr bool is_errored() const
  2707. {
  2708. return errored;
  2709. }
  2710. private:
  2711. /*!
  2712. @param[in] v value to add to the JSON value we build during parsing
  2713. @param[in] skip_callback whether we should skip calling the callback
  2714. function; this is required after start_array() and
  2715. start_object() SAX events, because otherwise we would call the
  2716. callback function with an empty array or object, respectively.
  2717. @invariant If the ref stack is empty, then the passed value will be the new
  2718. root.
  2719. @invariant If the ref stack contains a value, then it is an array or an
  2720. object to which we can add elements
  2721. @return pair of boolean (whether value should be kept) and pointer (to the
  2722. passed value in the ref_stack hierarchy; nullptr if not kept)
  2723. */
  2724. template<typename Value>
  2725. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  2726. {
  2727. assert(not keep_stack.empty());
  2728. // do not handle this value if we know it would be added to a discarded
  2729. // container
  2730. if (not keep_stack.back())
  2731. {
  2732. return {false, nullptr};
  2733. }
  2734. // create value
  2735. auto value = BasicJsonType(std::forward<Value>(v));
  2736. // check callback
  2737. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  2738. // do not handle this value if we just learnt it shall be discarded
  2739. if (not keep)
  2740. {
  2741. return {false, nullptr};
  2742. }
  2743. if (ref_stack.empty())
  2744. {
  2745. root = std::move(value);
  2746. return {true, &root};
  2747. }
  2748. // skip this value if we already decided to skip the parent
  2749. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  2750. if (not ref_stack.back())
  2751. {
  2752. return {false, nullptr};
  2753. }
  2754. // we now only expect arrays and objects
  2755. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  2756. // array
  2757. if (ref_stack.back()->is_array())
  2758. {
  2759. ref_stack.back()->m_value.array->push_back(std::move(value));
  2760. return {true, &(ref_stack.back()->m_value.array->back())};
  2761. }
  2762. // object
  2763. assert(ref_stack.back()->is_object());
  2764. // check if we should store an element for the current key
  2765. assert(not key_keep_stack.empty());
  2766. const bool store_element = key_keep_stack.back();
  2767. key_keep_stack.pop_back();
  2768. if (not store_element)
  2769. {
  2770. return {false, nullptr};
  2771. }
  2772. assert(object_element);
  2773. *object_element = std::move(value);
  2774. return {true, object_element};
  2775. }
  2776. /// the parsed JSON value
  2777. BasicJsonType& root;
  2778. /// stack to model hierarchy of values
  2779. std::vector<BasicJsonType*> ref_stack {};
  2780. /// stack to manage which values to keep
  2781. std::vector<bool> keep_stack {};
  2782. /// stack to manage which object keys to keep
  2783. std::vector<bool> key_keep_stack {};
  2784. /// helper to hold the reference for the next object element
  2785. BasicJsonType* object_element = nullptr;
  2786. /// whether a syntax error occurred
  2787. bool errored = false;
  2788. /// callback function
  2789. const parser_callback_t callback = nullptr;
  2790. /// whether to throw exceptions in case of errors
  2791. const bool allow_exceptions = true;
  2792. /// a discarded value for the callback
  2793. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  2794. };
  2795. template<typename BasicJsonType>
  2796. class json_sax_acceptor
  2797. {
  2798. public:
  2799. using number_integer_t = typename BasicJsonType::number_integer_t;
  2800. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2801. using number_float_t = typename BasicJsonType::number_float_t;
  2802. using string_t = typename BasicJsonType::string_t;
  2803. bool null()
  2804. {
  2805. return true;
  2806. }
  2807. bool boolean(bool /*unused*/)
  2808. {
  2809. return true;
  2810. }
  2811. bool number_integer(number_integer_t /*unused*/)
  2812. {
  2813. return true;
  2814. }
  2815. bool number_unsigned(number_unsigned_t /*unused*/)
  2816. {
  2817. return true;
  2818. }
  2819. bool number_float(number_float_t /*unused*/, const string_t& /*unused*/)
  2820. {
  2821. return true;
  2822. }
  2823. bool string(string_t& /*unused*/)
  2824. {
  2825. return true;
  2826. }
  2827. bool start_object(std::size_t /*unused*/ = std::size_t(-1))
  2828. {
  2829. return true;
  2830. }
  2831. bool key(string_t& /*unused*/)
  2832. {
  2833. return true;
  2834. }
  2835. bool end_object()
  2836. {
  2837. return true;
  2838. }
  2839. bool start_array(std::size_t /*unused*/ = std::size_t(-1))
  2840. {
  2841. return true;
  2842. }
  2843. bool end_array()
  2844. {
  2845. return true;
  2846. }
  2847. bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/)
  2848. {
  2849. return false;
  2850. }
  2851. };
  2852. } // namespace detail
  2853. } // namespace nlohmann
  2854. // #include <nlohmann/detail/macro_scope.hpp>
  2855. // #include <nlohmann/detail/meta/is_sax.hpp>
  2856. #include <cstdint> // size_t
  2857. #include <utility> // declval
  2858. #include <string> // string
  2859. // #include <nlohmann/detail/meta/detected.hpp>
  2860. // #include <nlohmann/detail/meta/type_traits.hpp>
  2861. namespace nlohmann
  2862. {
  2863. namespace detail
  2864. {
  2865. template <typename T>
  2866. using null_function_t = decltype(std::declval<T&>().null());
  2867. template <typename T>
  2868. using boolean_function_t =
  2869. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  2870. template <typename T, typename Integer>
  2871. using number_integer_function_t =
  2872. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  2873. template <typename T, typename Unsigned>
  2874. using number_unsigned_function_t =
  2875. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  2876. template <typename T, typename Float, typename String>
  2877. using number_float_function_t = decltype(std::declval<T&>().number_float(
  2878. std::declval<Float>(), std::declval<const String&>()));
  2879. template <typename T, typename String>
  2880. using string_function_t =
  2881. decltype(std::declval<T&>().string(std::declval<String&>()));
  2882. template <typename T>
  2883. using start_object_function_t =
  2884. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  2885. template <typename T, typename String>
  2886. using key_function_t =
  2887. decltype(std::declval<T&>().key(std::declval<String&>()));
  2888. template <typename T>
  2889. using end_object_function_t = decltype(std::declval<T&>().end_object());
  2890. template <typename T>
  2891. using start_array_function_t =
  2892. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  2893. template <typename T>
  2894. using end_array_function_t = decltype(std::declval<T&>().end_array());
  2895. template <typename T, typename Exception>
  2896. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  2897. std::declval<std::size_t>(), std::declval<const std::string&>(),
  2898. std::declval<const Exception&>()));
  2899. template <typename SAX, typename BasicJsonType>
  2900. struct is_sax
  2901. {
  2902. private:
  2903. static_assert(is_basic_json<BasicJsonType>::value,
  2904. "BasicJsonType must be of type basic_json<...>");
  2905. using number_integer_t = typename BasicJsonType::number_integer_t;
  2906. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2907. using number_float_t = typename BasicJsonType::number_float_t;
  2908. using string_t = typename BasicJsonType::string_t;
  2909. using exception_t = typename BasicJsonType::exception;
  2910. public:
  2911. static constexpr bool value =
  2912. is_detected_exact<bool, null_function_t, SAX>::value &&
  2913. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  2914. is_detected_exact<bool, number_integer_function_t, SAX,
  2915. number_integer_t>::value &&
  2916. is_detected_exact<bool, number_unsigned_function_t, SAX,
  2917. number_unsigned_t>::value &&
  2918. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  2919. string_t>::value &&
  2920. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  2921. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  2922. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  2923. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  2924. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  2925. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  2926. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  2927. };
  2928. template <typename SAX, typename BasicJsonType>
  2929. struct is_sax_static_asserts
  2930. {
  2931. private:
  2932. static_assert(is_basic_json<BasicJsonType>::value,
  2933. "BasicJsonType must be of type basic_json<...>");
  2934. using number_integer_t = typename BasicJsonType::number_integer_t;
  2935. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2936. using number_float_t = typename BasicJsonType::number_float_t;
  2937. using string_t = typename BasicJsonType::string_t;
  2938. using exception_t = typename BasicJsonType::exception;
  2939. public:
  2940. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  2941. "Missing/invalid function: bool null()");
  2942. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  2943. "Missing/invalid function: bool boolean(bool)");
  2944. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  2945. "Missing/invalid function: bool boolean(bool)");
  2946. static_assert(
  2947. is_detected_exact<bool, number_integer_function_t, SAX,
  2948. number_integer_t>::value,
  2949. "Missing/invalid function: bool number_integer(number_integer_t)");
  2950. static_assert(
  2951. is_detected_exact<bool, number_unsigned_function_t, SAX,
  2952. number_unsigned_t>::value,
  2953. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  2954. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  2955. number_float_t, string_t>::value,
  2956. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  2957. static_assert(
  2958. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  2959. "Missing/invalid function: bool string(string_t&)");
  2960. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  2961. "Missing/invalid function: bool start_object(std::size_t)");
  2962. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  2963. "Missing/invalid function: bool key(string_t&)");
  2964. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  2965. "Missing/invalid function: bool end_object()");
  2966. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  2967. "Missing/invalid function: bool start_array(std::size_t)");
  2968. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  2969. "Missing/invalid function: bool end_array()");
  2970. static_assert(
  2971. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  2972. "Missing/invalid function: bool parse_error(std::size_t, const "
  2973. "std::string&, const exception&)");
  2974. };
  2975. } // namespace detail
  2976. } // namespace nlohmann
  2977. // #include <nlohmann/detail/value_t.hpp>
  2978. namespace nlohmann
  2979. {
  2980. namespace detail
  2981. {
  2982. ///////////////////
  2983. // binary reader //
  2984. ///////////////////
  2985. /*!
  2986. @brief deserialization of CBOR, MessagePack, and UBJSON values
  2987. */
  2988. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  2989. class binary_reader
  2990. {
  2991. using number_integer_t = typename BasicJsonType::number_integer_t;
  2992. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2993. using number_float_t = typename BasicJsonType::number_float_t;
  2994. using string_t = typename BasicJsonType::string_t;
  2995. using json_sax_t = SAX;
  2996. public:
  2997. /*!
  2998. @brief create a binary reader
  2999. @param[in] adapter input adapter to read from
  3000. */
  3001. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  3002. {
  3003. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  3004. assert(ia);
  3005. }
  3006. // make class move-only
  3007. binary_reader(const binary_reader&) = delete;
  3008. binary_reader(binary_reader&&) = default;
  3009. binary_reader& operator=(const binary_reader&) = delete;
  3010. binary_reader& operator=(binary_reader&&) = default;
  3011. ~binary_reader() = default;
  3012. /*!
  3013. @param[in] format the binary format to parse
  3014. @param[in] sax_ a SAX event processor
  3015. @param[in] strict whether to expect the input to be consumed completed
  3016. @return
  3017. */
  3018. bool sax_parse(const input_format_t format,
  3019. json_sax_t* sax_,
  3020. const bool strict = true)
  3021. {
  3022. sax = sax_;
  3023. bool result = false;
  3024. switch (format)
  3025. {
  3026. case input_format_t::bson:
  3027. result = parse_bson_internal();
  3028. break;
  3029. case input_format_t::cbor:
  3030. result = parse_cbor_internal();
  3031. break;
  3032. case input_format_t::msgpack:
  3033. result = parse_msgpack_internal();
  3034. break;
  3035. case input_format_t::ubjson:
  3036. result = parse_ubjson_internal();
  3037. break;
  3038. default: // LCOV_EXCL_LINE
  3039. assert(false); // LCOV_EXCL_LINE
  3040. }
  3041. // strict mode: next byte must be EOF
  3042. if (result and strict)
  3043. {
  3044. if (format == input_format_t::ubjson)
  3045. {
  3046. get_ignore_noop();
  3047. }
  3048. else
  3049. {
  3050. get();
  3051. }
  3052. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  3053. {
  3054. return sax->parse_error(chars_read, get_token_string(),
  3055. parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value")));
  3056. }
  3057. }
  3058. return result;
  3059. }
  3060. /*!
  3061. @brief determine system byte order
  3062. @return true if and only if system's byte order is little endian
  3063. @note from http://stackoverflow.com/a/1001328/266378
  3064. */
  3065. static constexpr bool little_endianess(int num = 1) noexcept
  3066. {
  3067. return *reinterpret_cast<char*>(&num) == 1;
  3068. }
  3069. private:
  3070. //////////
  3071. // BSON //
  3072. //////////
  3073. /*!
  3074. @brief Reads in a BSON-object and passes it to the SAX-parser.
  3075. @return whether a valid BSON-value was passed to the SAX parser
  3076. */
  3077. bool parse_bson_internal()
  3078. {
  3079. std::int32_t document_size;
  3080. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  3081. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  3082. {
  3083. return false;
  3084. }
  3085. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/false)))
  3086. {
  3087. return false;
  3088. }
  3089. return sax->end_object();
  3090. }
  3091. /*!
  3092. @brief Parses a C-style string from the BSON input.
  3093. @param[in, out] result A reference to the string variable where the read
  3094. string is to be stored.
  3095. @return `true` if the \x00-byte indicating the end of the string was
  3096. encountered before the EOF; false` indicates an unexpected EOF.
  3097. */
  3098. bool get_bson_cstr(string_t& result)
  3099. {
  3100. auto out = std::back_inserter(result);
  3101. while (true)
  3102. {
  3103. get();
  3104. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring")))
  3105. {
  3106. return false;
  3107. }
  3108. if (current == 0x00)
  3109. {
  3110. return true;
  3111. }
  3112. *out++ = static_cast<char>(current);
  3113. }
  3114. return true;
  3115. }
  3116. /*!
  3117. @brief Parses a zero-terminated string of length @a len from the BSON
  3118. input.
  3119. @param[in] len The length (including the zero-byte at the end) of the
  3120. string to be read.
  3121. @param[in, out] result A reference to the string variable where the read
  3122. string is to be stored.
  3123. @tparam NumberType The type of the length @a len
  3124. @pre len >= 1
  3125. @return `true` if the string was successfully parsed
  3126. */
  3127. template<typename NumberType>
  3128. bool get_bson_string(const NumberType len, string_t& result)
  3129. {
  3130. if (JSON_UNLIKELY(len < 1))
  3131. {
  3132. auto last_token = get_token_string();
  3133. 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")));
  3134. }
  3135. return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof();
  3136. }
  3137. /*!
  3138. @brief Read a BSON document element of the given @a element_type.
  3139. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html
  3140. @param[in] element_type_parse_position The position in the input stream,
  3141. where the `element_type` was read.
  3142. @warning Not all BSON element types are supported yet. An unsupported
  3143. @a element_type will give rise to a parse_error.114:
  3144. Unsupported BSON record type 0x...
  3145. @return whether a valid BSON-object/array was passed to the SAX parser
  3146. */
  3147. bool parse_bson_element_internal(const int element_type,
  3148. const std::size_t element_type_parse_position)
  3149. {
  3150. switch (element_type)
  3151. {
  3152. case 0x01: // double
  3153. {
  3154. double number;
  3155. return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3156. }
  3157. case 0x02: // string
  3158. {
  3159. std::int32_t len;
  3160. string_t value;
  3161. return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value);
  3162. }
  3163. case 0x03: // object
  3164. {
  3165. return parse_bson_internal();
  3166. }
  3167. case 0x04: // array
  3168. {
  3169. return parse_bson_array();
  3170. }
  3171. case 0x08: // boolean
  3172. {
  3173. return sax->boolean(get() != 0);
  3174. }
  3175. case 0x0A: // null
  3176. {
  3177. return sax->null();
  3178. }
  3179. case 0x10: // int32
  3180. {
  3181. std::int32_t value;
  3182. return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  3183. }
  3184. case 0x12: // int64
  3185. {
  3186. std::int64_t value;
  3187. return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value);
  3188. }
  3189. default: // anything else not supported (yet)
  3190. {
  3191. std::array<char, 3> cr{{}};
  3192. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(element_type));
  3193. 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())));
  3194. }
  3195. }
  3196. }
  3197. /*!
  3198. @brief Read a BSON element list (as specified in the BSON-spec)
  3199. The same binary layout is used for objects and arrays, hence it must be
  3200. indicated with the argument @a is_array which one is expected
  3201. (true --> array, false --> object).
  3202. @param[in] is_array Determines if the element list being read is to be
  3203. treated as an object (@a is_array == false), or as an
  3204. array (@a is_array == true).
  3205. @return whether a valid BSON-object/array was passed to the SAX parser
  3206. */
  3207. bool parse_bson_element_list(const bool is_array)
  3208. {
  3209. string_t key;
  3210. while (int element_type = get())
  3211. {
  3212. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list")))
  3213. {
  3214. return false;
  3215. }
  3216. const std::size_t element_type_parse_position = chars_read;
  3217. if (JSON_UNLIKELY(not get_bson_cstr(key)))
  3218. {
  3219. return false;
  3220. }
  3221. if (not is_array and not sax->key(key))
  3222. {
  3223. return false;
  3224. }
  3225. if (JSON_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position)))
  3226. {
  3227. return false;
  3228. }
  3229. // get_bson_cstr only appends
  3230. key.clear();
  3231. }
  3232. return true;
  3233. }
  3234. /*!
  3235. @brief Reads an array from the BSON input and passes it to the SAX-parser.
  3236. @return whether a valid BSON-array was passed to the SAX parser
  3237. */
  3238. bool parse_bson_array()
  3239. {
  3240. std::int32_t document_size;
  3241. get_number<std::int32_t, true>(input_format_t::bson, document_size);
  3242. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  3243. {
  3244. return false;
  3245. }
  3246. if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/true)))
  3247. {
  3248. return false;
  3249. }
  3250. return sax->end_array();
  3251. }
  3252. //////////
  3253. // CBOR //
  3254. //////////
  3255. /*!
  3256. @param[in] get_char whether a new character should be retrieved from the
  3257. input (true, default) or whether the last read
  3258. character should be considered instead
  3259. @return whether a valid CBOR value was passed to the SAX parser
  3260. */
  3261. bool parse_cbor_internal(const bool get_char = true)
  3262. {
  3263. switch (get_char ? get() : current)
  3264. {
  3265. // EOF
  3266. case std::char_traits<char>::eof():
  3267. return unexpect_eof(input_format_t::cbor, "value");
  3268. // Integer 0x00..0x17 (0..23)
  3269. case 0x00:
  3270. case 0x01:
  3271. case 0x02:
  3272. case 0x03:
  3273. case 0x04:
  3274. case 0x05:
  3275. case 0x06:
  3276. case 0x07:
  3277. case 0x08:
  3278. case 0x09:
  3279. case 0x0A:
  3280. case 0x0B:
  3281. case 0x0C:
  3282. case 0x0D:
  3283. case 0x0E:
  3284. case 0x0F:
  3285. case 0x10:
  3286. case 0x11:
  3287. case 0x12:
  3288. case 0x13:
  3289. case 0x14:
  3290. case 0x15:
  3291. case 0x16:
  3292. case 0x17:
  3293. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  3294. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  3295. {
  3296. std::uint8_t number;
  3297. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3298. }
  3299. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  3300. {
  3301. std::uint16_t number;
  3302. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3303. }
  3304. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  3305. {
  3306. std::uint32_t number;
  3307. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3308. }
  3309. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  3310. {
  3311. std::uint64_t number;
  3312. return get_number(input_format_t::cbor, number) and sax->number_unsigned(number);
  3313. }
  3314. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  3315. case 0x20:
  3316. case 0x21:
  3317. case 0x22:
  3318. case 0x23:
  3319. case 0x24:
  3320. case 0x25:
  3321. case 0x26:
  3322. case 0x27:
  3323. case 0x28:
  3324. case 0x29:
  3325. case 0x2A:
  3326. case 0x2B:
  3327. case 0x2C:
  3328. case 0x2D:
  3329. case 0x2E:
  3330. case 0x2F:
  3331. case 0x30:
  3332. case 0x31:
  3333. case 0x32:
  3334. case 0x33:
  3335. case 0x34:
  3336. case 0x35:
  3337. case 0x36:
  3338. case 0x37:
  3339. return sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - current));
  3340. case 0x38: // Negative integer (one-byte uint8_t follows)
  3341. {
  3342. std::uint8_t number;
  3343. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3344. }
  3345. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  3346. {
  3347. std::uint16_t number;
  3348. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3349. }
  3350. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  3351. {
  3352. std::uint32_t number;
  3353. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  3354. }
  3355. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  3356. {
  3357. std::uint64_t number;
  3358. return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1)
  3359. - static_cast<number_integer_t>(number));
  3360. }
  3361. // UTF-8 string (0x00..0x17 bytes follow)
  3362. case 0x60:
  3363. case 0x61:
  3364. case 0x62:
  3365. case 0x63:
  3366. case 0x64:
  3367. case 0x65:
  3368. case 0x66:
  3369. case 0x67:
  3370. case 0x68:
  3371. case 0x69:
  3372. case 0x6A:
  3373. case 0x6B:
  3374. case 0x6C:
  3375. case 0x6D:
  3376. case 0x6E:
  3377. case 0x6F:
  3378. case 0x70:
  3379. case 0x71:
  3380. case 0x72:
  3381. case 0x73:
  3382. case 0x74:
  3383. case 0x75:
  3384. case 0x76:
  3385. case 0x77:
  3386. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  3387. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  3388. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  3389. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  3390. case 0x7F: // UTF-8 string (indefinite length)
  3391. {
  3392. string_t s;
  3393. return get_cbor_string(s) and sax->string(s);
  3394. }
  3395. // array (0x00..0x17 data items follow)
  3396. case 0x80:
  3397. case 0x81:
  3398. case 0x82:
  3399. case 0x83:
  3400. case 0x84:
  3401. case 0x85:
  3402. case 0x86:
  3403. case 0x87:
  3404. case 0x88:
  3405. case 0x89:
  3406. case 0x8A:
  3407. case 0x8B:
  3408. case 0x8C:
  3409. case 0x8D:
  3410. case 0x8E:
  3411. case 0x8F:
  3412. case 0x90:
  3413. case 0x91:
  3414. case 0x92:
  3415. case 0x93:
  3416. case 0x94:
  3417. case 0x95:
  3418. case 0x96:
  3419. case 0x97:
  3420. return get_cbor_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  3421. case 0x98: // array (one-byte uint8_t for n follows)
  3422. {
  3423. std::uint8_t len;
  3424. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3425. }
  3426. case 0x99: // array (two-byte uint16_t for n follow)
  3427. {
  3428. std::uint16_t len;
  3429. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3430. }
  3431. case 0x9A: // array (four-byte uint32_t for n follow)
  3432. {
  3433. std::uint32_t len;
  3434. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3435. }
  3436. case 0x9B: // array (eight-byte uint64_t for n follow)
  3437. {
  3438. std::uint64_t len;
  3439. return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len));
  3440. }
  3441. case 0x9F: // array (indefinite length)
  3442. return get_cbor_array(std::size_t(-1));
  3443. // map (0x00..0x17 pairs of data items follow)
  3444. case 0xA0:
  3445. case 0xA1:
  3446. case 0xA2:
  3447. case 0xA3:
  3448. case 0xA4:
  3449. case 0xA5:
  3450. case 0xA6:
  3451. case 0xA7:
  3452. case 0xA8:
  3453. case 0xA9:
  3454. case 0xAA:
  3455. case 0xAB:
  3456. case 0xAC:
  3457. case 0xAD:
  3458. case 0xAE:
  3459. case 0xAF:
  3460. case 0xB0:
  3461. case 0xB1:
  3462. case 0xB2:
  3463. case 0xB3:
  3464. case 0xB4:
  3465. case 0xB5:
  3466. case 0xB6:
  3467. case 0xB7:
  3468. return get_cbor_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
  3469. case 0xB8: // map (one-byte uint8_t for n follows)
  3470. {
  3471. std::uint8_t len;
  3472. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3473. }
  3474. case 0xB9: // map (two-byte uint16_t for n follow)
  3475. {
  3476. std::uint16_t len;
  3477. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3478. }
  3479. case 0xBA: // map (four-byte uint32_t for n follow)
  3480. {
  3481. std::uint32_t len;
  3482. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3483. }
  3484. case 0xBB: // map (eight-byte uint64_t for n follow)
  3485. {
  3486. std::uint64_t len;
  3487. return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len));
  3488. }
  3489. case 0xBF: // map (indefinite length)
  3490. return get_cbor_object(std::size_t(-1));
  3491. case 0xF4: // false
  3492. return sax->boolean(false);
  3493. case 0xF5: // true
  3494. return sax->boolean(true);
  3495. case 0xF6: // null
  3496. return sax->null();
  3497. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  3498. {
  3499. const int byte1_raw = get();
  3500. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  3501. {
  3502. return false;
  3503. }
  3504. const int byte2_raw = get();
  3505. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number")))
  3506. {
  3507. return false;
  3508. }
  3509. const auto byte1 = static_cast<unsigned char>(byte1_raw);
  3510. const auto byte2 = static_cast<unsigned char>(byte2_raw);
  3511. // code from RFC 7049, Appendix D, Figure 3:
  3512. // As half-precision floating-point numbers were only added
  3513. // to IEEE 754 in 2008, today's programming platforms often
  3514. // still only have limited support for them. It is very
  3515. // easy to include at least decoding support for them even
  3516. // without such support. An example of a small decoder for
  3517. // half-precision floating-point numbers in the C language
  3518. // is shown in Fig. 3.
  3519. const auto half = static_cast<unsigned int>((byte1 << 8u) + byte2);
  3520. const double val = [&half]
  3521. {
  3522. const int exp = (half >> 10u) & 0x1Fu;
  3523. const unsigned int mant = half & 0x3FFu;
  3524. assert(0 <= exp and exp <= 32);
  3525. assert(0 <= mant and mant <= 1024);
  3526. switch (exp)
  3527. {
  3528. case 0:
  3529. return std::ldexp(mant, -24);
  3530. case 31:
  3531. return (mant == 0)
  3532. ? std::numeric_limits<double>::infinity()
  3533. : std::numeric_limits<double>::quiet_NaN();
  3534. default:
  3535. return std::ldexp(mant + 1024, exp - 25);
  3536. }
  3537. }();
  3538. return sax->number_float((half & 0x8000u) != 0
  3539. ? static_cast<number_float_t>(-val)
  3540. : static_cast<number_float_t>(val), "");
  3541. }
  3542. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  3543. {
  3544. float number;
  3545. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3546. }
  3547. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  3548. {
  3549. double number;
  3550. return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3551. }
  3552. default: // anything else (0xFF is handled inside the other types)
  3553. {
  3554. auto last_token = get_token_string();
  3555. 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")));
  3556. }
  3557. }
  3558. }
  3559. /*!
  3560. @brief reads a CBOR string
  3561. This function first reads starting bytes to determine the expected
  3562. string length and then copies this number of bytes into a string.
  3563. Additionally, CBOR's strings with indefinite lengths are supported.
  3564. @param[out] result created string
  3565. @return whether string creation completed
  3566. */
  3567. bool get_cbor_string(string_t& result)
  3568. {
  3569. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string")))
  3570. {
  3571. return false;
  3572. }
  3573. switch (current)
  3574. {
  3575. // UTF-8 string (0x00..0x17 bytes follow)
  3576. case 0x60:
  3577. case 0x61:
  3578. case 0x62:
  3579. case 0x63:
  3580. case 0x64:
  3581. case 0x65:
  3582. case 0x66:
  3583. case 0x67:
  3584. case 0x68:
  3585. case 0x69:
  3586. case 0x6A:
  3587. case 0x6B:
  3588. case 0x6C:
  3589. case 0x6D:
  3590. case 0x6E:
  3591. case 0x6F:
  3592. case 0x70:
  3593. case 0x71:
  3594. case 0x72:
  3595. case 0x73:
  3596. case 0x74:
  3597. case 0x75:
  3598. case 0x76:
  3599. case 0x77:
  3600. {
  3601. return get_string(input_format_t::cbor, static_cast<unsigned int>(current) & 0x1Fu, result);
  3602. }
  3603. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  3604. {
  3605. std::uint8_t len;
  3606. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3607. }
  3608. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  3609. {
  3610. std::uint16_t len;
  3611. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3612. }
  3613. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  3614. {
  3615. std::uint32_t len;
  3616. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3617. }
  3618. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  3619. {
  3620. std::uint64_t len;
  3621. return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result);
  3622. }
  3623. case 0x7F: // UTF-8 string (indefinite length)
  3624. {
  3625. while (get() != 0xFF)
  3626. {
  3627. string_t chunk;
  3628. if (not get_cbor_string(chunk))
  3629. {
  3630. return false;
  3631. }
  3632. result.append(chunk);
  3633. }
  3634. return true;
  3635. }
  3636. default:
  3637. {
  3638. auto last_token = get_token_string();
  3639. 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")));
  3640. }
  3641. }
  3642. }
  3643. /*!
  3644. @param[in] len the length of the array or std::size_t(-1) for an
  3645. array of indefinite size
  3646. @return whether array creation completed
  3647. */
  3648. bool get_cbor_array(const std::size_t len)
  3649. {
  3650. if (JSON_UNLIKELY(not sax->start_array(len)))
  3651. {
  3652. return false;
  3653. }
  3654. if (len != std::size_t(-1))
  3655. {
  3656. for (std::size_t i = 0; i < len; ++i)
  3657. {
  3658. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3659. {
  3660. return false;
  3661. }
  3662. }
  3663. }
  3664. else
  3665. {
  3666. while (get() != 0xFF)
  3667. {
  3668. if (JSON_UNLIKELY(not parse_cbor_internal(false)))
  3669. {
  3670. return false;
  3671. }
  3672. }
  3673. }
  3674. return sax->end_array();
  3675. }
  3676. /*!
  3677. @param[in] len the length of the object or std::size_t(-1) for an
  3678. object of indefinite size
  3679. @return whether object creation completed
  3680. */
  3681. bool get_cbor_object(const std::size_t len)
  3682. {
  3683. if (JSON_UNLIKELY(not sax->start_object(len)))
  3684. {
  3685. return false;
  3686. }
  3687. string_t key;
  3688. if (len != std::size_t(-1))
  3689. {
  3690. for (std::size_t i = 0; i < len; ++i)
  3691. {
  3692. get();
  3693. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  3694. {
  3695. return false;
  3696. }
  3697. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3698. {
  3699. return false;
  3700. }
  3701. key.clear();
  3702. }
  3703. }
  3704. else
  3705. {
  3706. while (get() != 0xFF)
  3707. {
  3708. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  3709. {
  3710. return false;
  3711. }
  3712. if (JSON_UNLIKELY(not parse_cbor_internal()))
  3713. {
  3714. return false;
  3715. }
  3716. key.clear();
  3717. }
  3718. }
  3719. return sax->end_object();
  3720. }
  3721. /////////////
  3722. // MsgPack //
  3723. /////////////
  3724. /*!
  3725. @return whether a valid MessagePack value was passed to the SAX parser
  3726. */
  3727. bool parse_msgpack_internal()
  3728. {
  3729. switch (get())
  3730. {
  3731. // EOF
  3732. case std::char_traits<char>::eof():
  3733. return unexpect_eof(input_format_t::msgpack, "value");
  3734. // positive fixint
  3735. case 0x00:
  3736. case 0x01:
  3737. case 0x02:
  3738. case 0x03:
  3739. case 0x04:
  3740. case 0x05:
  3741. case 0x06:
  3742. case 0x07:
  3743. case 0x08:
  3744. case 0x09:
  3745. case 0x0A:
  3746. case 0x0B:
  3747. case 0x0C:
  3748. case 0x0D:
  3749. case 0x0E:
  3750. case 0x0F:
  3751. case 0x10:
  3752. case 0x11:
  3753. case 0x12:
  3754. case 0x13:
  3755. case 0x14:
  3756. case 0x15:
  3757. case 0x16:
  3758. case 0x17:
  3759. case 0x18:
  3760. case 0x19:
  3761. case 0x1A:
  3762. case 0x1B:
  3763. case 0x1C:
  3764. case 0x1D:
  3765. case 0x1E:
  3766. case 0x1F:
  3767. case 0x20:
  3768. case 0x21:
  3769. case 0x22:
  3770. case 0x23:
  3771. case 0x24:
  3772. case 0x25:
  3773. case 0x26:
  3774. case 0x27:
  3775. case 0x28:
  3776. case 0x29:
  3777. case 0x2A:
  3778. case 0x2B:
  3779. case 0x2C:
  3780. case 0x2D:
  3781. case 0x2E:
  3782. case 0x2F:
  3783. case 0x30:
  3784. case 0x31:
  3785. case 0x32:
  3786. case 0x33:
  3787. case 0x34:
  3788. case 0x35:
  3789. case 0x36:
  3790. case 0x37:
  3791. case 0x38:
  3792. case 0x39:
  3793. case 0x3A:
  3794. case 0x3B:
  3795. case 0x3C:
  3796. case 0x3D:
  3797. case 0x3E:
  3798. case 0x3F:
  3799. case 0x40:
  3800. case 0x41:
  3801. case 0x42:
  3802. case 0x43:
  3803. case 0x44:
  3804. case 0x45:
  3805. case 0x46:
  3806. case 0x47:
  3807. case 0x48:
  3808. case 0x49:
  3809. case 0x4A:
  3810. case 0x4B:
  3811. case 0x4C:
  3812. case 0x4D:
  3813. case 0x4E:
  3814. case 0x4F:
  3815. case 0x50:
  3816. case 0x51:
  3817. case 0x52:
  3818. case 0x53:
  3819. case 0x54:
  3820. case 0x55:
  3821. case 0x56:
  3822. case 0x57:
  3823. case 0x58:
  3824. case 0x59:
  3825. case 0x5A:
  3826. case 0x5B:
  3827. case 0x5C:
  3828. case 0x5D:
  3829. case 0x5E:
  3830. case 0x5F:
  3831. case 0x60:
  3832. case 0x61:
  3833. case 0x62:
  3834. case 0x63:
  3835. case 0x64:
  3836. case 0x65:
  3837. case 0x66:
  3838. case 0x67:
  3839. case 0x68:
  3840. case 0x69:
  3841. case 0x6A:
  3842. case 0x6B:
  3843. case 0x6C:
  3844. case 0x6D:
  3845. case 0x6E:
  3846. case 0x6F:
  3847. case 0x70:
  3848. case 0x71:
  3849. case 0x72:
  3850. case 0x73:
  3851. case 0x74:
  3852. case 0x75:
  3853. case 0x76:
  3854. case 0x77:
  3855. case 0x78:
  3856. case 0x79:
  3857. case 0x7A:
  3858. case 0x7B:
  3859. case 0x7C:
  3860. case 0x7D:
  3861. case 0x7E:
  3862. case 0x7F:
  3863. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  3864. // fixmap
  3865. case 0x80:
  3866. case 0x81:
  3867. case 0x82:
  3868. case 0x83:
  3869. case 0x84:
  3870. case 0x85:
  3871. case 0x86:
  3872. case 0x87:
  3873. case 0x88:
  3874. case 0x89:
  3875. case 0x8A:
  3876. case 0x8B:
  3877. case 0x8C:
  3878. case 0x8D:
  3879. case 0x8E:
  3880. case 0x8F:
  3881. return get_msgpack_object(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  3882. // fixarray
  3883. case 0x90:
  3884. case 0x91:
  3885. case 0x92:
  3886. case 0x93:
  3887. case 0x94:
  3888. case 0x95:
  3889. case 0x96:
  3890. case 0x97:
  3891. case 0x98:
  3892. case 0x99:
  3893. case 0x9A:
  3894. case 0x9B:
  3895. case 0x9C:
  3896. case 0x9D:
  3897. case 0x9E:
  3898. case 0x9F:
  3899. return get_msgpack_array(static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x0Fu));
  3900. // fixstr
  3901. case 0xA0:
  3902. case 0xA1:
  3903. case 0xA2:
  3904. case 0xA3:
  3905. case 0xA4:
  3906. case 0xA5:
  3907. case 0xA6:
  3908. case 0xA7:
  3909. case 0xA8:
  3910. case 0xA9:
  3911. case 0xAA:
  3912. case 0xAB:
  3913. case 0xAC:
  3914. case 0xAD:
  3915. case 0xAE:
  3916. case 0xAF:
  3917. case 0xB0:
  3918. case 0xB1:
  3919. case 0xB2:
  3920. case 0xB3:
  3921. case 0xB4:
  3922. case 0xB5:
  3923. case 0xB6:
  3924. case 0xB7:
  3925. case 0xB8:
  3926. case 0xB9:
  3927. case 0xBA:
  3928. case 0xBB:
  3929. case 0xBC:
  3930. case 0xBD:
  3931. case 0xBE:
  3932. case 0xBF:
  3933. {
  3934. string_t s;
  3935. return get_msgpack_string(s) and sax->string(s);
  3936. }
  3937. case 0xC0: // nil
  3938. return sax->null();
  3939. case 0xC2: // false
  3940. return sax->boolean(false);
  3941. case 0xC3: // true
  3942. return sax->boolean(true);
  3943. case 0xCA: // float 32
  3944. {
  3945. float number;
  3946. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3947. }
  3948. case 0xCB: // float 64
  3949. {
  3950. double number;
  3951. return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), "");
  3952. }
  3953. case 0xCC: // uint 8
  3954. {
  3955. std::uint8_t number;
  3956. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3957. }
  3958. case 0xCD: // uint 16
  3959. {
  3960. std::uint16_t number;
  3961. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3962. }
  3963. case 0xCE: // uint 32
  3964. {
  3965. std::uint32_t number;
  3966. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3967. }
  3968. case 0xCF: // uint 64
  3969. {
  3970. std::uint64_t number;
  3971. return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number);
  3972. }
  3973. case 0xD0: // int 8
  3974. {
  3975. std::int8_t number;
  3976. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  3977. }
  3978. case 0xD1: // int 16
  3979. {
  3980. std::int16_t number;
  3981. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  3982. }
  3983. case 0xD2: // int 32
  3984. {
  3985. std::int32_t number;
  3986. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  3987. }
  3988. case 0xD3: // int 64
  3989. {
  3990. std::int64_t number;
  3991. return get_number(input_format_t::msgpack, number) and sax->number_integer(number);
  3992. }
  3993. case 0xD9: // str 8
  3994. case 0xDA: // str 16
  3995. case 0xDB: // str 32
  3996. {
  3997. string_t s;
  3998. return get_msgpack_string(s) and sax->string(s);
  3999. }
  4000. case 0xDC: // array 16
  4001. {
  4002. std::uint16_t len;
  4003. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  4004. }
  4005. case 0xDD: // array 32
  4006. {
  4007. std::uint32_t len;
  4008. return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len));
  4009. }
  4010. case 0xDE: // map 16
  4011. {
  4012. std::uint16_t len;
  4013. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  4014. }
  4015. case 0xDF: // map 32
  4016. {
  4017. std::uint32_t len;
  4018. return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len));
  4019. }
  4020. // negative fixint
  4021. case 0xE0:
  4022. case 0xE1:
  4023. case 0xE2:
  4024. case 0xE3:
  4025. case 0xE4:
  4026. case 0xE5:
  4027. case 0xE6:
  4028. case 0xE7:
  4029. case 0xE8:
  4030. case 0xE9:
  4031. case 0xEA:
  4032. case 0xEB:
  4033. case 0xEC:
  4034. case 0xED:
  4035. case 0xEE:
  4036. case 0xEF:
  4037. case 0xF0:
  4038. case 0xF1:
  4039. case 0xF2:
  4040. case 0xF3:
  4041. case 0xF4:
  4042. case 0xF5:
  4043. case 0xF6:
  4044. case 0xF7:
  4045. case 0xF8:
  4046. case 0xF9:
  4047. case 0xFA:
  4048. case 0xFB:
  4049. case 0xFC:
  4050. case 0xFD:
  4051. case 0xFE:
  4052. case 0xFF:
  4053. return sax->number_integer(static_cast<std::int8_t>(current));
  4054. default: // anything else
  4055. {
  4056. auto last_token = get_token_string();
  4057. 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")));
  4058. }
  4059. }
  4060. }
  4061. /*!
  4062. @brief reads a MessagePack string
  4063. This function first reads starting bytes to determine the expected
  4064. string length and then copies this number of bytes into a string.
  4065. @param[out] result created string
  4066. @return whether string creation completed
  4067. */
  4068. bool get_msgpack_string(string_t& result)
  4069. {
  4070. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string")))
  4071. {
  4072. return false;
  4073. }
  4074. switch (current)
  4075. {
  4076. // fixstr
  4077. case 0xA0:
  4078. case 0xA1:
  4079. case 0xA2:
  4080. case 0xA3:
  4081. case 0xA4:
  4082. case 0xA5:
  4083. case 0xA6:
  4084. case 0xA7:
  4085. case 0xA8:
  4086. case 0xA9:
  4087. case 0xAA:
  4088. case 0xAB:
  4089. case 0xAC:
  4090. case 0xAD:
  4091. case 0xAE:
  4092. case 0xAF:
  4093. case 0xB0:
  4094. case 0xB1:
  4095. case 0xB2:
  4096. case 0xB3:
  4097. case 0xB4:
  4098. case 0xB5:
  4099. case 0xB6:
  4100. case 0xB7:
  4101. case 0xB8:
  4102. case 0xB9:
  4103. case 0xBA:
  4104. case 0xBB:
  4105. case 0xBC:
  4106. case 0xBD:
  4107. case 0xBE:
  4108. case 0xBF:
  4109. {
  4110. return get_string(input_format_t::msgpack, static_cast<unsigned int>(current) & 0x1Fu, result);
  4111. }
  4112. case 0xD9: // str 8
  4113. {
  4114. std::uint8_t len;
  4115. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4116. }
  4117. case 0xDA: // str 16
  4118. {
  4119. std::uint16_t len;
  4120. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4121. }
  4122. case 0xDB: // str 32
  4123. {
  4124. std::uint32_t len;
  4125. return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result);
  4126. }
  4127. default:
  4128. {
  4129. auto last_token = get_token_string();
  4130. 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")));
  4131. }
  4132. }
  4133. }
  4134. /*!
  4135. @param[in] len the length of the array
  4136. @return whether array creation completed
  4137. */
  4138. bool get_msgpack_array(const std::size_t len)
  4139. {
  4140. if (JSON_UNLIKELY(not sax->start_array(len)))
  4141. {
  4142. return false;
  4143. }
  4144. for (std::size_t i = 0; i < len; ++i)
  4145. {
  4146. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  4147. {
  4148. return false;
  4149. }
  4150. }
  4151. return sax->end_array();
  4152. }
  4153. /*!
  4154. @param[in] len the length of the object
  4155. @return whether object creation completed
  4156. */
  4157. bool get_msgpack_object(const std::size_t len)
  4158. {
  4159. if (JSON_UNLIKELY(not sax->start_object(len)))
  4160. {
  4161. return false;
  4162. }
  4163. string_t key;
  4164. for (std::size_t i = 0; i < len; ++i)
  4165. {
  4166. get();
  4167. if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  4168. {
  4169. return false;
  4170. }
  4171. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  4172. {
  4173. return false;
  4174. }
  4175. key.clear();
  4176. }
  4177. return sax->end_object();
  4178. }
  4179. ////////////
  4180. // UBJSON //
  4181. ////////////
  4182. /*!
  4183. @param[in] get_char whether a new character should be retrieved from the
  4184. input (true, default) or whether the last read
  4185. character should be considered instead
  4186. @return whether a valid UBJSON value was passed to the SAX parser
  4187. */
  4188. bool parse_ubjson_internal(const bool get_char = true)
  4189. {
  4190. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  4191. }
  4192. /*!
  4193. @brief reads a UBJSON string
  4194. This function is either called after reading the 'S' byte explicitly
  4195. indicating a string, or in case of an object key where the 'S' byte can be
  4196. left out.
  4197. @param[out] result created string
  4198. @param[in] get_char whether a new character should be retrieved from the
  4199. input (true, default) or whether the last read
  4200. character should be considered instead
  4201. @return whether string creation completed
  4202. */
  4203. bool get_ubjson_string(string_t& result, const bool get_char = true)
  4204. {
  4205. if (get_char)
  4206. {
  4207. get(); // TODO(niels): may we ignore N here?
  4208. }
  4209. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  4210. {
  4211. return false;
  4212. }
  4213. switch (current)
  4214. {
  4215. case 'U':
  4216. {
  4217. std::uint8_t len;
  4218. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4219. }
  4220. case 'i':
  4221. {
  4222. std::int8_t len;
  4223. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4224. }
  4225. case 'I':
  4226. {
  4227. std::int16_t len;
  4228. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4229. }
  4230. case 'l':
  4231. {
  4232. std::int32_t len;
  4233. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4234. }
  4235. case 'L':
  4236. {
  4237. std::int64_t len;
  4238. return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result);
  4239. }
  4240. default:
  4241. auto last_token = get_token_string();
  4242. 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")));
  4243. }
  4244. }
  4245. /*!
  4246. @param[out] result determined size
  4247. @return whether size determination completed
  4248. */
  4249. bool get_ubjson_size_value(std::size_t& result)
  4250. {
  4251. switch (get_ignore_noop())
  4252. {
  4253. case 'U':
  4254. {
  4255. std::uint8_t number;
  4256. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4257. {
  4258. return false;
  4259. }
  4260. result = static_cast<std::size_t>(number);
  4261. return true;
  4262. }
  4263. case 'i':
  4264. {
  4265. std::int8_t number;
  4266. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4267. {
  4268. return false;
  4269. }
  4270. result = static_cast<std::size_t>(number);
  4271. return true;
  4272. }
  4273. case 'I':
  4274. {
  4275. std::int16_t number;
  4276. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4277. {
  4278. return false;
  4279. }
  4280. result = static_cast<std::size_t>(number);
  4281. return true;
  4282. }
  4283. case 'l':
  4284. {
  4285. std::int32_t number;
  4286. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4287. {
  4288. return false;
  4289. }
  4290. result = static_cast<std::size_t>(number);
  4291. return true;
  4292. }
  4293. case 'L':
  4294. {
  4295. std::int64_t number;
  4296. if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number)))
  4297. {
  4298. return false;
  4299. }
  4300. result = static_cast<std::size_t>(number);
  4301. return true;
  4302. }
  4303. default:
  4304. {
  4305. auto last_token = get_token_string();
  4306. 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")));
  4307. }
  4308. }
  4309. }
  4310. /*!
  4311. @brief determine the type and size for a container
  4312. In the optimized UBJSON format, a type and a size can be provided to allow
  4313. for a more compact representation.
  4314. @param[out] result pair of the size and the type
  4315. @return whether pair creation completed
  4316. */
  4317. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  4318. {
  4319. result.first = string_t::npos; // size
  4320. result.second = 0; // type
  4321. get_ignore_noop();
  4322. if (current == '$')
  4323. {
  4324. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  4325. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type")))
  4326. {
  4327. return false;
  4328. }
  4329. get_ignore_noop();
  4330. if (JSON_UNLIKELY(current != '#'))
  4331. {
  4332. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value")))
  4333. {
  4334. return false;
  4335. }
  4336. auto last_token = get_token_string();
  4337. 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")));
  4338. }
  4339. return get_ubjson_size_value(result.first);
  4340. }
  4341. if (current == '#')
  4342. {
  4343. return get_ubjson_size_value(result.first);
  4344. }
  4345. return true;
  4346. }
  4347. /*!
  4348. @param prefix the previously read or set type prefix
  4349. @return whether value creation completed
  4350. */
  4351. bool get_ubjson_value(const int prefix)
  4352. {
  4353. switch (prefix)
  4354. {
  4355. case std::char_traits<char>::eof(): // EOF
  4356. return unexpect_eof(input_format_t::ubjson, "value");
  4357. case 'T': // true
  4358. return sax->boolean(true);
  4359. case 'F': // false
  4360. return sax->boolean(false);
  4361. case 'Z': // null
  4362. return sax->null();
  4363. case 'U':
  4364. {
  4365. std::uint8_t number;
  4366. return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number);
  4367. }
  4368. case 'i':
  4369. {
  4370. std::int8_t number;
  4371. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4372. }
  4373. case 'I':
  4374. {
  4375. std::int16_t number;
  4376. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4377. }
  4378. case 'l':
  4379. {
  4380. std::int32_t number;
  4381. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4382. }
  4383. case 'L':
  4384. {
  4385. std::int64_t number;
  4386. return get_number(input_format_t::ubjson, number) and sax->number_integer(number);
  4387. }
  4388. case 'd':
  4389. {
  4390. float number;
  4391. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4392. }
  4393. case 'D':
  4394. {
  4395. double number;
  4396. return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), "");
  4397. }
  4398. case 'C': // char
  4399. {
  4400. get();
  4401. if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char")))
  4402. {
  4403. return false;
  4404. }
  4405. if (JSON_UNLIKELY(current > 127))
  4406. {
  4407. auto last_token = get_token_string();
  4408. 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")));
  4409. }
  4410. string_t s(1, static_cast<char>(current));
  4411. return sax->string(s);
  4412. }
  4413. case 'S': // string
  4414. {
  4415. string_t s;
  4416. return get_ubjson_string(s) and sax->string(s);
  4417. }
  4418. case '[': // array
  4419. return get_ubjson_array();
  4420. case '{': // object
  4421. return get_ubjson_object();
  4422. default: // anything else
  4423. {
  4424. auto last_token = get_token_string();
  4425. 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")));
  4426. }
  4427. }
  4428. }
  4429. /*!
  4430. @return whether array creation completed
  4431. */
  4432. bool get_ubjson_array()
  4433. {
  4434. std::pair<std::size_t, int> size_and_type;
  4435. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  4436. {
  4437. return false;
  4438. }
  4439. if (size_and_type.first != string_t::npos)
  4440. {
  4441. if (JSON_UNLIKELY(not sax->start_array(size_and_type.first)))
  4442. {
  4443. return false;
  4444. }
  4445. if (size_and_type.second != 0)
  4446. {
  4447. if (size_and_type.second != 'N')
  4448. {
  4449. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4450. {
  4451. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  4452. {
  4453. return false;
  4454. }
  4455. }
  4456. }
  4457. }
  4458. else
  4459. {
  4460. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4461. {
  4462. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4463. {
  4464. return false;
  4465. }
  4466. }
  4467. }
  4468. }
  4469. else
  4470. {
  4471. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4472. {
  4473. return false;
  4474. }
  4475. while (current != ']')
  4476. {
  4477. if (JSON_UNLIKELY(not parse_ubjson_internal(false)))
  4478. {
  4479. return false;
  4480. }
  4481. get_ignore_noop();
  4482. }
  4483. }
  4484. return sax->end_array();
  4485. }
  4486. /*!
  4487. @return whether object creation completed
  4488. */
  4489. bool get_ubjson_object()
  4490. {
  4491. std::pair<std::size_t, int> size_and_type;
  4492. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  4493. {
  4494. return false;
  4495. }
  4496. string_t key;
  4497. if (size_and_type.first != string_t::npos)
  4498. {
  4499. if (JSON_UNLIKELY(not sax->start_object(size_and_type.first)))
  4500. {
  4501. return false;
  4502. }
  4503. if (size_and_type.second != 0)
  4504. {
  4505. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4506. {
  4507. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  4508. {
  4509. return false;
  4510. }
  4511. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  4512. {
  4513. return false;
  4514. }
  4515. key.clear();
  4516. }
  4517. }
  4518. else
  4519. {
  4520. for (std::size_t i = 0; i < size_and_type.first; ++i)
  4521. {
  4522. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  4523. {
  4524. return false;
  4525. }
  4526. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4527. {
  4528. return false;
  4529. }
  4530. key.clear();
  4531. }
  4532. }
  4533. }
  4534. else
  4535. {
  4536. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4537. {
  4538. return false;
  4539. }
  4540. while (current != '}')
  4541. {
  4542. if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  4543. {
  4544. return false;
  4545. }
  4546. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  4547. {
  4548. return false;
  4549. }
  4550. get_ignore_noop();
  4551. key.clear();
  4552. }
  4553. }
  4554. return sax->end_object();
  4555. }
  4556. ///////////////////////
  4557. // Utility functions //
  4558. ///////////////////////
  4559. /*!
  4560. @brief get next character from the input
  4561. This function provides the interface to the used input adapter. It does
  4562. not throw in case the input reached EOF, but returns a -'ve valued
  4563. `std::char_traits<char>::eof()` in that case.
  4564. @return character read from the input
  4565. */
  4566. int get()
  4567. {
  4568. ++chars_read;
  4569. return current = ia->get_character();
  4570. }
  4571. /*!
  4572. @return character read from the input after ignoring all 'N' entries
  4573. */
  4574. int get_ignore_noop()
  4575. {
  4576. do
  4577. {
  4578. get();
  4579. }
  4580. while (current == 'N');
  4581. return current;
  4582. }
  4583. /*
  4584. @brief read a number from the input
  4585. @tparam NumberType the type of the number
  4586. @param[in] format the current format (for diagnostics)
  4587. @param[out] result number of type @a NumberType
  4588. @return whether conversion completed
  4589. @note This function needs to respect the system's endianess, because
  4590. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  4591. (big endian) and therefore need reordering on little endian systems.
  4592. */
  4593. template<typename NumberType, bool InputIsLittleEndian = false>
  4594. bool get_number(const input_format_t format, NumberType& result)
  4595. {
  4596. // step 1: read input into array with system's byte order
  4597. std::array<std::uint8_t, sizeof(NumberType)> vec;
  4598. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  4599. {
  4600. get();
  4601. if (JSON_UNLIKELY(not unexpect_eof(format, "number")))
  4602. {
  4603. return false;
  4604. }
  4605. // reverse byte order prior to conversion if necessary
  4606. if (is_little_endian != InputIsLittleEndian)
  4607. {
  4608. vec[sizeof(NumberType) - i - 1] = static_cast<std::uint8_t>(current);
  4609. }
  4610. else
  4611. {
  4612. vec[i] = static_cast<std::uint8_t>(current); // LCOV_EXCL_LINE
  4613. }
  4614. }
  4615. // step 2: convert array into number of type T and return
  4616. std::memcpy(&result, vec.data(), sizeof(NumberType));
  4617. return true;
  4618. }
  4619. /*!
  4620. @brief create a string by reading characters from the input
  4621. @tparam NumberType the type of the number
  4622. @param[in] format the current format (for diagnostics)
  4623. @param[in] len number of characters to read
  4624. @param[out] result string created by reading @a len bytes
  4625. @return whether string creation completed
  4626. @note We can not reserve @a len bytes for the result, because @a len
  4627. may be too large. Usually, @ref unexpect_eof() detects the end of
  4628. the input before we run out of string memory.
  4629. */
  4630. template<typename NumberType>
  4631. bool get_string(const input_format_t format,
  4632. const NumberType len,
  4633. string_t& result)
  4634. {
  4635. bool success = true;
  4636. std::generate_n(std::back_inserter(result), len, [this, &success, &format]()
  4637. {
  4638. get();
  4639. if (JSON_UNLIKELY(not unexpect_eof(format, "string")))
  4640. {
  4641. success = false;
  4642. }
  4643. return static_cast<char>(current);
  4644. });
  4645. return success;
  4646. }
  4647. /*!
  4648. @param[in] format the current format (for diagnostics)
  4649. @param[in] context further context information (for diagnostics)
  4650. @return whether the last read character is not EOF
  4651. */
  4652. bool unexpect_eof(const input_format_t format, const char* context) const
  4653. {
  4654. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  4655. {
  4656. return sax->parse_error(chars_read, "<end of file>",
  4657. parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context)));
  4658. }
  4659. return true;
  4660. }
  4661. /*!
  4662. @return a string representation of the last read byte
  4663. */
  4664. std::string get_token_string() const
  4665. {
  4666. std::array<char, 3> cr{{}};
  4667. (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast<unsigned char>(current));
  4668. return std::string{cr.data()};
  4669. }
  4670. /*!
  4671. @param[in] format the current format
  4672. @param[in] detail a detailed error message
  4673. @param[in] context further contect information
  4674. @return a message string to use in the parse_error exceptions
  4675. */
  4676. std::string exception_message(const input_format_t format,
  4677. const std::string& detail,
  4678. const std::string& context) const
  4679. {
  4680. std::string error_msg = "syntax error while parsing ";
  4681. switch (format)
  4682. {
  4683. case input_format_t::cbor:
  4684. error_msg += "CBOR";
  4685. break;
  4686. case input_format_t::msgpack:
  4687. error_msg += "MessagePack";
  4688. break;
  4689. case input_format_t::ubjson:
  4690. error_msg += "UBJSON";
  4691. break;
  4692. case input_format_t::bson:
  4693. error_msg += "BSON";
  4694. break;
  4695. default: // LCOV_EXCL_LINE
  4696. assert(false); // LCOV_EXCL_LINE
  4697. }
  4698. return error_msg + " " + context + ": " + detail;
  4699. }
  4700. private:
  4701. /// input adapter
  4702. input_adapter_t ia = nullptr;
  4703. /// the current character
  4704. int current = std::char_traits<char>::eof();
  4705. /// the number of characters read
  4706. std::size_t chars_read = 0;
  4707. /// whether we can assume little endianess
  4708. const bool is_little_endian = little_endianess();
  4709. /// the SAX parser
  4710. json_sax_t* sax = nullptr;
  4711. };
  4712. } // namespace detail
  4713. } // namespace nlohmann
  4714. // #include <nlohmann/detail/input/input_adapters.hpp>
  4715. // #include <nlohmann/detail/input/lexer.hpp>
  4716. #include <array> // array
  4717. #include <clocale> // localeconv
  4718. #include <cstddef> // size_t
  4719. #include <cstdio> // snprintf
  4720. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  4721. #include <initializer_list> // initializer_list
  4722. #include <string> // char_traits, string
  4723. #include <utility> // move
  4724. #include <vector> // vector
  4725. // #include <nlohmann/detail/input/input_adapters.hpp>
  4726. // #include <nlohmann/detail/input/position_t.hpp>
  4727. // #include <nlohmann/detail/macro_scope.hpp>
  4728. namespace nlohmann
  4729. {
  4730. namespace detail
  4731. {
  4732. ///////////
  4733. // lexer //
  4734. ///////////
  4735. /*!
  4736. @brief lexical analysis
  4737. This class organizes the lexical analysis during JSON deserialization.
  4738. */
  4739. template<typename BasicJsonType>
  4740. class lexer
  4741. {
  4742. using number_integer_t = typename BasicJsonType::number_integer_t;
  4743. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  4744. using number_float_t = typename BasicJsonType::number_float_t;
  4745. using string_t = typename BasicJsonType::string_t;
  4746. public:
  4747. /// token types for the parser
  4748. enum class token_type
  4749. {
  4750. uninitialized, ///< indicating the scanner is uninitialized
  4751. literal_true, ///< the `true` literal
  4752. literal_false, ///< the `false` literal
  4753. literal_null, ///< the `null` literal
  4754. value_string, ///< a string -- use get_string() for actual value
  4755. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  4756. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  4757. value_float, ///< an floating point number -- use get_number_float() for actual value
  4758. begin_array, ///< the character for array begin `[`
  4759. begin_object, ///< the character for object begin `{`
  4760. end_array, ///< the character for array end `]`
  4761. end_object, ///< the character for object end `}`
  4762. name_separator, ///< the name separator `:`
  4763. value_separator, ///< the value separator `,`
  4764. parse_error, ///< indicating a parse error
  4765. end_of_input, ///< indicating the end of the input buffer
  4766. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  4767. };
  4768. /// return name of values of type token_type (only used for errors)
  4769. static const char* token_type_name(const token_type t) noexcept
  4770. {
  4771. switch (t)
  4772. {
  4773. case token_type::uninitialized:
  4774. return "<uninitialized>";
  4775. case token_type::literal_true:
  4776. return "true literal";
  4777. case token_type::literal_false:
  4778. return "false literal";
  4779. case token_type::literal_null:
  4780. return "null literal";
  4781. case token_type::value_string:
  4782. return "string literal";
  4783. case lexer::token_type::value_unsigned:
  4784. case lexer::token_type::value_integer:
  4785. case lexer::token_type::value_float:
  4786. return "number literal";
  4787. case token_type::begin_array:
  4788. return "'['";
  4789. case token_type::begin_object:
  4790. return "'{'";
  4791. case token_type::end_array:
  4792. return "']'";
  4793. case token_type::end_object:
  4794. return "'}'";
  4795. case token_type::name_separator:
  4796. return "':'";
  4797. case token_type::value_separator:
  4798. return "','";
  4799. case token_type::parse_error:
  4800. return "<parse error>";
  4801. case token_type::end_of_input:
  4802. return "end of input";
  4803. case token_type::literal_or_value:
  4804. return "'[', '{', or a literal";
  4805. // LCOV_EXCL_START
  4806. default: // catch non-enum values
  4807. return "unknown token";
  4808. // LCOV_EXCL_STOP
  4809. }
  4810. }
  4811. explicit lexer(detail::input_adapter_t&& adapter)
  4812. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  4813. // delete because of pointer members
  4814. lexer(const lexer&) = delete;
  4815. lexer(lexer&&) = delete;
  4816. lexer& operator=(lexer&) = delete;
  4817. lexer& operator=(lexer&&) = delete;
  4818. ~lexer() = default;
  4819. private:
  4820. /////////////////////
  4821. // locales
  4822. /////////////////////
  4823. /// return the locale-dependent decimal point
  4824. static char get_decimal_point() noexcept
  4825. {
  4826. const auto loc = localeconv();
  4827. assert(loc != nullptr);
  4828. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  4829. }
  4830. /////////////////////
  4831. // scan functions
  4832. /////////////////////
  4833. /*!
  4834. @brief get codepoint from 4 hex characters following `\u`
  4835. For input "\u c1 c2 c3 c4" the codepoint is:
  4836. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  4837. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  4838. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  4839. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  4840. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  4841. between the ASCII value of the character and the desired integer value.
  4842. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  4843. non-hex character)
  4844. */
  4845. int get_codepoint()
  4846. {
  4847. // this function only makes sense after reading `\u`
  4848. assert(current == 'u');
  4849. int codepoint = 0;
  4850. const auto factors = { 12u, 8u, 4u, 0u };
  4851. for (const auto factor : factors)
  4852. {
  4853. get();
  4854. if (current >= '0' and current <= '9')
  4855. {
  4856. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x30u) << factor);
  4857. }
  4858. else if (current >= 'A' and current <= 'F')
  4859. {
  4860. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x37u) << factor);
  4861. }
  4862. else if (current >= 'a' and current <= 'f')
  4863. {
  4864. codepoint += static_cast<int>((static_cast<unsigned int>(current) - 0x57u) << factor);
  4865. }
  4866. else
  4867. {
  4868. return -1;
  4869. }
  4870. }
  4871. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  4872. return codepoint;
  4873. }
  4874. /*!
  4875. @brief check if the next byte(s) are inside a given range
  4876. Adds the current byte and, for each passed range, reads a new byte and
  4877. checks if it is inside the range. If a violation was detected, set up an
  4878. error message and return false. Otherwise, return true.
  4879. @param[in] ranges list of integers; interpreted as list of pairs of
  4880. inclusive lower and upper bound, respectively
  4881. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  4882. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  4883. @return true if and only if no range violation was detected
  4884. */
  4885. bool next_byte_in_range(std::initializer_list<int> ranges)
  4886. {
  4887. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  4888. add(current);
  4889. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  4890. {
  4891. get();
  4892. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  4893. {
  4894. add(current);
  4895. }
  4896. else
  4897. {
  4898. error_message = "invalid string: ill-formed UTF-8 byte";
  4899. return false;
  4900. }
  4901. }
  4902. return true;
  4903. }
  4904. /*!
  4905. @brief scan a string literal
  4906. This function scans a string according to Sect. 7 of RFC 7159. While
  4907. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  4908. function returns successfully, token_buffer is *not* null-terminated (as it
  4909. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  4910. string.
  4911. @return token_type::value_string if string could be successfully scanned,
  4912. token_type::parse_error otherwise
  4913. @note In case of errors, variable error_message contains a textual
  4914. description.
  4915. */
  4916. token_type scan_string()
  4917. {
  4918. // reset token_buffer (ignore opening quote)
  4919. reset();
  4920. // we entered the function by reading an open quote
  4921. assert(current == '\"');
  4922. while (true)
  4923. {
  4924. // get next character
  4925. switch (get())
  4926. {
  4927. // end of file while parsing string
  4928. case std::char_traits<char>::eof():
  4929. {
  4930. error_message = "invalid string: missing closing quote";
  4931. return token_type::parse_error;
  4932. }
  4933. // closing quote
  4934. case '\"':
  4935. {
  4936. return token_type::value_string;
  4937. }
  4938. // escapes
  4939. case '\\':
  4940. {
  4941. switch (get())
  4942. {
  4943. // quotation mark
  4944. case '\"':
  4945. add('\"');
  4946. break;
  4947. // reverse solidus
  4948. case '\\':
  4949. add('\\');
  4950. break;
  4951. // solidus
  4952. case '/':
  4953. add('/');
  4954. break;
  4955. // backspace
  4956. case 'b':
  4957. add('\b');
  4958. break;
  4959. // form feed
  4960. case 'f':
  4961. add('\f');
  4962. break;
  4963. // line feed
  4964. case 'n':
  4965. add('\n');
  4966. break;
  4967. // carriage return
  4968. case 'r':
  4969. add('\r');
  4970. break;
  4971. // tab
  4972. case 't':
  4973. add('\t');
  4974. break;
  4975. // unicode escapes
  4976. case 'u':
  4977. {
  4978. const int codepoint1 = get_codepoint();
  4979. int codepoint = codepoint1; // start with codepoint1
  4980. if (JSON_UNLIKELY(codepoint1 == -1))
  4981. {
  4982. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  4983. return token_type::parse_error;
  4984. }
  4985. // check if code point is a high surrogate
  4986. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  4987. {
  4988. // expect next \uxxxx entry
  4989. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  4990. {
  4991. const int codepoint2 = get_codepoint();
  4992. if (JSON_UNLIKELY(codepoint2 == -1))
  4993. {
  4994. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  4995. return token_type::parse_error;
  4996. }
  4997. // check if codepoint2 is a low surrogate
  4998. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  4999. {
  5000. // overwrite codepoint
  5001. codepoint = static_cast<int>(
  5002. // high surrogate occupies the most significant 22 bits
  5003. (static_cast<unsigned int>(codepoint1) << 10u)
  5004. // low surrogate occupies the least significant 15 bits
  5005. + static_cast<unsigned int>(codepoint2)
  5006. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  5007. // in the result so we have to subtract with:
  5008. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  5009. - 0x35FDC00u);
  5010. }
  5011. else
  5012. {
  5013. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  5014. return token_type::parse_error;
  5015. }
  5016. }
  5017. else
  5018. {
  5019. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  5020. return token_type::parse_error;
  5021. }
  5022. }
  5023. else
  5024. {
  5025. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  5026. {
  5027. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  5028. return token_type::parse_error;
  5029. }
  5030. }
  5031. // result of the above calculation yields a proper codepoint
  5032. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  5033. // translate codepoint into bytes
  5034. if (codepoint < 0x80)
  5035. {
  5036. // 1-byte characters: 0xxxxxxx (ASCII)
  5037. add(codepoint);
  5038. }
  5039. else if (codepoint <= 0x7FF)
  5040. {
  5041. // 2-byte characters: 110xxxxx 10xxxxxx
  5042. add(static_cast<int>(0xC0u | (static_cast<unsigned int>(codepoint) >> 6u)));
  5043. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5044. }
  5045. else if (codepoint <= 0xFFFF)
  5046. {
  5047. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  5048. add(static_cast<int>(0xE0u | (static_cast<unsigned int>(codepoint) >> 12u)));
  5049. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5050. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5051. }
  5052. else
  5053. {
  5054. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  5055. add(static_cast<int>(0xF0u | (static_cast<unsigned int>(codepoint) >> 18u)));
  5056. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 12u) & 0x3Fu)));
  5057. add(static_cast<int>(0x80u | ((static_cast<unsigned int>(codepoint) >> 6u) & 0x3Fu)));
  5058. add(static_cast<int>(0x80u | (static_cast<unsigned int>(codepoint) & 0x3Fu)));
  5059. }
  5060. break;
  5061. }
  5062. // other characters after escape
  5063. default:
  5064. error_message = "invalid string: forbidden character after backslash";
  5065. return token_type::parse_error;
  5066. }
  5067. break;
  5068. }
  5069. // invalid control characters
  5070. case 0x00:
  5071. {
  5072. error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000";
  5073. return token_type::parse_error;
  5074. }
  5075. case 0x01:
  5076. {
  5077. error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001";
  5078. return token_type::parse_error;
  5079. }
  5080. case 0x02:
  5081. {
  5082. error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002";
  5083. return token_type::parse_error;
  5084. }
  5085. case 0x03:
  5086. {
  5087. error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003";
  5088. return token_type::parse_error;
  5089. }
  5090. case 0x04:
  5091. {
  5092. error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004";
  5093. return token_type::parse_error;
  5094. }
  5095. case 0x05:
  5096. {
  5097. error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005";
  5098. return token_type::parse_error;
  5099. }
  5100. case 0x06:
  5101. {
  5102. error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006";
  5103. return token_type::parse_error;
  5104. }
  5105. case 0x07:
  5106. {
  5107. error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007";
  5108. return token_type::parse_error;
  5109. }
  5110. case 0x08:
  5111. {
  5112. error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b";
  5113. return token_type::parse_error;
  5114. }
  5115. case 0x09:
  5116. {
  5117. error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t";
  5118. return token_type::parse_error;
  5119. }
  5120. case 0x0A:
  5121. {
  5122. error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n";
  5123. return token_type::parse_error;
  5124. }
  5125. case 0x0B:
  5126. {
  5127. error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B";
  5128. return token_type::parse_error;
  5129. }
  5130. case 0x0C:
  5131. {
  5132. error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f";
  5133. return token_type::parse_error;
  5134. }
  5135. case 0x0D:
  5136. {
  5137. error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r";
  5138. return token_type::parse_error;
  5139. }
  5140. case 0x0E:
  5141. {
  5142. error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E";
  5143. return token_type::parse_error;
  5144. }
  5145. case 0x0F:
  5146. {
  5147. error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F";
  5148. return token_type::parse_error;
  5149. }
  5150. case 0x10:
  5151. {
  5152. error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010";
  5153. return token_type::parse_error;
  5154. }
  5155. case 0x11:
  5156. {
  5157. error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011";
  5158. return token_type::parse_error;
  5159. }
  5160. case 0x12:
  5161. {
  5162. error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012";
  5163. return token_type::parse_error;
  5164. }
  5165. case 0x13:
  5166. {
  5167. error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013";
  5168. return token_type::parse_error;
  5169. }
  5170. case 0x14:
  5171. {
  5172. error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014";
  5173. return token_type::parse_error;
  5174. }
  5175. case 0x15:
  5176. {
  5177. error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015";
  5178. return token_type::parse_error;
  5179. }
  5180. case 0x16:
  5181. {
  5182. error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016";
  5183. return token_type::parse_error;
  5184. }
  5185. case 0x17:
  5186. {
  5187. error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017";
  5188. return token_type::parse_error;
  5189. }
  5190. case 0x18:
  5191. {
  5192. error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018";
  5193. return token_type::parse_error;
  5194. }
  5195. case 0x19:
  5196. {
  5197. error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019";
  5198. return token_type::parse_error;
  5199. }
  5200. case 0x1A:
  5201. {
  5202. error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A";
  5203. return token_type::parse_error;
  5204. }
  5205. case 0x1B:
  5206. {
  5207. error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B";
  5208. return token_type::parse_error;
  5209. }
  5210. case 0x1C:
  5211. {
  5212. error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C";
  5213. return token_type::parse_error;
  5214. }
  5215. case 0x1D:
  5216. {
  5217. error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D";
  5218. return token_type::parse_error;
  5219. }
  5220. case 0x1E:
  5221. {
  5222. error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E";
  5223. return token_type::parse_error;
  5224. }
  5225. case 0x1F:
  5226. {
  5227. error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F";
  5228. return token_type::parse_error;
  5229. }
  5230. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  5231. case 0x20:
  5232. case 0x21:
  5233. case 0x23:
  5234. case 0x24:
  5235. case 0x25:
  5236. case 0x26:
  5237. case 0x27:
  5238. case 0x28:
  5239. case 0x29:
  5240. case 0x2A:
  5241. case 0x2B:
  5242. case 0x2C:
  5243. case 0x2D:
  5244. case 0x2E:
  5245. case 0x2F:
  5246. case 0x30:
  5247. case 0x31:
  5248. case 0x32:
  5249. case 0x33:
  5250. case 0x34:
  5251. case 0x35:
  5252. case 0x36:
  5253. case 0x37:
  5254. case 0x38:
  5255. case 0x39:
  5256. case 0x3A:
  5257. case 0x3B:
  5258. case 0x3C:
  5259. case 0x3D:
  5260. case 0x3E:
  5261. case 0x3F:
  5262. case 0x40:
  5263. case 0x41:
  5264. case 0x42:
  5265. case 0x43:
  5266. case 0x44:
  5267. case 0x45:
  5268. case 0x46:
  5269. case 0x47:
  5270. case 0x48:
  5271. case 0x49:
  5272. case 0x4A:
  5273. case 0x4B:
  5274. case 0x4C:
  5275. case 0x4D:
  5276. case 0x4E:
  5277. case 0x4F:
  5278. case 0x50:
  5279. case 0x51:
  5280. case 0x52:
  5281. case 0x53:
  5282. case 0x54:
  5283. case 0x55:
  5284. case 0x56:
  5285. case 0x57:
  5286. case 0x58:
  5287. case 0x59:
  5288. case 0x5A:
  5289. case 0x5B:
  5290. case 0x5D:
  5291. case 0x5E:
  5292. case 0x5F:
  5293. case 0x60:
  5294. case 0x61:
  5295. case 0x62:
  5296. case 0x63:
  5297. case 0x64:
  5298. case 0x65:
  5299. case 0x66:
  5300. case 0x67:
  5301. case 0x68:
  5302. case 0x69:
  5303. case 0x6A:
  5304. case 0x6B:
  5305. case 0x6C:
  5306. case 0x6D:
  5307. case 0x6E:
  5308. case 0x6F:
  5309. case 0x70:
  5310. case 0x71:
  5311. case 0x72:
  5312. case 0x73:
  5313. case 0x74:
  5314. case 0x75:
  5315. case 0x76:
  5316. case 0x77:
  5317. case 0x78:
  5318. case 0x79:
  5319. case 0x7A:
  5320. case 0x7B:
  5321. case 0x7C:
  5322. case 0x7D:
  5323. case 0x7E:
  5324. case 0x7F:
  5325. {
  5326. add(current);
  5327. break;
  5328. }
  5329. // U+0080..U+07FF: bytes C2..DF 80..BF
  5330. case 0xC2:
  5331. case 0xC3:
  5332. case 0xC4:
  5333. case 0xC5:
  5334. case 0xC6:
  5335. case 0xC7:
  5336. case 0xC8:
  5337. case 0xC9:
  5338. case 0xCA:
  5339. case 0xCB:
  5340. case 0xCC:
  5341. case 0xCD:
  5342. case 0xCE:
  5343. case 0xCF:
  5344. case 0xD0:
  5345. case 0xD1:
  5346. case 0xD2:
  5347. case 0xD3:
  5348. case 0xD4:
  5349. case 0xD5:
  5350. case 0xD6:
  5351. case 0xD7:
  5352. case 0xD8:
  5353. case 0xD9:
  5354. case 0xDA:
  5355. case 0xDB:
  5356. case 0xDC:
  5357. case 0xDD:
  5358. case 0xDE:
  5359. case 0xDF:
  5360. {
  5361. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  5362. {
  5363. return token_type::parse_error;
  5364. }
  5365. break;
  5366. }
  5367. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  5368. case 0xE0:
  5369. {
  5370. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  5371. {
  5372. return token_type::parse_error;
  5373. }
  5374. break;
  5375. }
  5376. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  5377. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  5378. case 0xE1:
  5379. case 0xE2:
  5380. case 0xE3:
  5381. case 0xE4:
  5382. case 0xE5:
  5383. case 0xE6:
  5384. case 0xE7:
  5385. case 0xE8:
  5386. case 0xE9:
  5387. case 0xEA:
  5388. case 0xEB:
  5389. case 0xEC:
  5390. case 0xEE:
  5391. case 0xEF:
  5392. {
  5393. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  5394. {
  5395. return token_type::parse_error;
  5396. }
  5397. break;
  5398. }
  5399. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  5400. case 0xED:
  5401. {
  5402. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  5403. {
  5404. return token_type::parse_error;
  5405. }
  5406. break;
  5407. }
  5408. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  5409. case 0xF0:
  5410. {
  5411. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5412. {
  5413. return token_type::parse_error;
  5414. }
  5415. break;
  5416. }
  5417. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  5418. case 0xF1:
  5419. case 0xF2:
  5420. case 0xF3:
  5421. {
  5422. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  5423. {
  5424. return token_type::parse_error;
  5425. }
  5426. break;
  5427. }
  5428. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  5429. case 0xF4:
  5430. {
  5431. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  5432. {
  5433. return token_type::parse_error;
  5434. }
  5435. break;
  5436. }
  5437. // remaining bytes (80..C1 and F5..FF) are ill-formed
  5438. default:
  5439. {
  5440. error_message = "invalid string: ill-formed UTF-8 byte";
  5441. return token_type::parse_error;
  5442. }
  5443. }
  5444. }
  5445. }
  5446. static void strtof(float& f, const char* str, char** endptr) noexcept
  5447. {
  5448. f = std::strtof(str, endptr);
  5449. }
  5450. static void strtof(double& f, const char* str, char** endptr) noexcept
  5451. {
  5452. f = std::strtod(str, endptr);
  5453. }
  5454. static void strtof(long double& f, const char* str, char** endptr) noexcept
  5455. {
  5456. f = std::strtold(str, endptr);
  5457. }
  5458. /*!
  5459. @brief scan a number literal
  5460. This function scans a string according to Sect. 6 of RFC 7159.
  5461. The function is realized with a deterministic finite state machine derived
  5462. from the grammar described in RFC 7159. Starting in state "init", the
  5463. input is read and used to determined the next state. Only state "done"
  5464. accepts the number. State "error" is a trap state to model errors. In the
  5465. table below, "anything" means any character but the ones listed before.
  5466. state | 0 | 1-9 | e E | + | - | . | anything
  5467. ---------|----------|----------|----------|---------|---------|----------|-----------
  5468. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  5469. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  5470. zero | done | done | exponent | done | done | decimal1 | done
  5471. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  5472. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  5473. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  5474. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  5475. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  5476. any2 | any2 | any2 | done | done | done | done | done
  5477. The state machine is realized with one label per state (prefixed with
  5478. "scan_number_") and `goto` statements between them. The state machine
  5479. contains cycles, but any cycle can be left when EOF is read. Therefore,
  5480. the function is guaranteed to terminate.
  5481. During scanning, the read bytes are stored in token_buffer. This string is
  5482. then converted to a signed integer, an unsigned integer, or a
  5483. floating-point number.
  5484. @return token_type::value_unsigned, token_type::value_integer, or
  5485. token_type::value_float if number could be successfully scanned,
  5486. token_type::parse_error otherwise
  5487. @note The scanner is independent of the current locale. Internally, the
  5488. locale's decimal point is used instead of `.` to work with the
  5489. locale-dependent converters.
  5490. */
  5491. token_type scan_number() // lgtm [cpp/use-of-goto]
  5492. {
  5493. // reset token_buffer to store the number's bytes
  5494. reset();
  5495. // the type of the parsed number; initially set to unsigned; will be
  5496. // changed if minus sign, decimal point or exponent is read
  5497. token_type number_type = token_type::value_unsigned;
  5498. // state (init): we just found out we need to scan a number
  5499. switch (current)
  5500. {
  5501. case '-':
  5502. {
  5503. add(current);
  5504. goto scan_number_minus;
  5505. }
  5506. case '0':
  5507. {
  5508. add(current);
  5509. goto scan_number_zero;
  5510. }
  5511. case '1':
  5512. case '2':
  5513. case '3':
  5514. case '4':
  5515. case '5':
  5516. case '6':
  5517. case '7':
  5518. case '8':
  5519. case '9':
  5520. {
  5521. add(current);
  5522. goto scan_number_any1;
  5523. }
  5524. // all other characters are rejected outside scan_number()
  5525. default: // LCOV_EXCL_LINE
  5526. assert(false); // LCOV_EXCL_LINE
  5527. }
  5528. scan_number_minus:
  5529. // state: we just parsed a leading minus sign
  5530. number_type = token_type::value_integer;
  5531. switch (get())
  5532. {
  5533. case '0':
  5534. {
  5535. add(current);
  5536. goto scan_number_zero;
  5537. }
  5538. case '1':
  5539. case '2':
  5540. case '3':
  5541. case '4':
  5542. case '5':
  5543. case '6':
  5544. case '7':
  5545. case '8':
  5546. case '9':
  5547. {
  5548. add(current);
  5549. goto scan_number_any1;
  5550. }
  5551. default:
  5552. {
  5553. error_message = "invalid number; expected digit after '-'";
  5554. return token_type::parse_error;
  5555. }
  5556. }
  5557. scan_number_zero:
  5558. // state: we just parse a zero (maybe with a leading minus sign)
  5559. switch (get())
  5560. {
  5561. case '.':
  5562. {
  5563. add(decimal_point_char);
  5564. goto scan_number_decimal1;
  5565. }
  5566. case 'e':
  5567. case 'E':
  5568. {
  5569. add(current);
  5570. goto scan_number_exponent;
  5571. }
  5572. default:
  5573. goto scan_number_done;
  5574. }
  5575. scan_number_any1:
  5576. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  5577. switch (get())
  5578. {
  5579. case '0':
  5580. case '1':
  5581. case '2':
  5582. case '3':
  5583. case '4':
  5584. case '5':
  5585. case '6':
  5586. case '7':
  5587. case '8':
  5588. case '9':
  5589. {
  5590. add(current);
  5591. goto scan_number_any1;
  5592. }
  5593. case '.':
  5594. {
  5595. add(decimal_point_char);
  5596. goto scan_number_decimal1;
  5597. }
  5598. case 'e':
  5599. case 'E':
  5600. {
  5601. add(current);
  5602. goto scan_number_exponent;
  5603. }
  5604. default:
  5605. goto scan_number_done;
  5606. }
  5607. scan_number_decimal1:
  5608. // state: we just parsed a decimal point
  5609. number_type = token_type::value_float;
  5610. switch (get())
  5611. {
  5612. case '0':
  5613. case '1':
  5614. case '2':
  5615. case '3':
  5616. case '4':
  5617. case '5':
  5618. case '6':
  5619. case '7':
  5620. case '8':
  5621. case '9':
  5622. {
  5623. add(current);
  5624. goto scan_number_decimal2;
  5625. }
  5626. default:
  5627. {
  5628. error_message = "invalid number; expected digit after '.'";
  5629. return token_type::parse_error;
  5630. }
  5631. }
  5632. scan_number_decimal2:
  5633. // we just parsed at least one number after a decimal point
  5634. switch (get())
  5635. {
  5636. case '0':
  5637. case '1':
  5638. case '2':
  5639. case '3':
  5640. case '4':
  5641. case '5':
  5642. case '6':
  5643. case '7':
  5644. case '8':
  5645. case '9':
  5646. {
  5647. add(current);
  5648. goto scan_number_decimal2;
  5649. }
  5650. case 'e':
  5651. case 'E':
  5652. {
  5653. add(current);
  5654. goto scan_number_exponent;
  5655. }
  5656. default:
  5657. goto scan_number_done;
  5658. }
  5659. scan_number_exponent:
  5660. // we just parsed an exponent
  5661. number_type = token_type::value_float;
  5662. switch (get())
  5663. {
  5664. case '+':
  5665. case '-':
  5666. {
  5667. add(current);
  5668. goto scan_number_sign;
  5669. }
  5670. case '0':
  5671. case '1':
  5672. case '2':
  5673. case '3':
  5674. case '4':
  5675. case '5':
  5676. case '6':
  5677. case '7':
  5678. case '8':
  5679. case '9':
  5680. {
  5681. add(current);
  5682. goto scan_number_any2;
  5683. }
  5684. default:
  5685. {
  5686. error_message =
  5687. "invalid number; expected '+', '-', or digit after exponent";
  5688. return token_type::parse_error;
  5689. }
  5690. }
  5691. scan_number_sign:
  5692. // we just parsed an exponent sign
  5693. switch (get())
  5694. {
  5695. case '0':
  5696. case '1':
  5697. case '2':
  5698. case '3':
  5699. case '4':
  5700. case '5':
  5701. case '6':
  5702. case '7':
  5703. case '8':
  5704. case '9':
  5705. {
  5706. add(current);
  5707. goto scan_number_any2;
  5708. }
  5709. default:
  5710. {
  5711. error_message = "invalid number; expected digit after exponent sign";
  5712. return token_type::parse_error;
  5713. }
  5714. }
  5715. scan_number_any2:
  5716. // we just parsed a number after the exponent or exponent sign
  5717. switch (get())
  5718. {
  5719. case '0':
  5720. case '1':
  5721. case '2':
  5722. case '3':
  5723. case '4':
  5724. case '5':
  5725. case '6':
  5726. case '7':
  5727. case '8':
  5728. case '9':
  5729. {
  5730. add(current);
  5731. goto scan_number_any2;
  5732. }
  5733. default:
  5734. goto scan_number_done;
  5735. }
  5736. scan_number_done:
  5737. // unget the character after the number (we only read it to know that
  5738. // we are done scanning a number)
  5739. unget();
  5740. char* endptr = nullptr;
  5741. errno = 0;
  5742. // try to parse integers first and fall back to floats
  5743. if (number_type == token_type::value_unsigned)
  5744. {
  5745. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  5746. // we checked the number format before
  5747. assert(endptr == token_buffer.data() + token_buffer.size());
  5748. if (errno == 0)
  5749. {
  5750. value_unsigned = static_cast<number_unsigned_t>(x);
  5751. if (value_unsigned == x)
  5752. {
  5753. return token_type::value_unsigned;
  5754. }
  5755. }
  5756. }
  5757. else if (number_type == token_type::value_integer)
  5758. {
  5759. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  5760. // we checked the number format before
  5761. assert(endptr == token_buffer.data() + token_buffer.size());
  5762. if (errno == 0)
  5763. {
  5764. value_integer = static_cast<number_integer_t>(x);
  5765. if (value_integer == x)
  5766. {
  5767. return token_type::value_integer;
  5768. }
  5769. }
  5770. }
  5771. // this code is reached if we parse a floating-point number or if an
  5772. // integer conversion above failed
  5773. strtof(value_float, token_buffer.data(), &endptr);
  5774. // we checked the number format before
  5775. assert(endptr == token_buffer.data() + token_buffer.size());
  5776. return token_type::value_float;
  5777. }
  5778. /*!
  5779. @param[in] literal_text the literal text to expect
  5780. @param[in] length the length of the passed literal text
  5781. @param[in] return_type the token type to return on success
  5782. */
  5783. token_type scan_literal(const char* literal_text, const std::size_t length,
  5784. token_type return_type)
  5785. {
  5786. assert(current == literal_text[0]);
  5787. for (std::size_t i = 1; i < length; ++i)
  5788. {
  5789. if (JSON_UNLIKELY(get() != literal_text[i]))
  5790. {
  5791. error_message = "invalid literal";
  5792. return token_type::parse_error;
  5793. }
  5794. }
  5795. return return_type;
  5796. }
  5797. /////////////////////
  5798. // input management
  5799. /////////////////////
  5800. /// reset token_buffer; current character is beginning of token
  5801. void reset() noexcept
  5802. {
  5803. token_buffer.clear();
  5804. token_string.clear();
  5805. token_string.push_back(std::char_traits<char>::to_char_type(current));
  5806. }
  5807. /*
  5808. @brief get next character from the input
  5809. This function provides the interface to the used input adapter. It does
  5810. not throw in case the input reached EOF, but returns a
  5811. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  5812. for use in error messages.
  5813. @return character read from the input
  5814. */
  5815. std::char_traits<char>::int_type get()
  5816. {
  5817. ++position.chars_read_total;
  5818. ++position.chars_read_current_line;
  5819. if (next_unget)
  5820. {
  5821. // just reset the next_unget variable and work with current
  5822. next_unget = false;
  5823. }
  5824. else
  5825. {
  5826. current = ia->get_character();
  5827. }
  5828. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  5829. {
  5830. token_string.push_back(std::char_traits<char>::to_char_type(current));
  5831. }
  5832. if (current == '\n')
  5833. {
  5834. ++position.lines_read;
  5835. position.chars_read_current_line = 0;
  5836. }
  5837. return current;
  5838. }
  5839. /*!
  5840. @brief unget current character (read it again on next get)
  5841. We implement unget by setting variable next_unget to true. The input is not
  5842. changed - we just simulate ungetting by modifying chars_read_total,
  5843. chars_read_current_line, and token_string. The next call to get() will
  5844. behave as if the unget character is read again.
  5845. */
  5846. void unget()
  5847. {
  5848. next_unget = true;
  5849. --position.chars_read_total;
  5850. // in case we "unget" a newline, we have to also decrement the lines_read
  5851. if (position.chars_read_current_line == 0)
  5852. {
  5853. if (position.lines_read > 0)
  5854. {
  5855. --position.lines_read;
  5856. }
  5857. }
  5858. else
  5859. {
  5860. --position.chars_read_current_line;
  5861. }
  5862. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  5863. {
  5864. assert(not token_string.empty());
  5865. token_string.pop_back();
  5866. }
  5867. }
  5868. /// add a character to token_buffer
  5869. void add(int c)
  5870. {
  5871. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  5872. }
  5873. public:
  5874. /////////////////////
  5875. // value getters
  5876. /////////////////////
  5877. /// return integer value
  5878. constexpr number_integer_t get_number_integer() const noexcept
  5879. {
  5880. return value_integer;
  5881. }
  5882. /// return unsigned integer value
  5883. constexpr number_unsigned_t get_number_unsigned() const noexcept
  5884. {
  5885. return value_unsigned;
  5886. }
  5887. /// return floating-point value
  5888. constexpr number_float_t get_number_float() const noexcept
  5889. {
  5890. return value_float;
  5891. }
  5892. /// return current string value (implicitly resets the token; useful only once)
  5893. string_t& get_string()
  5894. {
  5895. return token_buffer;
  5896. }
  5897. /////////////////////
  5898. // diagnostics
  5899. /////////////////////
  5900. /// return position of last read token
  5901. constexpr position_t get_position() const noexcept
  5902. {
  5903. return position;
  5904. }
  5905. /// return the last read token (for errors only). Will never contain EOF
  5906. /// (an arbitrary value that is not a valid char value, often -1), because
  5907. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  5908. std::string get_token_string() const
  5909. {
  5910. // escape control characters
  5911. std::string result;
  5912. for (const auto c : token_string)
  5913. {
  5914. if ('\x00' <= c and c <= '\x1F')
  5915. {
  5916. // escape control characters
  5917. std::array<char, 9> cs{{}};
  5918. (std::snprintf)(cs.data(), cs.size(), "<U+%.4X>", static_cast<unsigned char>(c));
  5919. result += cs.data();
  5920. }
  5921. else
  5922. {
  5923. // add character as is
  5924. result.push_back(c);
  5925. }
  5926. }
  5927. return result;
  5928. }
  5929. /// return syntax error message
  5930. constexpr const char* get_error_message() const noexcept
  5931. {
  5932. return error_message;
  5933. }
  5934. /////////////////////
  5935. // actual scanner
  5936. /////////////////////
  5937. /*!
  5938. @brief skip the UTF-8 byte order mark
  5939. @return true iff there is no BOM or the correct BOM has been skipped
  5940. */
  5941. bool skip_bom()
  5942. {
  5943. if (get() == 0xEF)
  5944. {
  5945. // check if we completely parse the BOM
  5946. return get() == 0xBB and get() == 0xBF;
  5947. }
  5948. // the first character is not the beginning of the BOM; unget it to
  5949. // process is later
  5950. unget();
  5951. return true;
  5952. }
  5953. token_type scan()
  5954. {
  5955. // initially, skip the BOM
  5956. if (position.chars_read_total == 0 and not skip_bom())
  5957. {
  5958. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  5959. return token_type::parse_error;
  5960. }
  5961. // read next character and ignore whitespace
  5962. do
  5963. {
  5964. get();
  5965. }
  5966. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  5967. switch (current)
  5968. {
  5969. // structural characters
  5970. case '[':
  5971. return token_type::begin_array;
  5972. case ']':
  5973. return token_type::end_array;
  5974. case '{':
  5975. return token_type::begin_object;
  5976. case '}':
  5977. return token_type::end_object;
  5978. case ':':
  5979. return token_type::name_separator;
  5980. case ',':
  5981. return token_type::value_separator;
  5982. // literals
  5983. case 't':
  5984. return scan_literal("true", 4, token_type::literal_true);
  5985. case 'f':
  5986. return scan_literal("false", 5, token_type::literal_false);
  5987. case 'n':
  5988. return scan_literal("null", 4, token_type::literal_null);
  5989. // string
  5990. case '\"':
  5991. return scan_string();
  5992. // number
  5993. case '-':
  5994. case '0':
  5995. case '1':
  5996. case '2':
  5997. case '3':
  5998. case '4':
  5999. case '5':
  6000. case '6':
  6001. case '7':
  6002. case '8':
  6003. case '9':
  6004. return scan_number();
  6005. // end of input (the null byte is needed when parsing from
  6006. // string literals)
  6007. case '\0':
  6008. case std::char_traits<char>::eof():
  6009. return token_type::end_of_input;
  6010. // error
  6011. default:
  6012. error_message = "invalid literal";
  6013. return token_type::parse_error;
  6014. }
  6015. }
  6016. private:
  6017. /// input adapter
  6018. detail::input_adapter_t ia = nullptr;
  6019. /// the current character
  6020. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  6021. /// whether the next get() call should just return current
  6022. bool next_unget = false;
  6023. /// the start position of the current token
  6024. position_t position {};
  6025. /// raw input token string (for error messages)
  6026. std::vector<char> token_string {};
  6027. /// buffer for variable-length tokens (numbers, strings)
  6028. string_t token_buffer {};
  6029. /// a description of occurred lexer errors
  6030. const char* error_message = "";
  6031. // number values
  6032. number_integer_t value_integer = 0;
  6033. number_unsigned_t value_unsigned = 0;
  6034. number_float_t value_float = 0;
  6035. /// the decimal point
  6036. const char decimal_point_char = '.';
  6037. };
  6038. } // namespace detail
  6039. } // namespace nlohmann
  6040. // #include <nlohmann/detail/input/parser.hpp>
  6041. #include <cassert> // assert
  6042. #include <cmath> // isfinite
  6043. #include <cstdint> // uint8_t
  6044. #include <functional> // function
  6045. #include <string> // string
  6046. #include <utility> // move
  6047. #include <vector> // vector
  6048. // #include <nlohmann/detail/exceptions.hpp>
  6049. // #include <nlohmann/detail/input/input_adapters.hpp>
  6050. // #include <nlohmann/detail/input/json_sax.hpp>
  6051. // #include <nlohmann/detail/input/lexer.hpp>
  6052. // #include <nlohmann/detail/macro_scope.hpp>
  6053. // #include <nlohmann/detail/meta/is_sax.hpp>
  6054. // #include <nlohmann/detail/value_t.hpp>
  6055. namespace nlohmann
  6056. {
  6057. namespace detail
  6058. {
  6059. ////////////
  6060. // parser //
  6061. ////////////
  6062. /*!
  6063. @brief syntax analysis
  6064. This class implements a recursive decent parser.
  6065. */
  6066. template<typename BasicJsonType>
  6067. class parser
  6068. {
  6069. using number_integer_t = typename BasicJsonType::number_integer_t;
  6070. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  6071. using number_float_t = typename BasicJsonType::number_float_t;
  6072. using string_t = typename BasicJsonType::string_t;
  6073. using lexer_t = lexer<BasicJsonType>;
  6074. using token_type = typename lexer_t::token_type;
  6075. public:
  6076. enum class parse_event_t : uint8_t
  6077. {
  6078. /// the parser read `{` and started to process a JSON object
  6079. object_start,
  6080. /// the parser read `}` and finished processing a JSON object
  6081. object_end,
  6082. /// the parser read `[` and started to process a JSON array
  6083. array_start,
  6084. /// the parser read `]` and finished processing a JSON array
  6085. array_end,
  6086. /// the parser read a key of a value in an object
  6087. key,
  6088. /// the parser finished reading a JSON value
  6089. value
  6090. };
  6091. using parser_callback_t =
  6092. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  6093. /// a parser reading from an input adapter
  6094. explicit parser(detail::input_adapter_t&& adapter,
  6095. const parser_callback_t cb = nullptr,
  6096. const bool allow_exceptions_ = true)
  6097. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  6098. {
  6099. // read first token
  6100. get_token();
  6101. }
  6102. /*!
  6103. @brief public parser interface
  6104. @param[in] strict whether to expect the last token to be EOF
  6105. @param[in,out] result parsed JSON value
  6106. @throw parse_error.101 in case of an unexpected token
  6107. @throw parse_error.102 if to_unicode fails or surrogate error
  6108. @throw parse_error.103 if to_unicode fails
  6109. */
  6110. void parse(const bool strict, BasicJsonType& result)
  6111. {
  6112. if (callback)
  6113. {
  6114. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  6115. sax_parse_internal(&sdp);
  6116. result.assert_invariant();
  6117. // in strict mode, input must be completely read
  6118. if (strict and (get_token() != token_type::end_of_input))
  6119. {
  6120. sdp.parse_error(m_lexer.get_position(),
  6121. m_lexer.get_token_string(),
  6122. parse_error::create(101, m_lexer.get_position(),
  6123. exception_message(token_type::end_of_input, "value")));
  6124. }
  6125. // in case of an error, return discarded value
  6126. if (sdp.is_errored())
  6127. {
  6128. result = value_t::discarded;
  6129. return;
  6130. }
  6131. // set top-level value to null if it was discarded by the callback
  6132. // function
  6133. if (result.is_discarded())
  6134. {
  6135. result = nullptr;
  6136. }
  6137. }
  6138. else
  6139. {
  6140. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  6141. sax_parse_internal(&sdp);
  6142. result.assert_invariant();
  6143. // in strict mode, input must be completely read
  6144. if (strict and (get_token() != token_type::end_of_input))
  6145. {
  6146. sdp.parse_error(m_lexer.get_position(),
  6147. m_lexer.get_token_string(),
  6148. parse_error::create(101, m_lexer.get_position(),
  6149. exception_message(token_type::end_of_input, "value")));
  6150. }
  6151. // in case of an error, return discarded value
  6152. if (sdp.is_errored())
  6153. {
  6154. result = value_t::discarded;
  6155. return;
  6156. }
  6157. }
  6158. }
  6159. /*!
  6160. @brief public accept interface
  6161. @param[in] strict whether to expect the last token to be EOF
  6162. @return whether the input is a proper JSON text
  6163. */
  6164. bool accept(const bool strict = true)
  6165. {
  6166. json_sax_acceptor<BasicJsonType> sax_acceptor;
  6167. return sax_parse(&sax_acceptor, strict);
  6168. }
  6169. template <typename SAX>
  6170. bool sax_parse(SAX* sax, const bool strict = true)
  6171. {
  6172. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  6173. const bool result = sax_parse_internal(sax);
  6174. // strict mode: next byte must be EOF
  6175. if (result and strict and (get_token() != token_type::end_of_input))
  6176. {
  6177. return sax->parse_error(m_lexer.get_position(),
  6178. m_lexer.get_token_string(),
  6179. parse_error::create(101, m_lexer.get_position(),
  6180. exception_message(token_type::end_of_input, "value")));
  6181. }
  6182. return result;
  6183. }
  6184. private:
  6185. template <typename SAX>
  6186. bool sax_parse_internal(SAX* sax)
  6187. {
  6188. // stack to remember the hierarchy of structured values we are parsing
  6189. // true = array; false = object
  6190. std::vector<bool> states;
  6191. // value to avoid a goto (see comment where set to true)
  6192. bool skip_to_state_evaluation = false;
  6193. while (true)
  6194. {
  6195. if (not skip_to_state_evaluation)
  6196. {
  6197. // invariant: get_token() was called before each iteration
  6198. switch (last_token)
  6199. {
  6200. case token_type::begin_object:
  6201. {
  6202. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6203. {
  6204. return false;
  6205. }
  6206. // closing } -> we are done
  6207. if (get_token() == token_type::end_object)
  6208. {
  6209. if (JSON_UNLIKELY(not sax->end_object()))
  6210. {
  6211. return false;
  6212. }
  6213. break;
  6214. }
  6215. // parse key
  6216. if (JSON_UNLIKELY(last_token != token_type::value_string))
  6217. {
  6218. return sax->parse_error(m_lexer.get_position(),
  6219. m_lexer.get_token_string(),
  6220. parse_error::create(101, m_lexer.get_position(),
  6221. exception_message(token_type::value_string, "object key")));
  6222. }
  6223. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  6224. {
  6225. return false;
  6226. }
  6227. // parse separator (:)
  6228. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  6229. {
  6230. return sax->parse_error(m_lexer.get_position(),
  6231. m_lexer.get_token_string(),
  6232. parse_error::create(101, m_lexer.get_position(),
  6233. exception_message(token_type::name_separator, "object separator")));
  6234. }
  6235. // remember we are now inside an object
  6236. states.push_back(false);
  6237. // parse values
  6238. get_token();
  6239. continue;
  6240. }
  6241. case token_type::begin_array:
  6242. {
  6243. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6244. {
  6245. return false;
  6246. }
  6247. // closing ] -> we are done
  6248. if (get_token() == token_type::end_array)
  6249. {
  6250. if (JSON_UNLIKELY(not sax->end_array()))
  6251. {
  6252. return false;
  6253. }
  6254. break;
  6255. }
  6256. // remember we are now inside an array
  6257. states.push_back(true);
  6258. // parse values (no need to call get_token)
  6259. continue;
  6260. }
  6261. case token_type::value_float:
  6262. {
  6263. const auto res = m_lexer.get_number_float();
  6264. if (JSON_UNLIKELY(not std::isfinite(res)))
  6265. {
  6266. return sax->parse_error(m_lexer.get_position(),
  6267. m_lexer.get_token_string(),
  6268. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  6269. }
  6270. if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  6271. {
  6272. return false;
  6273. }
  6274. break;
  6275. }
  6276. case token_type::literal_false:
  6277. {
  6278. if (JSON_UNLIKELY(not sax->boolean(false)))
  6279. {
  6280. return false;
  6281. }
  6282. break;
  6283. }
  6284. case token_type::literal_null:
  6285. {
  6286. if (JSON_UNLIKELY(not sax->null()))
  6287. {
  6288. return false;
  6289. }
  6290. break;
  6291. }
  6292. case token_type::literal_true:
  6293. {
  6294. if (JSON_UNLIKELY(not sax->boolean(true)))
  6295. {
  6296. return false;
  6297. }
  6298. break;
  6299. }
  6300. case token_type::value_integer:
  6301. {
  6302. if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  6303. {
  6304. return false;
  6305. }
  6306. break;
  6307. }
  6308. case token_type::value_string:
  6309. {
  6310. if (JSON_UNLIKELY(not sax->string(m_lexer.get_string())))
  6311. {
  6312. return false;
  6313. }
  6314. break;
  6315. }
  6316. case token_type::value_unsigned:
  6317. {
  6318. if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  6319. {
  6320. return false;
  6321. }
  6322. break;
  6323. }
  6324. case token_type::parse_error:
  6325. {
  6326. // using "uninitialized" to avoid "expected" message
  6327. return sax->parse_error(m_lexer.get_position(),
  6328. m_lexer.get_token_string(),
  6329. parse_error::create(101, m_lexer.get_position(),
  6330. exception_message(token_type::uninitialized, "value")));
  6331. }
  6332. default: // the last token was unexpected
  6333. {
  6334. return sax->parse_error(m_lexer.get_position(),
  6335. m_lexer.get_token_string(),
  6336. parse_error::create(101, m_lexer.get_position(),
  6337. exception_message(token_type::literal_or_value, "value")));
  6338. }
  6339. }
  6340. }
  6341. else
  6342. {
  6343. skip_to_state_evaluation = false;
  6344. }
  6345. // we reached this line after we successfully parsed a value
  6346. if (states.empty())
  6347. {
  6348. // empty stack: we reached the end of the hierarchy: done
  6349. return true;
  6350. }
  6351. if (states.back()) // array
  6352. {
  6353. // comma -> next value
  6354. if (get_token() == token_type::value_separator)
  6355. {
  6356. // parse a new value
  6357. get_token();
  6358. continue;
  6359. }
  6360. // closing ]
  6361. if (JSON_LIKELY(last_token == token_type::end_array))
  6362. {
  6363. if (JSON_UNLIKELY(not sax->end_array()))
  6364. {
  6365. return false;
  6366. }
  6367. // We are done with this array. Before we can parse a
  6368. // new value, we need to evaluate the new state first.
  6369. // By setting skip_to_state_evaluation to false, we
  6370. // are effectively jumping to the beginning of this if.
  6371. assert(not states.empty());
  6372. states.pop_back();
  6373. skip_to_state_evaluation = true;
  6374. continue;
  6375. }
  6376. return sax->parse_error(m_lexer.get_position(),
  6377. m_lexer.get_token_string(),
  6378. parse_error::create(101, m_lexer.get_position(),
  6379. exception_message(token_type::end_array, "array")));
  6380. }
  6381. else // object
  6382. {
  6383. // comma -> next value
  6384. if (get_token() == token_type::value_separator)
  6385. {
  6386. // parse key
  6387. if (JSON_UNLIKELY(get_token() != token_type::value_string))
  6388. {
  6389. return sax->parse_error(m_lexer.get_position(),
  6390. m_lexer.get_token_string(),
  6391. parse_error::create(101, m_lexer.get_position(),
  6392. exception_message(token_type::value_string, "object key")));
  6393. }
  6394. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  6395. {
  6396. return false;
  6397. }
  6398. // parse separator (:)
  6399. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  6400. {
  6401. return sax->parse_error(m_lexer.get_position(),
  6402. m_lexer.get_token_string(),
  6403. parse_error::create(101, m_lexer.get_position(),
  6404. exception_message(token_type::name_separator, "object separator")));
  6405. }
  6406. // parse values
  6407. get_token();
  6408. continue;
  6409. }
  6410. // closing }
  6411. if (JSON_LIKELY(last_token == token_type::end_object))
  6412. {
  6413. if (JSON_UNLIKELY(not sax->end_object()))
  6414. {
  6415. return false;
  6416. }
  6417. // We are done with this object. Before we can parse a
  6418. // new value, we need to evaluate the new state first.
  6419. // By setting skip_to_state_evaluation to false, we
  6420. // are effectively jumping to the beginning of this if.
  6421. assert(not states.empty());
  6422. states.pop_back();
  6423. skip_to_state_evaluation = true;
  6424. continue;
  6425. }
  6426. return sax->parse_error(m_lexer.get_position(),
  6427. m_lexer.get_token_string(),
  6428. parse_error::create(101, m_lexer.get_position(),
  6429. exception_message(token_type::end_object, "object")));
  6430. }
  6431. }
  6432. }
  6433. /// get next token from lexer
  6434. token_type get_token()
  6435. {
  6436. return last_token = m_lexer.scan();
  6437. }
  6438. std::string exception_message(const token_type expected, const std::string& context)
  6439. {
  6440. std::string error_msg = "syntax error ";
  6441. if (not context.empty())
  6442. {
  6443. error_msg += "while parsing " + context + " ";
  6444. }
  6445. error_msg += "- ";
  6446. if (last_token == token_type::parse_error)
  6447. {
  6448. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  6449. m_lexer.get_token_string() + "'";
  6450. }
  6451. else
  6452. {
  6453. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  6454. }
  6455. if (expected != token_type::uninitialized)
  6456. {
  6457. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  6458. }
  6459. return error_msg;
  6460. }
  6461. private:
  6462. /// callback function
  6463. const parser_callback_t callback = nullptr;
  6464. /// the type of the last read token
  6465. token_type last_token = token_type::uninitialized;
  6466. /// the lexer
  6467. lexer_t m_lexer;
  6468. /// whether to throw exceptions in case of errors
  6469. const bool allow_exceptions = true;
  6470. };
  6471. } // namespace detail
  6472. } // namespace nlohmann
  6473. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  6474. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  6475. #include <cstddef> // ptrdiff_t
  6476. #include <limits> // numeric_limits
  6477. namespace nlohmann
  6478. {
  6479. namespace detail
  6480. {
  6481. /*
  6482. @brief an iterator for primitive JSON types
  6483. This class models an iterator for primitive JSON types (boolean, number,
  6484. string). It's only purpose is to allow the iterator/const_iterator classes
  6485. to "iterate" over primitive values. Internally, the iterator is modeled by
  6486. a `difference_type` variable. Value begin_value (`0`) models the begin,
  6487. end_value (`1`) models past the end.
  6488. */
  6489. class primitive_iterator_t
  6490. {
  6491. private:
  6492. using difference_type = std::ptrdiff_t;
  6493. static constexpr difference_type begin_value = 0;
  6494. static constexpr difference_type end_value = begin_value + 1;
  6495. /// iterator as signed integer type
  6496. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  6497. public:
  6498. constexpr difference_type get_value() const noexcept
  6499. {
  6500. return m_it;
  6501. }
  6502. /// set iterator to a defined beginning
  6503. void set_begin() noexcept
  6504. {
  6505. m_it = begin_value;
  6506. }
  6507. /// set iterator to a defined past the end
  6508. void set_end() noexcept
  6509. {
  6510. m_it = end_value;
  6511. }
  6512. /// return whether the iterator can be dereferenced
  6513. constexpr bool is_begin() const noexcept
  6514. {
  6515. return m_it == begin_value;
  6516. }
  6517. /// return whether the iterator is at end
  6518. constexpr bool is_end() const noexcept
  6519. {
  6520. return m_it == end_value;
  6521. }
  6522. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6523. {
  6524. return lhs.m_it == rhs.m_it;
  6525. }
  6526. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6527. {
  6528. return lhs.m_it < rhs.m_it;
  6529. }
  6530. primitive_iterator_t operator+(difference_type n) noexcept
  6531. {
  6532. auto result = *this;
  6533. result += n;
  6534. return result;
  6535. }
  6536. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  6537. {
  6538. return lhs.m_it - rhs.m_it;
  6539. }
  6540. primitive_iterator_t& operator++() noexcept
  6541. {
  6542. ++m_it;
  6543. return *this;
  6544. }
  6545. primitive_iterator_t const operator++(int) noexcept
  6546. {
  6547. auto result = *this;
  6548. ++m_it;
  6549. return result;
  6550. }
  6551. primitive_iterator_t& operator--() noexcept
  6552. {
  6553. --m_it;
  6554. return *this;
  6555. }
  6556. primitive_iterator_t const operator--(int) noexcept
  6557. {
  6558. auto result = *this;
  6559. --m_it;
  6560. return result;
  6561. }
  6562. primitive_iterator_t& operator+=(difference_type n) noexcept
  6563. {
  6564. m_it += n;
  6565. return *this;
  6566. }
  6567. primitive_iterator_t& operator-=(difference_type n) noexcept
  6568. {
  6569. m_it -= n;
  6570. return *this;
  6571. }
  6572. };
  6573. } // namespace detail
  6574. } // namespace nlohmann
  6575. namespace nlohmann
  6576. {
  6577. namespace detail
  6578. {
  6579. /*!
  6580. @brief an iterator value
  6581. @note This structure could easily be a union, but MSVC currently does not allow
  6582. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  6583. */
  6584. template<typename BasicJsonType> struct internal_iterator
  6585. {
  6586. /// iterator for JSON objects
  6587. typename BasicJsonType::object_t::iterator object_iterator {};
  6588. /// iterator for JSON arrays
  6589. typename BasicJsonType::array_t::iterator array_iterator {};
  6590. /// generic iterator for all other types
  6591. primitive_iterator_t primitive_iterator {};
  6592. };
  6593. } // namespace detail
  6594. } // namespace nlohmann
  6595. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  6596. #include <ciso646> // not
  6597. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  6598. #include <type_traits> // conditional, is_const, remove_const
  6599. // #include <nlohmann/detail/exceptions.hpp>
  6600. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  6601. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  6602. // #include <nlohmann/detail/macro_scope.hpp>
  6603. // #include <nlohmann/detail/meta/cpp_future.hpp>
  6604. // #include <nlohmann/detail/meta/type_traits.hpp>
  6605. // #include <nlohmann/detail/value_t.hpp>
  6606. namespace nlohmann
  6607. {
  6608. namespace detail
  6609. {
  6610. // forward declare, to be able to friend it later on
  6611. template<typename IteratorType> class iteration_proxy;
  6612. template<typename IteratorType> class iteration_proxy_value;
  6613. /*!
  6614. @brief a template for a bidirectional iterator for the @ref basic_json class
  6615. This class implements a both iterators (iterator and const_iterator) for the
  6616. @ref basic_json class.
  6617. @note An iterator is called *initialized* when a pointer to a JSON value has
  6618. been set (e.g., by a constructor or a copy assignment). If the iterator is
  6619. default-constructed, it is *uninitialized* and most methods are undefined.
  6620. **The library uses assertions to detect calls on uninitialized iterators.**
  6621. @requirement The class satisfies the following concept requirements:
  6622. -
  6623. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  6624. The iterator that can be moved can be moved in both directions (i.e.
  6625. incremented and decremented).
  6626. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  6627. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  6628. */
  6629. template<typename BasicJsonType>
  6630. class iter_impl
  6631. {
  6632. /// allow basic_json to access private members
  6633. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  6634. friend BasicJsonType;
  6635. friend iteration_proxy<iter_impl>;
  6636. friend iteration_proxy_value<iter_impl>;
  6637. using object_t = typename BasicJsonType::object_t;
  6638. using array_t = typename BasicJsonType::array_t;
  6639. // make sure BasicJsonType is basic_json or const basic_json
  6640. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  6641. "iter_impl only accepts (const) basic_json");
  6642. public:
  6643. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  6644. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  6645. /// A user-defined iterator should provide publicly accessible typedefs named
  6646. /// iterator_category, value_type, difference_type, pointer, and reference.
  6647. /// Note that value_type is required to be non-const, even for constant iterators.
  6648. using iterator_category = std::bidirectional_iterator_tag;
  6649. /// the type of the values when the iterator is dereferenced
  6650. using value_type = typename BasicJsonType::value_type;
  6651. /// a type to represent differences between iterators
  6652. using difference_type = typename BasicJsonType::difference_type;
  6653. /// defines a pointer to the type iterated over (value_type)
  6654. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  6655. typename BasicJsonType::const_pointer,
  6656. typename BasicJsonType::pointer>::type;
  6657. /// defines a reference to the type iterated over (value_type)
  6658. using reference =
  6659. typename std::conditional<std::is_const<BasicJsonType>::value,
  6660. typename BasicJsonType::const_reference,
  6661. typename BasicJsonType::reference>::type;
  6662. /// default constructor
  6663. iter_impl() = default;
  6664. /*!
  6665. @brief constructor for a given JSON instance
  6666. @param[in] object pointer to a JSON object for this iterator
  6667. @pre object != nullptr
  6668. @post The iterator is initialized; i.e. `m_object != nullptr`.
  6669. */
  6670. explicit iter_impl(pointer object) noexcept : m_object(object)
  6671. {
  6672. assert(m_object != nullptr);
  6673. switch (m_object->m_type)
  6674. {
  6675. case value_t::object:
  6676. {
  6677. m_it.object_iterator = typename object_t::iterator();
  6678. break;
  6679. }
  6680. case value_t::array:
  6681. {
  6682. m_it.array_iterator = typename array_t::iterator();
  6683. break;
  6684. }
  6685. default:
  6686. {
  6687. m_it.primitive_iterator = primitive_iterator_t();
  6688. break;
  6689. }
  6690. }
  6691. }
  6692. /*!
  6693. @note The conventional copy constructor and copy assignment are implicitly
  6694. defined. Combined with the following converting constructor and
  6695. assignment, they support: (1) copy from iterator to iterator, (2)
  6696. copy from const iterator to const iterator, and (3) conversion from
  6697. iterator to const iterator. However conversion from const iterator
  6698. to iterator is not defined.
  6699. */
  6700. /*!
  6701. @brief converting constructor
  6702. @param[in] other non-const iterator to copy from
  6703. @note It is not checked whether @a other is initialized.
  6704. */
  6705. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  6706. : m_object(other.m_object), m_it(other.m_it) {}
  6707. /*!
  6708. @brief converting assignment
  6709. @param[in,out] other non-const iterator to copy from
  6710. @return const/non-const iterator
  6711. @note It is not checked whether @a other is initialized.
  6712. */
  6713. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  6714. {
  6715. m_object = other.m_object;
  6716. m_it = other.m_it;
  6717. return *this;
  6718. }
  6719. private:
  6720. /*!
  6721. @brief set the iterator to the first value
  6722. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6723. */
  6724. void set_begin() noexcept
  6725. {
  6726. assert(m_object != nullptr);
  6727. switch (m_object->m_type)
  6728. {
  6729. case value_t::object:
  6730. {
  6731. m_it.object_iterator = m_object->m_value.object->begin();
  6732. break;
  6733. }
  6734. case value_t::array:
  6735. {
  6736. m_it.array_iterator = m_object->m_value.array->begin();
  6737. break;
  6738. }
  6739. case value_t::null:
  6740. {
  6741. // set to end so begin()==end() is true: null is empty
  6742. m_it.primitive_iterator.set_end();
  6743. break;
  6744. }
  6745. default:
  6746. {
  6747. m_it.primitive_iterator.set_begin();
  6748. break;
  6749. }
  6750. }
  6751. }
  6752. /*!
  6753. @brief set the iterator past the last value
  6754. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6755. */
  6756. void set_end() noexcept
  6757. {
  6758. assert(m_object != nullptr);
  6759. switch (m_object->m_type)
  6760. {
  6761. case value_t::object:
  6762. {
  6763. m_it.object_iterator = m_object->m_value.object->end();
  6764. break;
  6765. }
  6766. case value_t::array:
  6767. {
  6768. m_it.array_iterator = m_object->m_value.array->end();
  6769. break;
  6770. }
  6771. default:
  6772. {
  6773. m_it.primitive_iterator.set_end();
  6774. break;
  6775. }
  6776. }
  6777. }
  6778. public:
  6779. /*!
  6780. @brief return a reference to the value pointed to by the iterator
  6781. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6782. */
  6783. reference operator*() const
  6784. {
  6785. assert(m_object != nullptr);
  6786. switch (m_object->m_type)
  6787. {
  6788. case value_t::object:
  6789. {
  6790. assert(m_it.object_iterator != m_object->m_value.object->end());
  6791. return m_it.object_iterator->second;
  6792. }
  6793. case value_t::array:
  6794. {
  6795. assert(m_it.array_iterator != m_object->m_value.array->end());
  6796. return *m_it.array_iterator;
  6797. }
  6798. case value_t::null:
  6799. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6800. default:
  6801. {
  6802. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  6803. {
  6804. return *m_object;
  6805. }
  6806. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6807. }
  6808. }
  6809. }
  6810. /*!
  6811. @brief dereference the iterator
  6812. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6813. */
  6814. pointer operator->() const
  6815. {
  6816. assert(m_object != nullptr);
  6817. switch (m_object->m_type)
  6818. {
  6819. case value_t::object:
  6820. {
  6821. assert(m_it.object_iterator != m_object->m_value.object->end());
  6822. return &(m_it.object_iterator->second);
  6823. }
  6824. case value_t::array:
  6825. {
  6826. assert(m_it.array_iterator != m_object->m_value.array->end());
  6827. return &*m_it.array_iterator;
  6828. }
  6829. default:
  6830. {
  6831. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  6832. {
  6833. return m_object;
  6834. }
  6835. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  6836. }
  6837. }
  6838. }
  6839. /*!
  6840. @brief post-increment (it++)
  6841. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6842. */
  6843. iter_impl const operator++(int)
  6844. {
  6845. auto result = *this;
  6846. ++(*this);
  6847. return result;
  6848. }
  6849. /*!
  6850. @brief pre-increment (++it)
  6851. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6852. */
  6853. iter_impl& operator++()
  6854. {
  6855. assert(m_object != nullptr);
  6856. switch (m_object->m_type)
  6857. {
  6858. case value_t::object:
  6859. {
  6860. std::advance(m_it.object_iterator, 1);
  6861. break;
  6862. }
  6863. case value_t::array:
  6864. {
  6865. std::advance(m_it.array_iterator, 1);
  6866. break;
  6867. }
  6868. default:
  6869. {
  6870. ++m_it.primitive_iterator;
  6871. break;
  6872. }
  6873. }
  6874. return *this;
  6875. }
  6876. /*!
  6877. @brief post-decrement (it--)
  6878. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6879. */
  6880. iter_impl const operator--(int)
  6881. {
  6882. auto result = *this;
  6883. --(*this);
  6884. return result;
  6885. }
  6886. /*!
  6887. @brief pre-decrement (--it)
  6888. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6889. */
  6890. iter_impl& operator--()
  6891. {
  6892. assert(m_object != nullptr);
  6893. switch (m_object->m_type)
  6894. {
  6895. case value_t::object:
  6896. {
  6897. std::advance(m_it.object_iterator, -1);
  6898. break;
  6899. }
  6900. case value_t::array:
  6901. {
  6902. std::advance(m_it.array_iterator, -1);
  6903. break;
  6904. }
  6905. default:
  6906. {
  6907. --m_it.primitive_iterator;
  6908. break;
  6909. }
  6910. }
  6911. return *this;
  6912. }
  6913. /*!
  6914. @brief comparison: equal
  6915. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6916. */
  6917. bool operator==(const iter_impl& other) const
  6918. {
  6919. // if objects are not the same, the comparison is undefined
  6920. if (JSON_UNLIKELY(m_object != other.m_object))
  6921. {
  6922. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6923. }
  6924. assert(m_object != nullptr);
  6925. switch (m_object->m_type)
  6926. {
  6927. case value_t::object:
  6928. return (m_it.object_iterator == other.m_it.object_iterator);
  6929. case value_t::array:
  6930. return (m_it.array_iterator == other.m_it.array_iterator);
  6931. default:
  6932. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  6933. }
  6934. }
  6935. /*!
  6936. @brief comparison: not equal
  6937. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6938. */
  6939. bool operator!=(const iter_impl& other) const
  6940. {
  6941. return not operator==(other);
  6942. }
  6943. /*!
  6944. @brief comparison: smaller
  6945. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6946. */
  6947. bool operator<(const iter_impl& other) const
  6948. {
  6949. // if objects are not the same, the comparison is undefined
  6950. if (JSON_UNLIKELY(m_object != other.m_object))
  6951. {
  6952. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  6953. }
  6954. assert(m_object != nullptr);
  6955. switch (m_object->m_type)
  6956. {
  6957. case value_t::object:
  6958. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  6959. case value_t::array:
  6960. return (m_it.array_iterator < other.m_it.array_iterator);
  6961. default:
  6962. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  6963. }
  6964. }
  6965. /*!
  6966. @brief comparison: less than or equal
  6967. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6968. */
  6969. bool operator<=(const iter_impl& other) const
  6970. {
  6971. return not other.operator < (*this);
  6972. }
  6973. /*!
  6974. @brief comparison: greater than
  6975. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6976. */
  6977. bool operator>(const iter_impl& other) const
  6978. {
  6979. return not operator<=(other);
  6980. }
  6981. /*!
  6982. @brief comparison: greater than or equal
  6983. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6984. */
  6985. bool operator>=(const iter_impl& other) const
  6986. {
  6987. return not operator<(other);
  6988. }
  6989. /*!
  6990. @brief add to iterator
  6991. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  6992. */
  6993. iter_impl& operator+=(difference_type i)
  6994. {
  6995. assert(m_object != nullptr);
  6996. switch (m_object->m_type)
  6997. {
  6998. case value_t::object:
  6999. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  7000. case value_t::array:
  7001. {
  7002. std::advance(m_it.array_iterator, i);
  7003. break;
  7004. }
  7005. default:
  7006. {
  7007. m_it.primitive_iterator += i;
  7008. break;
  7009. }
  7010. }
  7011. return *this;
  7012. }
  7013. /*!
  7014. @brief subtract from iterator
  7015. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7016. */
  7017. iter_impl& operator-=(difference_type i)
  7018. {
  7019. return operator+=(-i);
  7020. }
  7021. /*!
  7022. @brief add to iterator
  7023. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7024. */
  7025. iter_impl operator+(difference_type i) const
  7026. {
  7027. auto result = *this;
  7028. result += i;
  7029. return result;
  7030. }
  7031. /*!
  7032. @brief addition of distance and iterator
  7033. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7034. */
  7035. friend iter_impl operator+(difference_type i, const iter_impl& it)
  7036. {
  7037. auto result = it;
  7038. result += i;
  7039. return result;
  7040. }
  7041. /*!
  7042. @brief subtract from iterator
  7043. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7044. */
  7045. iter_impl operator-(difference_type i) const
  7046. {
  7047. auto result = *this;
  7048. result -= i;
  7049. return result;
  7050. }
  7051. /*!
  7052. @brief return difference
  7053. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7054. */
  7055. difference_type operator-(const iter_impl& other) const
  7056. {
  7057. assert(m_object != nullptr);
  7058. switch (m_object->m_type)
  7059. {
  7060. case value_t::object:
  7061. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  7062. case value_t::array:
  7063. return m_it.array_iterator - other.m_it.array_iterator;
  7064. default:
  7065. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  7066. }
  7067. }
  7068. /*!
  7069. @brief access to successor
  7070. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7071. */
  7072. reference operator[](difference_type n) const
  7073. {
  7074. assert(m_object != nullptr);
  7075. switch (m_object->m_type)
  7076. {
  7077. case value_t::object:
  7078. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  7079. case value_t::array:
  7080. return *std::next(m_it.array_iterator, n);
  7081. case value_t::null:
  7082. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  7083. default:
  7084. {
  7085. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  7086. {
  7087. return *m_object;
  7088. }
  7089. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  7090. }
  7091. }
  7092. }
  7093. /*!
  7094. @brief return the key of an object iterator
  7095. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7096. */
  7097. const typename object_t::key_type& key() const
  7098. {
  7099. assert(m_object != nullptr);
  7100. if (JSON_LIKELY(m_object->is_object()))
  7101. {
  7102. return m_it.object_iterator->first;
  7103. }
  7104. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  7105. }
  7106. /*!
  7107. @brief return the value of an iterator
  7108. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  7109. */
  7110. reference value() const
  7111. {
  7112. return operator*();
  7113. }
  7114. private:
  7115. /// associated JSON instance
  7116. pointer m_object = nullptr;
  7117. /// the actual iterator of the associated instance
  7118. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it {};
  7119. };
  7120. } // namespace detail
  7121. } // namespace nlohmann
  7122. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  7123. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  7124. #include <cstddef> // ptrdiff_t
  7125. #include <iterator> // reverse_iterator
  7126. #include <utility> // declval
  7127. namespace nlohmann
  7128. {
  7129. namespace detail
  7130. {
  7131. //////////////////////
  7132. // reverse_iterator //
  7133. //////////////////////
  7134. /*!
  7135. @brief a template for a reverse iterator class
  7136. @tparam Base the base iterator type to reverse. Valid types are @ref
  7137. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  7138. create @ref const_reverse_iterator).
  7139. @requirement The class satisfies the following concept requirements:
  7140. -
  7141. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  7142. The iterator that can be moved can be moved in both directions (i.e.
  7143. incremented and decremented).
  7144. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  7145. It is possible to write to the pointed-to element (only if @a Base is
  7146. @ref iterator).
  7147. @since version 1.0.0
  7148. */
  7149. template<typename Base>
  7150. class json_reverse_iterator : public std::reverse_iterator<Base>
  7151. {
  7152. public:
  7153. using difference_type = std::ptrdiff_t;
  7154. /// shortcut to the reverse iterator adapter
  7155. using base_iterator = std::reverse_iterator<Base>;
  7156. /// the reference type for the pointed-to element
  7157. using reference = typename Base::reference;
  7158. /// create reverse iterator from iterator
  7159. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  7160. : base_iterator(it) {}
  7161. /// create reverse iterator from base class
  7162. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  7163. /// post-increment (it++)
  7164. json_reverse_iterator const operator++(int)
  7165. {
  7166. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  7167. }
  7168. /// pre-increment (++it)
  7169. json_reverse_iterator& operator++()
  7170. {
  7171. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  7172. }
  7173. /// post-decrement (it--)
  7174. json_reverse_iterator const operator--(int)
  7175. {
  7176. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  7177. }
  7178. /// pre-decrement (--it)
  7179. json_reverse_iterator& operator--()
  7180. {
  7181. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  7182. }
  7183. /// add to iterator
  7184. json_reverse_iterator& operator+=(difference_type i)
  7185. {
  7186. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  7187. }
  7188. /// add to iterator
  7189. json_reverse_iterator operator+(difference_type i) const
  7190. {
  7191. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  7192. }
  7193. /// subtract from iterator
  7194. json_reverse_iterator operator-(difference_type i) const
  7195. {
  7196. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  7197. }
  7198. /// return difference
  7199. difference_type operator-(const json_reverse_iterator& other) const
  7200. {
  7201. return base_iterator(*this) - base_iterator(other);
  7202. }
  7203. /// access to successor
  7204. reference operator[](difference_type n) const
  7205. {
  7206. return *(this->operator+(n));
  7207. }
  7208. /// return the key of an object iterator
  7209. auto key() const -> decltype(std::declval<Base>().key())
  7210. {
  7211. auto it = --this->base();
  7212. return it.key();
  7213. }
  7214. /// return the value of an iterator
  7215. reference value() const
  7216. {
  7217. auto it = --this->base();
  7218. return it.operator * ();
  7219. }
  7220. };
  7221. } // namespace detail
  7222. } // namespace nlohmann
  7223. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  7224. // #include <nlohmann/detail/json_pointer.hpp>
  7225. #include <algorithm> // all_of
  7226. #include <cassert> // assert
  7227. #include <numeric> // accumulate
  7228. #include <string> // string
  7229. #include <utility> // move
  7230. #include <vector> // vector
  7231. // #include <nlohmann/detail/exceptions.hpp>
  7232. // #include <nlohmann/detail/macro_scope.hpp>
  7233. // #include <nlohmann/detail/value_t.hpp>
  7234. namespace nlohmann
  7235. {
  7236. template<typename BasicJsonType>
  7237. class json_pointer
  7238. {
  7239. // allow basic_json to access private members
  7240. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  7241. friend class basic_json;
  7242. public:
  7243. /*!
  7244. @brief create JSON pointer
  7245. Create a JSON pointer according to the syntax described in
  7246. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  7247. @param[in] s string representing the JSON pointer; if omitted, the empty
  7248. string is assumed which references the whole JSON value
  7249. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  7250. not begin with a slash (`/`); see example below
  7251. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  7252. not followed by `0` (representing `~`) or `1` (representing `/`); see
  7253. example below
  7254. @liveexample{The example shows the construction several valid JSON pointers
  7255. as well as the exceptional behavior.,json_pointer}
  7256. @since version 2.0.0
  7257. */
  7258. explicit json_pointer(const std::string& s = "")
  7259. : reference_tokens(split(s))
  7260. {}
  7261. /*!
  7262. @brief return a string representation of the JSON pointer
  7263. @invariant For each JSON pointer `ptr`, it holds:
  7264. @code {.cpp}
  7265. ptr == json_pointer(ptr.to_string());
  7266. @endcode
  7267. @return a string representation of the JSON pointer
  7268. @liveexample{The example shows the result of `to_string`.,json_pointer__to_string}
  7269. @since version 2.0.0
  7270. */
  7271. std::string to_string() const
  7272. {
  7273. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  7274. std::string{},
  7275. [](const std::string & a, const std::string & b)
  7276. {
  7277. return a + "/" + escape(b);
  7278. });
  7279. }
  7280. /// @copydoc to_string()
  7281. operator std::string() const
  7282. {
  7283. return to_string();
  7284. }
  7285. /*!
  7286. @brief append another JSON pointer at the end of this JSON pointer
  7287. @param[in] ptr JSON pointer to append
  7288. @return JSON pointer with @a ptr appended
  7289. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7290. @complexity Linear in the length of @a ptr.
  7291. @sa @ref operator/=(std::string) to append a reference token
  7292. @sa @ref operator/=(std::size_t) to append an array index
  7293. @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator
  7294. @since version 3.6.0
  7295. */
  7296. json_pointer& operator/=(const json_pointer& ptr)
  7297. {
  7298. reference_tokens.insert(reference_tokens.end(),
  7299. ptr.reference_tokens.begin(),
  7300. ptr.reference_tokens.end());
  7301. return *this;
  7302. }
  7303. /*!
  7304. @brief append an unescaped reference token at the end of this JSON pointer
  7305. @param[in] token reference token to append
  7306. @return JSON pointer with @a token appended without escaping @a token
  7307. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7308. @complexity Amortized constant.
  7309. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7310. @sa @ref operator/=(std::size_t) to append an array index
  7311. @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator
  7312. @since version 3.6.0
  7313. */
  7314. json_pointer& operator/=(std::string token)
  7315. {
  7316. push_back(std::move(token));
  7317. return *this;
  7318. }
  7319. /*!
  7320. @brief append an array index at the end of this JSON pointer
  7321. @param[in] array_index array index ot append
  7322. @return JSON pointer with @a array_index appended
  7323. @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add}
  7324. @complexity Amortized constant.
  7325. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7326. @sa @ref operator/=(std::string) to append a reference token
  7327. @sa @ref operator/(const json_pointer&, std::string) for a binary operator
  7328. @since version 3.6.0
  7329. */
  7330. json_pointer& operator/=(std::size_t array_index)
  7331. {
  7332. return *this /= std::to_string(array_index);
  7333. }
  7334. /*!
  7335. @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer
  7336. @param[in] lhs JSON pointer
  7337. @param[in] rhs JSON pointer
  7338. @return a new JSON pointer with @a rhs appended to @a lhs
  7339. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7340. @complexity Linear in the length of @a lhs and @a rhs.
  7341. @sa @ref operator/=(const json_pointer&) to append a JSON pointer
  7342. @since version 3.6.0
  7343. */
  7344. friend json_pointer operator/(const json_pointer& lhs,
  7345. const json_pointer& rhs)
  7346. {
  7347. return json_pointer(lhs) /= rhs;
  7348. }
  7349. /*!
  7350. @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer
  7351. @param[in] ptr JSON pointer
  7352. @param[in] token reference token
  7353. @return a new JSON pointer with unescaped @a token appended to @a ptr
  7354. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7355. @complexity Linear in the length of @a ptr.
  7356. @sa @ref operator/=(std::string) to append a reference token
  7357. @since version 3.6.0
  7358. */
  7359. friend json_pointer operator/(const json_pointer& ptr, std::string token)
  7360. {
  7361. return json_pointer(ptr) /= std::move(token);
  7362. }
  7363. /*!
  7364. @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer
  7365. @param[in] ptr JSON pointer
  7366. @param[in] array_index array index
  7367. @return a new JSON pointer with @a array_index appended to @a ptr
  7368. @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary}
  7369. @complexity Linear in the length of @a ptr.
  7370. @sa @ref operator/=(std::size_t) to append an array index
  7371. @since version 3.6.0
  7372. */
  7373. friend json_pointer operator/(const json_pointer& ptr, std::size_t array_index)
  7374. {
  7375. return json_pointer(ptr) /= array_index;
  7376. }
  7377. /*!
  7378. @brief returns the parent of this JSON pointer
  7379. @return parent of this JSON pointer; in case this JSON pointer is the root,
  7380. the root itself is returned
  7381. @complexity Linear in the length of the JSON pointer.
  7382. @liveexample{The example shows the result of `parent_pointer` for different
  7383. JSON Pointers.,json_pointer__parent_pointer}
  7384. @since version 3.6.0
  7385. */
  7386. json_pointer parent_pointer() const
  7387. {
  7388. if (empty())
  7389. {
  7390. return *this;
  7391. }
  7392. json_pointer res = *this;
  7393. res.pop_back();
  7394. return res;
  7395. }
  7396. /*!
  7397. @brief remove last reference token
  7398. @pre not `empty()`
  7399. @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back}
  7400. @complexity Constant.
  7401. @throw out_of_range.405 if JSON pointer has no parent
  7402. @since version 3.6.0
  7403. */
  7404. void pop_back()
  7405. {
  7406. if (JSON_UNLIKELY(empty()))
  7407. {
  7408. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7409. }
  7410. reference_tokens.pop_back();
  7411. }
  7412. /*!
  7413. @brief return last reference token
  7414. @pre not `empty()`
  7415. @return last reference token
  7416. @liveexample{The example shows the usage of `back`.,json_pointer__back}
  7417. @complexity Constant.
  7418. @throw out_of_range.405 if JSON pointer has no parent
  7419. @since version 3.6.0
  7420. */
  7421. const std::string& back()
  7422. {
  7423. if (JSON_UNLIKELY(empty()))
  7424. {
  7425. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7426. }
  7427. return reference_tokens.back();
  7428. }
  7429. /*!
  7430. @brief append an unescaped token at the end of the reference pointer
  7431. @param[in] token token to add
  7432. @complexity Amortized constant.
  7433. @liveexample{The example shows the result of `push_back` for different
  7434. JSON Pointers.,json_pointer__push_back}
  7435. @since version 3.6.0
  7436. */
  7437. void push_back(const std::string& token)
  7438. {
  7439. reference_tokens.push_back(token);
  7440. }
  7441. /// @copydoc push_back(const std::string&)
  7442. void push_back(std::string&& token)
  7443. {
  7444. reference_tokens.push_back(std::move(token));
  7445. }
  7446. /*!
  7447. @brief return whether pointer points to the root document
  7448. @return true iff the JSON pointer points to the root document
  7449. @complexity Constant.
  7450. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  7451. @liveexample{The example shows the result of `empty` for different JSON
  7452. Pointers.,json_pointer__empty}
  7453. @since version 3.6.0
  7454. */
  7455. bool empty() const noexcept
  7456. {
  7457. return reference_tokens.empty();
  7458. }
  7459. private:
  7460. /*!
  7461. @param[in] s reference token to be converted into an array index
  7462. @return integer representation of @a s
  7463. @throw out_of_range.404 if string @a s could not be converted to an integer
  7464. */
  7465. static int array_index(const std::string& s)
  7466. {
  7467. std::size_t processed_chars = 0;
  7468. const int res = std::stoi(s, &processed_chars);
  7469. // check if the string was completely read
  7470. if (JSON_UNLIKELY(processed_chars != s.size()))
  7471. {
  7472. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  7473. }
  7474. return res;
  7475. }
  7476. json_pointer top() const
  7477. {
  7478. if (JSON_UNLIKELY(empty()))
  7479. {
  7480. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  7481. }
  7482. json_pointer result = *this;
  7483. result.reference_tokens = {reference_tokens[0]};
  7484. return result;
  7485. }
  7486. /*!
  7487. @brief create and return a reference to the pointed to value
  7488. @complexity Linear in the number of reference tokens.
  7489. @throw parse_error.109 if array index is not a number
  7490. @throw type_error.313 if value cannot be unflattened
  7491. */
  7492. BasicJsonType& get_and_create(BasicJsonType& j) const
  7493. {
  7494. using size_type = typename BasicJsonType::size_type;
  7495. auto result = &j;
  7496. // in case no reference tokens exist, return a reference to the JSON value
  7497. // j which will be overwritten by a primitive value
  7498. for (const auto& reference_token : reference_tokens)
  7499. {
  7500. switch (result->m_type)
  7501. {
  7502. case detail::value_t::null:
  7503. {
  7504. if (reference_token == "0")
  7505. {
  7506. // start a new array if reference token is 0
  7507. result = &result->operator[](0);
  7508. }
  7509. else
  7510. {
  7511. // start a new object otherwise
  7512. result = &result->operator[](reference_token);
  7513. }
  7514. break;
  7515. }
  7516. case detail::value_t::object:
  7517. {
  7518. // create an entry in the object
  7519. result = &result->operator[](reference_token);
  7520. break;
  7521. }
  7522. case detail::value_t::array:
  7523. {
  7524. // create an entry in the array
  7525. JSON_TRY
  7526. {
  7527. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  7528. }
  7529. JSON_CATCH(std::invalid_argument&)
  7530. {
  7531. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7532. }
  7533. break;
  7534. }
  7535. /*
  7536. The following code is only reached if there exists a reference
  7537. token _and_ the current value is primitive. In this case, we have
  7538. an error situation, because primitive values may only occur as
  7539. single value; that is, with an empty list of reference tokens.
  7540. */
  7541. default:
  7542. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  7543. }
  7544. }
  7545. return *result;
  7546. }
  7547. /*!
  7548. @brief return a reference to the pointed to value
  7549. @note This version does not throw if a value is not present, but tries to
  7550. create nested values instead. For instance, calling this function
  7551. with pointer `"/this/that"` on a null value is equivalent to calling
  7552. `operator[]("this").operator[]("that")` on that value, effectively
  7553. changing the null value to an object.
  7554. @param[in] ptr a JSON value
  7555. @return reference to the JSON value pointed to by the JSON pointer
  7556. @complexity Linear in the length of the JSON pointer.
  7557. @throw parse_error.106 if an array index begins with '0'
  7558. @throw parse_error.109 if an array index was not a number
  7559. @throw out_of_range.404 if the JSON pointer can not be resolved
  7560. */
  7561. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  7562. {
  7563. using size_type = typename BasicJsonType::size_type;
  7564. for (const auto& reference_token : reference_tokens)
  7565. {
  7566. // convert null values to arrays or objects before continuing
  7567. if (ptr->m_type == detail::value_t::null)
  7568. {
  7569. // check if reference token is a number
  7570. const bool nums =
  7571. std::all_of(reference_token.begin(), reference_token.end(),
  7572. [](const char x)
  7573. {
  7574. return x >= '0' and x <= '9';
  7575. });
  7576. // change value to array for numbers or "-" or to object otherwise
  7577. *ptr = (nums or reference_token == "-")
  7578. ? detail::value_t::array
  7579. : detail::value_t::object;
  7580. }
  7581. switch (ptr->m_type)
  7582. {
  7583. case detail::value_t::object:
  7584. {
  7585. // use unchecked object access
  7586. ptr = &ptr->operator[](reference_token);
  7587. break;
  7588. }
  7589. case detail::value_t::array:
  7590. {
  7591. // error condition (cf. RFC 6901, Sect. 4)
  7592. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7593. {
  7594. JSON_THROW(detail::parse_error::create(106, 0,
  7595. "array index '" + reference_token +
  7596. "' must not begin with '0'"));
  7597. }
  7598. if (reference_token == "-")
  7599. {
  7600. // explicitly treat "-" as index beyond the end
  7601. ptr = &ptr->operator[](ptr->m_value.array->size());
  7602. }
  7603. else
  7604. {
  7605. // convert array index to number; unchecked access
  7606. JSON_TRY
  7607. {
  7608. ptr = &ptr->operator[](
  7609. static_cast<size_type>(array_index(reference_token)));
  7610. }
  7611. JSON_CATCH(std::invalid_argument&)
  7612. {
  7613. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7614. }
  7615. }
  7616. break;
  7617. }
  7618. default:
  7619. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7620. }
  7621. }
  7622. return *ptr;
  7623. }
  7624. /*!
  7625. @throw parse_error.106 if an array index begins with '0'
  7626. @throw parse_error.109 if an array index was not a number
  7627. @throw out_of_range.402 if the array index '-' is used
  7628. @throw out_of_range.404 if the JSON pointer can not be resolved
  7629. */
  7630. BasicJsonType& get_checked(BasicJsonType* ptr) const
  7631. {
  7632. using size_type = typename BasicJsonType::size_type;
  7633. for (const auto& reference_token : reference_tokens)
  7634. {
  7635. switch (ptr->m_type)
  7636. {
  7637. case detail::value_t::object:
  7638. {
  7639. // note: at performs range check
  7640. ptr = &ptr->at(reference_token);
  7641. break;
  7642. }
  7643. case detail::value_t::array:
  7644. {
  7645. if (JSON_UNLIKELY(reference_token == "-"))
  7646. {
  7647. // "-" always fails the range check
  7648. JSON_THROW(detail::out_of_range::create(402,
  7649. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7650. ") is out of range"));
  7651. }
  7652. // error condition (cf. RFC 6901, Sect. 4)
  7653. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7654. {
  7655. JSON_THROW(detail::parse_error::create(106, 0,
  7656. "array index '" + reference_token +
  7657. "' must not begin with '0'"));
  7658. }
  7659. // note: at performs range check
  7660. JSON_TRY
  7661. {
  7662. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  7663. }
  7664. JSON_CATCH(std::invalid_argument&)
  7665. {
  7666. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7667. }
  7668. break;
  7669. }
  7670. default:
  7671. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7672. }
  7673. }
  7674. return *ptr;
  7675. }
  7676. /*!
  7677. @brief return a const reference to the pointed to value
  7678. @param[in] ptr a JSON value
  7679. @return const reference to the JSON value pointed to by the JSON
  7680. pointer
  7681. @throw parse_error.106 if an array index begins with '0'
  7682. @throw parse_error.109 if an array index was not a number
  7683. @throw out_of_range.402 if the array index '-' is used
  7684. @throw out_of_range.404 if the JSON pointer can not be resolved
  7685. */
  7686. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  7687. {
  7688. using size_type = typename BasicJsonType::size_type;
  7689. for (const auto& reference_token : reference_tokens)
  7690. {
  7691. switch (ptr->m_type)
  7692. {
  7693. case detail::value_t::object:
  7694. {
  7695. // use unchecked object access
  7696. ptr = &ptr->operator[](reference_token);
  7697. break;
  7698. }
  7699. case detail::value_t::array:
  7700. {
  7701. if (JSON_UNLIKELY(reference_token == "-"))
  7702. {
  7703. // "-" cannot be used for const access
  7704. JSON_THROW(detail::out_of_range::create(402,
  7705. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7706. ") is out of range"));
  7707. }
  7708. // error condition (cf. RFC 6901, Sect. 4)
  7709. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7710. {
  7711. JSON_THROW(detail::parse_error::create(106, 0,
  7712. "array index '" + reference_token +
  7713. "' must not begin with '0'"));
  7714. }
  7715. // use unchecked array access
  7716. JSON_TRY
  7717. {
  7718. ptr = &ptr->operator[](
  7719. static_cast<size_type>(array_index(reference_token)));
  7720. }
  7721. JSON_CATCH(std::invalid_argument&)
  7722. {
  7723. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7724. }
  7725. break;
  7726. }
  7727. default:
  7728. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7729. }
  7730. }
  7731. return *ptr;
  7732. }
  7733. /*!
  7734. @throw parse_error.106 if an array index begins with '0'
  7735. @throw parse_error.109 if an array index was not a number
  7736. @throw out_of_range.402 if the array index '-' is used
  7737. @throw out_of_range.404 if the JSON pointer can not be resolved
  7738. */
  7739. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  7740. {
  7741. using size_type = typename BasicJsonType::size_type;
  7742. for (const auto& reference_token : reference_tokens)
  7743. {
  7744. switch (ptr->m_type)
  7745. {
  7746. case detail::value_t::object:
  7747. {
  7748. // note: at performs range check
  7749. ptr = &ptr->at(reference_token);
  7750. break;
  7751. }
  7752. case detail::value_t::array:
  7753. {
  7754. if (JSON_UNLIKELY(reference_token == "-"))
  7755. {
  7756. // "-" always fails the range check
  7757. JSON_THROW(detail::out_of_range::create(402,
  7758. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  7759. ") is out of range"));
  7760. }
  7761. // error condition (cf. RFC 6901, Sect. 4)
  7762. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  7763. {
  7764. JSON_THROW(detail::parse_error::create(106, 0,
  7765. "array index '" + reference_token +
  7766. "' must not begin with '0'"));
  7767. }
  7768. // note: at performs range check
  7769. JSON_TRY
  7770. {
  7771. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  7772. }
  7773. JSON_CATCH(std::invalid_argument&)
  7774. {
  7775. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  7776. }
  7777. break;
  7778. }
  7779. default:
  7780. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  7781. }
  7782. }
  7783. return *ptr;
  7784. }
  7785. /*!
  7786. @brief split the string input to reference tokens
  7787. @note This function is only called by the json_pointer constructor.
  7788. All exceptions below are documented there.
  7789. @throw parse_error.107 if the pointer is not empty or begins with '/'
  7790. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  7791. */
  7792. static std::vector<std::string> split(const std::string& reference_string)
  7793. {
  7794. std::vector<std::string> result;
  7795. // special case: empty reference string -> no reference tokens
  7796. if (reference_string.empty())
  7797. {
  7798. return result;
  7799. }
  7800. // check if nonempty reference string begins with slash
  7801. if (JSON_UNLIKELY(reference_string[0] != '/'))
  7802. {
  7803. JSON_THROW(detail::parse_error::create(107, 1,
  7804. "JSON pointer must be empty or begin with '/' - was: '" +
  7805. reference_string + "'"));
  7806. }
  7807. // extract the reference tokens:
  7808. // - slash: position of the last read slash (or end of string)
  7809. // - start: position after the previous slash
  7810. for (
  7811. // search for the first slash after the first character
  7812. std::size_t slash = reference_string.find_first_of('/', 1),
  7813. // set the beginning of the first reference token
  7814. start = 1;
  7815. // we can stop if start == 0 (if slash == std::string::npos)
  7816. start != 0;
  7817. // set the beginning of the next reference token
  7818. // (will eventually be 0 if slash == std::string::npos)
  7819. start = (slash == std::string::npos) ? 0 : slash + 1,
  7820. // find next slash
  7821. slash = reference_string.find_first_of('/', start))
  7822. {
  7823. // use the text between the beginning of the reference token
  7824. // (start) and the last slash (slash).
  7825. auto reference_token = reference_string.substr(start, slash - start);
  7826. // check reference tokens are properly escaped
  7827. for (std::size_t pos = reference_token.find_first_of('~');
  7828. pos != std::string::npos;
  7829. pos = reference_token.find_first_of('~', pos + 1))
  7830. {
  7831. assert(reference_token[pos] == '~');
  7832. // ~ must be followed by 0 or 1
  7833. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  7834. (reference_token[pos + 1] != '0' and
  7835. reference_token[pos + 1] != '1')))
  7836. {
  7837. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  7838. }
  7839. }
  7840. // finally, store the reference token
  7841. unescape(reference_token);
  7842. result.push_back(reference_token);
  7843. }
  7844. return result;
  7845. }
  7846. /*!
  7847. @brief replace all occurrences of a substring by another string
  7848. @param[in,out] s the string to manipulate; changed so that all
  7849. occurrences of @a f are replaced with @a t
  7850. @param[in] f the substring to replace with @a t
  7851. @param[in] t the string to replace @a f
  7852. @pre The search string @a f must not be empty. **This precondition is
  7853. enforced with an assertion.**
  7854. @since version 2.0.0
  7855. */
  7856. static void replace_substring(std::string& s, const std::string& f,
  7857. const std::string& t)
  7858. {
  7859. assert(not f.empty());
  7860. for (auto pos = s.find(f); // find first occurrence of f
  7861. pos != std::string::npos; // make sure f was found
  7862. s.replace(pos, f.size(), t), // replace with t, and
  7863. pos = s.find(f, pos + t.size())) // find next occurrence of f
  7864. {}
  7865. }
  7866. /// escape "~" to "~0" and "/" to "~1"
  7867. static std::string escape(std::string s)
  7868. {
  7869. replace_substring(s, "~", "~0");
  7870. replace_substring(s, "/", "~1");
  7871. return s;
  7872. }
  7873. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  7874. static void unescape(std::string& s)
  7875. {
  7876. replace_substring(s, "~1", "/");
  7877. replace_substring(s, "~0", "~");
  7878. }
  7879. /*!
  7880. @param[in] reference_string the reference string to the current value
  7881. @param[in] value the value to consider
  7882. @param[in,out] result the result object to insert values to
  7883. @note Empty objects or arrays are flattened to `null`.
  7884. */
  7885. static void flatten(const std::string& reference_string,
  7886. const BasicJsonType& value,
  7887. BasicJsonType& result)
  7888. {
  7889. switch (value.m_type)
  7890. {
  7891. case detail::value_t::array:
  7892. {
  7893. if (value.m_value.array->empty())
  7894. {
  7895. // flatten empty array as null
  7896. result[reference_string] = nullptr;
  7897. }
  7898. else
  7899. {
  7900. // iterate array and use index as reference string
  7901. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  7902. {
  7903. flatten(reference_string + "/" + std::to_string(i),
  7904. value.m_value.array->operator[](i), result);
  7905. }
  7906. }
  7907. break;
  7908. }
  7909. case detail::value_t::object:
  7910. {
  7911. if (value.m_value.object->empty())
  7912. {
  7913. // flatten empty object as null
  7914. result[reference_string] = nullptr;
  7915. }
  7916. else
  7917. {
  7918. // iterate object and use keys as reference string
  7919. for (const auto& element : *value.m_value.object)
  7920. {
  7921. flatten(reference_string + "/" + escape(element.first), element.second, result);
  7922. }
  7923. }
  7924. break;
  7925. }
  7926. default:
  7927. {
  7928. // add primitive value with its reference string
  7929. result[reference_string] = value;
  7930. break;
  7931. }
  7932. }
  7933. }
  7934. /*!
  7935. @param[in] value flattened JSON
  7936. @return unflattened JSON
  7937. @throw parse_error.109 if array index is not a number
  7938. @throw type_error.314 if value is not an object
  7939. @throw type_error.315 if object values are not primitive
  7940. @throw type_error.313 if value cannot be unflattened
  7941. */
  7942. static BasicJsonType
  7943. unflatten(const BasicJsonType& value)
  7944. {
  7945. if (JSON_UNLIKELY(not value.is_object()))
  7946. {
  7947. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  7948. }
  7949. BasicJsonType result;
  7950. // iterate the JSON object values
  7951. for (const auto& element : *value.m_value.object)
  7952. {
  7953. if (JSON_UNLIKELY(not element.second.is_primitive()))
  7954. {
  7955. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  7956. }
  7957. // assign value to reference pointed to by JSON pointer; Note that if
  7958. // the JSON pointer is "" (i.e., points to the whole value), function
  7959. // get_and_create returns a reference to result itself. An assignment
  7960. // will then create a primitive value.
  7961. json_pointer(element.first).get_and_create(result) = element.second;
  7962. }
  7963. return result;
  7964. }
  7965. /*!
  7966. @brief compares two JSON pointers for equality
  7967. @param[in] lhs JSON pointer to compare
  7968. @param[in] rhs JSON pointer to compare
  7969. @return whether @a lhs is equal to @a rhs
  7970. @complexity Linear in the length of the JSON pointer
  7971. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  7972. */
  7973. friend bool operator==(json_pointer const& lhs,
  7974. json_pointer const& rhs) noexcept
  7975. {
  7976. return lhs.reference_tokens == rhs.reference_tokens;
  7977. }
  7978. /*!
  7979. @brief compares two JSON pointers for inequality
  7980. @param[in] lhs JSON pointer to compare
  7981. @param[in] rhs JSON pointer to compare
  7982. @return whether @a lhs is not equal @a rhs
  7983. @complexity Linear in the length of the JSON pointer
  7984. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  7985. */
  7986. friend bool operator!=(json_pointer const& lhs,
  7987. json_pointer const& rhs) noexcept
  7988. {
  7989. return not (lhs == rhs);
  7990. }
  7991. /// the reference tokens
  7992. std::vector<std::string> reference_tokens;
  7993. };
  7994. } // namespace nlohmann
  7995. // #include <nlohmann/detail/json_ref.hpp>
  7996. #include <initializer_list>
  7997. #include <utility>
  7998. // #include <nlohmann/detail/meta/type_traits.hpp>
  7999. namespace nlohmann
  8000. {
  8001. namespace detail
  8002. {
  8003. template<typename BasicJsonType>
  8004. class json_ref
  8005. {
  8006. public:
  8007. using value_type = BasicJsonType;
  8008. json_ref(value_type&& value)
  8009. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  8010. {}
  8011. json_ref(const value_type& value)
  8012. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  8013. {}
  8014. json_ref(std::initializer_list<json_ref> init)
  8015. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  8016. {}
  8017. template <
  8018. class... Args,
  8019. enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 >
  8020. json_ref(Args && ... args)
  8021. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value),
  8022. is_rvalue(true) {}
  8023. // class should be movable only
  8024. json_ref(json_ref&&) = default;
  8025. json_ref(const json_ref&) = delete;
  8026. json_ref& operator=(const json_ref&) = delete;
  8027. json_ref& operator=(json_ref&&) = delete;
  8028. ~json_ref() = default;
  8029. value_type moved_or_copied() const
  8030. {
  8031. if (is_rvalue)
  8032. {
  8033. return std::move(*value_ref);
  8034. }
  8035. return *value_ref;
  8036. }
  8037. value_type const& operator*() const
  8038. {
  8039. return *static_cast<value_type const*>(value_ref);
  8040. }
  8041. value_type const* operator->() const
  8042. {
  8043. return static_cast<value_type const*>(value_ref);
  8044. }
  8045. private:
  8046. mutable value_type owned_value = nullptr;
  8047. value_type* value_ref = nullptr;
  8048. const bool is_rvalue;
  8049. };
  8050. } // namespace detail
  8051. } // namespace nlohmann
  8052. // #include <nlohmann/detail/macro_scope.hpp>
  8053. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8054. // #include <nlohmann/detail/meta/type_traits.hpp>
  8055. // #include <nlohmann/detail/output/binary_writer.hpp>
  8056. #include <algorithm> // reverse
  8057. #include <array> // array
  8058. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  8059. #include <cstring> // memcpy
  8060. #include <limits> // numeric_limits
  8061. #include <string> // string
  8062. // #include <nlohmann/detail/input/binary_reader.hpp>
  8063. // #include <nlohmann/detail/output/output_adapters.hpp>
  8064. #include <algorithm> // copy
  8065. #include <cstddef> // size_t
  8066. #include <ios> // streamsize
  8067. #include <iterator> // back_inserter
  8068. #include <memory> // shared_ptr, make_shared
  8069. #include <ostream> // basic_ostream
  8070. #include <string> // basic_string
  8071. #include <vector> // vector
  8072. namespace nlohmann
  8073. {
  8074. namespace detail
  8075. {
  8076. /// abstract output adapter interface
  8077. template<typename CharType> struct output_adapter_protocol
  8078. {
  8079. virtual void write_character(CharType c) = 0;
  8080. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  8081. virtual ~output_adapter_protocol() = default;
  8082. };
  8083. /// a type to simplify interfaces
  8084. template<typename CharType>
  8085. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  8086. /// output adapter for byte vectors
  8087. template<typename CharType>
  8088. class output_vector_adapter : public output_adapter_protocol<CharType>
  8089. {
  8090. public:
  8091. explicit output_vector_adapter(std::vector<CharType>& vec) noexcept
  8092. : v(vec)
  8093. {}
  8094. void write_character(CharType c) override
  8095. {
  8096. v.push_back(c);
  8097. }
  8098. void write_characters(const CharType* s, std::size_t length) override
  8099. {
  8100. std::copy(s, s + length, std::back_inserter(v));
  8101. }
  8102. private:
  8103. std::vector<CharType>& v;
  8104. };
  8105. /// output adapter for output streams
  8106. template<typename CharType>
  8107. class output_stream_adapter : public output_adapter_protocol<CharType>
  8108. {
  8109. public:
  8110. explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept
  8111. : stream(s)
  8112. {}
  8113. void write_character(CharType c) override
  8114. {
  8115. stream.put(c);
  8116. }
  8117. void write_characters(const CharType* s, std::size_t length) override
  8118. {
  8119. stream.write(s, static_cast<std::streamsize>(length));
  8120. }
  8121. private:
  8122. std::basic_ostream<CharType>& stream;
  8123. };
  8124. /// output adapter for basic_string
  8125. template<typename CharType, typename StringType = std::basic_string<CharType>>
  8126. class output_string_adapter : public output_adapter_protocol<CharType>
  8127. {
  8128. public:
  8129. explicit output_string_adapter(StringType& s) noexcept
  8130. : str(s)
  8131. {}
  8132. void write_character(CharType c) override
  8133. {
  8134. str.push_back(c);
  8135. }
  8136. void write_characters(const CharType* s, std::size_t length) override
  8137. {
  8138. str.append(s, length);
  8139. }
  8140. private:
  8141. StringType& str;
  8142. };
  8143. template<typename CharType, typename StringType = std::basic_string<CharType>>
  8144. class output_adapter
  8145. {
  8146. public:
  8147. output_adapter(std::vector<CharType>& vec)
  8148. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  8149. output_adapter(std::basic_ostream<CharType>& s)
  8150. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  8151. output_adapter(StringType& s)
  8152. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  8153. operator output_adapter_t<CharType>()
  8154. {
  8155. return oa;
  8156. }
  8157. private:
  8158. output_adapter_t<CharType> oa = nullptr;
  8159. };
  8160. } // namespace detail
  8161. } // namespace nlohmann
  8162. namespace nlohmann
  8163. {
  8164. namespace detail
  8165. {
  8166. ///////////////////
  8167. // binary writer //
  8168. ///////////////////
  8169. /*!
  8170. @brief serialization to CBOR and MessagePack values
  8171. */
  8172. template<typename BasicJsonType, typename CharType>
  8173. class binary_writer
  8174. {
  8175. using string_t = typename BasicJsonType::string_t;
  8176. public:
  8177. /*!
  8178. @brief create a binary writer
  8179. @param[in] adapter output adapter to write to
  8180. */
  8181. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  8182. {
  8183. assert(oa);
  8184. }
  8185. /*!
  8186. @param[in] j JSON value to serialize
  8187. @pre j.type() == value_t::object
  8188. */
  8189. void write_bson(const BasicJsonType& j)
  8190. {
  8191. switch (j.type())
  8192. {
  8193. case value_t::object:
  8194. {
  8195. write_bson_object(*j.m_value.object);
  8196. break;
  8197. }
  8198. default:
  8199. {
  8200. JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name())));
  8201. }
  8202. }
  8203. }
  8204. /*!
  8205. @param[in] j JSON value to serialize
  8206. */
  8207. void write_cbor(const BasicJsonType& j)
  8208. {
  8209. switch (j.type())
  8210. {
  8211. case value_t::null:
  8212. {
  8213. oa->write_character(to_char_type(0xF6));
  8214. break;
  8215. }
  8216. case value_t::boolean:
  8217. {
  8218. oa->write_character(j.m_value.boolean
  8219. ? to_char_type(0xF5)
  8220. : to_char_type(0xF4));
  8221. break;
  8222. }
  8223. case value_t::number_integer:
  8224. {
  8225. if (j.m_value.number_integer >= 0)
  8226. {
  8227. // CBOR does not differentiate between positive signed
  8228. // integers and unsigned integers. Therefore, we used the
  8229. // code from the value_t::number_unsigned case here.
  8230. if (j.m_value.number_integer <= 0x17)
  8231. {
  8232. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8233. }
  8234. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  8235. {
  8236. oa->write_character(to_char_type(0x18));
  8237. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8238. }
  8239. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint16_t>::max)())
  8240. {
  8241. oa->write_character(to_char_type(0x19));
  8242. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8243. }
  8244. else if (j.m_value.number_integer <= (std::numeric_limits<std::uint32_t>::max)())
  8245. {
  8246. oa->write_character(to_char_type(0x1A));
  8247. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8248. }
  8249. else
  8250. {
  8251. oa->write_character(to_char_type(0x1B));
  8252. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8253. }
  8254. }
  8255. else
  8256. {
  8257. // The conversions below encode the sign in the first
  8258. // byte, and the value is converted to a positive number.
  8259. const auto positive_number = -1 - j.m_value.number_integer;
  8260. if (j.m_value.number_integer >= -24)
  8261. {
  8262. write_number(static_cast<std::uint8_t>(0x20 + positive_number));
  8263. }
  8264. else if (positive_number <= (std::numeric_limits<std::uint8_t>::max)())
  8265. {
  8266. oa->write_character(to_char_type(0x38));
  8267. write_number(static_cast<std::uint8_t>(positive_number));
  8268. }
  8269. else if (positive_number <= (std::numeric_limits<std::uint16_t>::max)())
  8270. {
  8271. oa->write_character(to_char_type(0x39));
  8272. write_number(static_cast<std::uint16_t>(positive_number));
  8273. }
  8274. else if (positive_number <= (std::numeric_limits<std::uint32_t>::max)())
  8275. {
  8276. oa->write_character(to_char_type(0x3A));
  8277. write_number(static_cast<std::uint32_t>(positive_number));
  8278. }
  8279. else
  8280. {
  8281. oa->write_character(to_char_type(0x3B));
  8282. write_number(static_cast<std::uint64_t>(positive_number));
  8283. }
  8284. }
  8285. break;
  8286. }
  8287. case value_t::number_unsigned:
  8288. {
  8289. if (j.m_value.number_unsigned <= 0x17)
  8290. {
  8291. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  8292. }
  8293. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8294. {
  8295. oa->write_character(to_char_type(0x18));
  8296. write_number(static_cast<std::uint8_t>(j.m_value.number_unsigned));
  8297. }
  8298. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8299. {
  8300. oa->write_character(to_char_type(0x19));
  8301. write_number(static_cast<std::uint16_t>(j.m_value.number_unsigned));
  8302. }
  8303. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8304. {
  8305. oa->write_character(to_char_type(0x1A));
  8306. write_number(static_cast<std::uint32_t>(j.m_value.number_unsigned));
  8307. }
  8308. else
  8309. {
  8310. oa->write_character(to_char_type(0x1B));
  8311. write_number(static_cast<std::uint64_t>(j.m_value.number_unsigned));
  8312. }
  8313. break;
  8314. }
  8315. case value_t::number_float:
  8316. {
  8317. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  8318. write_number(j.m_value.number_float);
  8319. break;
  8320. }
  8321. case value_t::string:
  8322. {
  8323. // step 1: write control byte and the string length
  8324. const auto N = j.m_value.string->size();
  8325. if (N <= 0x17)
  8326. {
  8327. write_number(static_cast<std::uint8_t>(0x60 + N));
  8328. }
  8329. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8330. {
  8331. oa->write_character(to_char_type(0x78));
  8332. write_number(static_cast<std::uint8_t>(N));
  8333. }
  8334. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8335. {
  8336. oa->write_character(to_char_type(0x79));
  8337. write_number(static_cast<std::uint16_t>(N));
  8338. }
  8339. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8340. {
  8341. oa->write_character(to_char_type(0x7A));
  8342. write_number(static_cast<std::uint32_t>(N));
  8343. }
  8344. // LCOV_EXCL_START
  8345. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8346. {
  8347. oa->write_character(to_char_type(0x7B));
  8348. write_number(static_cast<std::uint64_t>(N));
  8349. }
  8350. // LCOV_EXCL_STOP
  8351. // step 2: write the string
  8352. oa->write_characters(
  8353. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8354. j.m_value.string->size());
  8355. break;
  8356. }
  8357. case value_t::array:
  8358. {
  8359. // step 1: write control byte and the array size
  8360. const auto N = j.m_value.array->size();
  8361. if (N <= 0x17)
  8362. {
  8363. write_number(static_cast<std::uint8_t>(0x80 + N));
  8364. }
  8365. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8366. {
  8367. oa->write_character(to_char_type(0x98));
  8368. write_number(static_cast<std::uint8_t>(N));
  8369. }
  8370. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8371. {
  8372. oa->write_character(to_char_type(0x99));
  8373. write_number(static_cast<std::uint16_t>(N));
  8374. }
  8375. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8376. {
  8377. oa->write_character(to_char_type(0x9A));
  8378. write_number(static_cast<std::uint32_t>(N));
  8379. }
  8380. // LCOV_EXCL_START
  8381. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8382. {
  8383. oa->write_character(to_char_type(0x9B));
  8384. write_number(static_cast<std::uint64_t>(N));
  8385. }
  8386. // LCOV_EXCL_STOP
  8387. // step 2: write each element
  8388. for (const auto& el : *j.m_value.array)
  8389. {
  8390. write_cbor(el);
  8391. }
  8392. break;
  8393. }
  8394. case value_t::object:
  8395. {
  8396. // step 1: write control byte and the object size
  8397. const auto N = j.m_value.object->size();
  8398. if (N <= 0x17)
  8399. {
  8400. write_number(static_cast<std::uint8_t>(0xA0 + N));
  8401. }
  8402. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8403. {
  8404. oa->write_character(to_char_type(0xB8));
  8405. write_number(static_cast<std::uint8_t>(N));
  8406. }
  8407. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8408. {
  8409. oa->write_character(to_char_type(0xB9));
  8410. write_number(static_cast<std::uint16_t>(N));
  8411. }
  8412. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8413. {
  8414. oa->write_character(to_char_type(0xBA));
  8415. write_number(static_cast<std::uint32_t>(N));
  8416. }
  8417. // LCOV_EXCL_START
  8418. else if (N <= (std::numeric_limits<std::uint64_t>::max)())
  8419. {
  8420. oa->write_character(to_char_type(0xBB));
  8421. write_number(static_cast<std::uint64_t>(N));
  8422. }
  8423. // LCOV_EXCL_STOP
  8424. // step 2: write each element
  8425. for (const auto& el : *j.m_value.object)
  8426. {
  8427. write_cbor(el.first);
  8428. write_cbor(el.second);
  8429. }
  8430. break;
  8431. }
  8432. default:
  8433. break;
  8434. }
  8435. }
  8436. /*!
  8437. @param[in] j JSON value to serialize
  8438. */
  8439. void write_msgpack(const BasicJsonType& j)
  8440. {
  8441. switch (j.type())
  8442. {
  8443. case value_t::null: // nil
  8444. {
  8445. oa->write_character(to_char_type(0xC0));
  8446. break;
  8447. }
  8448. case value_t::boolean: // true and false
  8449. {
  8450. oa->write_character(j.m_value.boolean
  8451. ? to_char_type(0xC3)
  8452. : to_char_type(0xC2));
  8453. break;
  8454. }
  8455. case value_t::number_integer:
  8456. {
  8457. if (j.m_value.number_integer >= 0)
  8458. {
  8459. // MessagePack does not differentiate between positive
  8460. // signed integers and unsigned integers. Therefore, we used
  8461. // the code from the value_t::number_unsigned case here.
  8462. if (j.m_value.number_unsigned < 128)
  8463. {
  8464. // positive fixnum
  8465. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8466. }
  8467. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8468. {
  8469. // uint 8
  8470. oa->write_character(to_char_type(0xCC));
  8471. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8472. }
  8473. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8474. {
  8475. // uint 16
  8476. oa->write_character(to_char_type(0xCD));
  8477. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8478. }
  8479. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8480. {
  8481. // uint 32
  8482. oa->write_character(to_char_type(0xCE));
  8483. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8484. }
  8485. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  8486. {
  8487. // uint 64
  8488. oa->write_character(to_char_type(0xCF));
  8489. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8490. }
  8491. }
  8492. else
  8493. {
  8494. if (j.m_value.number_integer >= -32)
  8495. {
  8496. // negative fixnum
  8497. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  8498. }
  8499. else if (j.m_value.number_integer >= (std::numeric_limits<std::int8_t>::min)() and
  8500. j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  8501. {
  8502. // int 8
  8503. oa->write_character(to_char_type(0xD0));
  8504. write_number(static_cast<std::int8_t>(j.m_value.number_integer));
  8505. }
  8506. else if (j.m_value.number_integer >= (std::numeric_limits<std::int16_t>::min)() and
  8507. j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  8508. {
  8509. // int 16
  8510. oa->write_character(to_char_type(0xD1));
  8511. write_number(static_cast<std::int16_t>(j.m_value.number_integer));
  8512. }
  8513. else if (j.m_value.number_integer >= (std::numeric_limits<std::int32_t>::min)() and
  8514. j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  8515. {
  8516. // int 32
  8517. oa->write_character(to_char_type(0xD2));
  8518. write_number(static_cast<std::int32_t>(j.m_value.number_integer));
  8519. }
  8520. else if (j.m_value.number_integer >= (std::numeric_limits<std::int64_t>::min)() and
  8521. j.m_value.number_integer <= (std::numeric_limits<std::int64_t>::max)())
  8522. {
  8523. // int 64
  8524. oa->write_character(to_char_type(0xD3));
  8525. write_number(static_cast<std::int64_t>(j.m_value.number_integer));
  8526. }
  8527. }
  8528. break;
  8529. }
  8530. case value_t::number_unsigned:
  8531. {
  8532. if (j.m_value.number_unsigned < 128)
  8533. {
  8534. // positive fixnum
  8535. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8536. }
  8537. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  8538. {
  8539. // uint 8
  8540. oa->write_character(to_char_type(0xCC));
  8541. write_number(static_cast<std::uint8_t>(j.m_value.number_integer));
  8542. }
  8543. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint16_t>::max)())
  8544. {
  8545. // uint 16
  8546. oa->write_character(to_char_type(0xCD));
  8547. write_number(static_cast<std::uint16_t>(j.m_value.number_integer));
  8548. }
  8549. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint32_t>::max)())
  8550. {
  8551. // uint 32
  8552. oa->write_character(to_char_type(0xCE));
  8553. write_number(static_cast<std::uint32_t>(j.m_value.number_integer));
  8554. }
  8555. else if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint64_t>::max)())
  8556. {
  8557. // uint 64
  8558. oa->write_character(to_char_type(0xCF));
  8559. write_number(static_cast<std::uint64_t>(j.m_value.number_integer));
  8560. }
  8561. break;
  8562. }
  8563. case value_t::number_float:
  8564. {
  8565. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  8566. write_number(j.m_value.number_float);
  8567. break;
  8568. }
  8569. case value_t::string:
  8570. {
  8571. // step 1: write control byte and the string length
  8572. const auto N = j.m_value.string->size();
  8573. if (N <= 31)
  8574. {
  8575. // fixstr
  8576. write_number(static_cast<std::uint8_t>(0xA0 | N));
  8577. }
  8578. else if (N <= (std::numeric_limits<std::uint8_t>::max)())
  8579. {
  8580. // str 8
  8581. oa->write_character(to_char_type(0xD9));
  8582. write_number(static_cast<std::uint8_t>(N));
  8583. }
  8584. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8585. {
  8586. // str 16
  8587. oa->write_character(to_char_type(0xDA));
  8588. write_number(static_cast<std::uint16_t>(N));
  8589. }
  8590. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8591. {
  8592. // str 32
  8593. oa->write_character(to_char_type(0xDB));
  8594. write_number(static_cast<std::uint32_t>(N));
  8595. }
  8596. // step 2: write the string
  8597. oa->write_characters(
  8598. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8599. j.m_value.string->size());
  8600. break;
  8601. }
  8602. case value_t::array:
  8603. {
  8604. // step 1: write control byte and the array size
  8605. const auto N = j.m_value.array->size();
  8606. if (N <= 15)
  8607. {
  8608. // fixarray
  8609. write_number(static_cast<std::uint8_t>(0x90 | N));
  8610. }
  8611. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8612. {
  8613. // array 16
  8614. oa->write_character(to_char_type(0xDC));
  8615. write_number(static_cast<std::uint16_t>(N));
  8616. }
  8617. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8618. {
  8619. // array 32
  8620. oa->write_character(to_char_type(0xDD));
  8621. write_number(static_cast<std::uint32_t>(N));
  8622. }
  8623. // step 2: write each element
  8624. for (const auto& el : *j.m_value.array)
  8625. {
  8626. write_msgpack(el);
  8627. }
  8628. break;
  8629. }
  8630. case value_t::object:
  8631. {
  8632. // step 1: write control byte and the object size
  8633. const auto N = j.m_value.object->size();
  8634. if (N <= 15)
  8635. {
  8636. // fixmap
  8637. write_number(static_cast<std::uint8_t>(0x80 | (N & 0xF)));
  8638. }
  8639. else if (N <= (std::numeric_limits<std::uint16_t>::max)())
  8640. {
  8641. // map 16
  8642. oa->write_character(to_char_type(0xDE));
  8643. write_number(static_cast<std::uint16_t>(N));
  8644. }
  8645. else if (N <= (std::numeric_limits<std::uint32_t>::max)())
  8646. {
  8647. // map 32
  8648. oa->write_character(to_char_type(0xDF));
  8649. write_number(static_cast<std::uint32_t>(N));
  8650. }
  8651. // step 2: write each element
  8652. for (const auto& el : *j.m_value.object)
  8653. {
  8654. write_msgpack(el.first);
  8655. write_msgpack(el.second);
  8656. }
  8657. break;
  8658. }
  8659. default:
  8660. break;
  8661. }
  8662. }
  8663. /*!
  8664. @param[in] j JSON value to serialize
  8665. @param[in] use_count whether to use '#' prefixes (optimized format)
  8666. @param[in] use_type whether to use '$' prefixes (optimized format)
  8667. @param[in] add_prefix whether prefixes need to be used for this value
  8668. */
  8669. void write_ubjson(const BasicJsonType& j, const bool use_count,
  8670. const bool use_type, const bool add_prefix = true)
  8671. {
  8672. switch (j.type())
  8673. {
  8674. case value_t::null:
  8675. {
  8676. if (add_prefix)
  8677. {
  8678. oa->write_character(to_char_type('Z'));
  8679. }
  8680. break;
  8681. }
  8682. case value_t::boolean:
  8683. {
  8684. if (add_prefix)
  8685. {
  8686. oa->write_character(j.m_value.boolean
  8687. ? to_char_type('T')
  8688. : to_char_type('F'));
  8689. }
  8690. break;
  8691. }
  8692. case value_t::number_integer:
  8693. {
  8694. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  8695. break;
  8696. }
  8697. case value_t::number_unsigned:
  8698. {
  8699. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  8700. break;
  8701. }
  8702. case value_t::number_float:
  8703. {
  8704. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  8705. break;
  8706. }
  8707. case value_t::string:
  8708. {
  8709. if (add_prefix)
  8710. {
  8711. oa->write_character(to_char_type('S'));
  8712. }
  8713. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  8714. oa->write_characters(
  8715. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  8716. j.m_value.string->size());
  8717. break;
  8718. }
  8719. case value_t::array:
  8720. {
  8721. if (add_prefix)
  8722. {
  8723. oa->write_character(to_char_type('['));
  8724. }
  8725. bool prefix_required = true;
  8726. if (use_type and not j.m_value.array->empty())
  8727. {
  8728. assert(use_count);
  8729. const CharType first_prefix = ubjson_prefix(j.front());
  8730. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  8731. [this, first_prefix](const BasicJsonType & v)
  8732. {
  8733. return ubjson_prefix(v) == first_prefix;
  8734. });
  8735. if (same_prefix)
  8736. {
  8737. prefix_required = false;
  8738. oa->write_character(to_char_type('$'));
  8739. oa->write_character(first_prefix);
  8740. }
  8741. }
  8742. if (use_count)
  8743. {
  8744. oa->write_character(to_char_type('#'));
  8745. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  8746. }
  8747. for (const auto& el : *j.m_value.array)
  8748. {
  8749. write_ubjson(el, use_count, use_type, prefix_required);
  8750. }
  8751. if (not use_count)
  8752. {
  8753. oa->write_character(to_char_type(']'));
  8754. }
  8755. break;
  8756. }
  8757. case value_t::object:
  8758. {
  8759. if (add_prefix)
  8760. {
  8761. oa->write_character(to_char_type('{'));
  8762. }
  8763. bool prefix_required = true;
  8764. if (use_type and not j.m_value.object->empty())
  8765. {
  8766. assert(use_count);
  8767. const CharType first_prefix = ubjson_prefix(j.front());
  8768. const bool same_prefix = std::all_of(j.begin(), j.end(),
  8769. [this, first_prefix](const BasicJsonType & v)
  8770. {
  8771. return ubjson_prefix(v) == first_prefix;
  8772. });
  8773. if (same_prefix)
  8774. {
  8775. prefix_required = false;
  8776. oa->write_character(to_char_type('$'));
  8777. oa->write_character(first_prefix);
  8778. }
  8779. }
  8780. if (use_count)
  8781. {
  8782. oa->write_character(to_char_type('#'));
  8783. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  8784. }
  8785. for (const auto& el : *j.m_value.object)
  8786. {
  8787. write_number_with_ubjson_prefix(el.first.size(), true);
  8788. oa->write_characters(
  8789. reinterpret_cast<const CharType*>(el.first.c_str()),
  8790. el.first.size());
  8791. write_ubjson(el.second, use_count, use_type, prefix_required);
  8792. }
  8793. if (not use_count)
  8794. {
  8795. oa->write_character(to_char_type('}'));
  8796. }
  8797. break;
  8798. }
  8799. default:
  8800. break;
  8801. }
  8802. }
  8803. private:
  8804. //////////
  8805. // BSON //
  8806. //////////
  8807. /*!
  8808. @return The size of a BSON document entry header, including the id marker
  8809. and the entry name size (and its null-terminator).
  8810. */
  8811. static std::size_t calc_bson_entry_header_size(const string_t& name)
  8812. {
  8813. const auto it = name.find(static_cast<typename string_t::value_type>(0));
  8814. if (JSON_UNLIKELY(it != BasicJsonType::string_t::npos))
  8815. {
  8816. JSON_THROW(out_of_range::create(409,
  8817. "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")"));
  8818. }
  8819. return /*id*/ 1ul + name.size() + /*zero-terminator*/1u;
  8820. }
  8821. /*!
  8822. @brief Writes the given @a element_type and @a name to the output adapter
  8823. */
  8824. void write_bson_entry_header(const string_t& name,
  8825. const std::uint8_t element_type)
  8826. {
  8827. oa->write_character(to_char_type(element_type)); // boolean
  8828. oa->write_characters(
  8829. reinterpret_cast<const CharType*>(name.c_str()),
  8830. name.size() + 1u);
  8831. }
  8832. /*!
  8833. @brief Writes a BSON element with key @a name and boolean value @a value
  8834. */
  8835. void write_bson_boolean(const string_t& name,
  8836. const bool value)
  8837. {
  8838. write_bson_entry_header(name, 0x08);
  8839. oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00));
  8840. }
  8841. /*!
  8842. @brief Writes a BSON element with key @a name and double value @a value
  8843. */
  8844. void write_bson_double(const string_t& name,
  8845. const double value)
  8846. {
  8847. write_bson_entry_header(name, 0x01);
  8848. write_number<double, true>(value);
  8849. }
  8850. /*!
  8851. @return The size of the BSON-encoded string in @a value
  8852. */
  8853. static std::size_t calc_bson_string_size(const string_t& value)
  8854. {
  8855. return sizeof(std::int32_t) + value.size() + 1ul;
  8856. }
  8857. /*!
  8858. @brief Writes a BSON element with key @a name and string value @a value
  8859. */
  8860. void write_bson_string(const string_t& name,
  8861. const string_t& value)
  8862. {
  8863. write_bson_entry_header(name, 0x02);
  8864. write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul));
  8865. oa->write_characters(
  8866. reinterpret_cast<const CharType*>(value.c_str()),
  8867. value.size() + 1);
  8868. }
  8869. /*!
  8870. @brief Writes a BSON element with key @a name and null value
  8871. */
  8872. void write_bson_null(const string_t& name)
  8873. {
  8874. write_bson_entry_header(name, 0x0A);
  8875. }
  8876. /*!
  8877. @return The size of the BSON-encoded integer @a value
  8878. */
  8879. static std::size_t calc_bson_integer_size(const std::int64_t value)
  8880. {
  8881. return (std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()
  8882. ? sizeof(std::int32_t)
  8883. : sizeof(std::int64_t);
  8884. }
  8885. /*!
  8886. @brief Writes a BSON element with key @a name and integer @a value
  8887. */
  8888. void write_bson_integer(const string_t& name,
  8889. const std::int64_t value)
  8890. {
  8891. if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)())
  8892. {
  8893. write_bson_entry_header(name, 0x10); // int32
  8894. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8895. }
  8896. else
  8897. {
  8898. write_bson_entry_header(name, 0x12); // int64
  8899. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8900. }
  8901. }
  8902. /*!
  8903. @return The size of the BSON-encoded unsigned integer in @a j
  8904. */
  8905. static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept
  8906. {
  8907. return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8908. ? sizeof(std::int32_t)
  8909. : sizeof(std::int64_t);
  8910. }
  8911. /*!
  8912. @brief Writes a BSON element with key @a name and unsigned @a value
  8913. */
  8914. void write_bson_unsigned(const string_t& name,
  8915. const std::uint64_t value)
  8916. {
  8917. if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  8918. {
  8919. write_bson_entry_header(name, 0x10 /* int32 */);
  8920. write_number<std::int32_t, true>(static_cast<std::int32_t>(value));
  8921. }
  8922. else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  8923. {
  8924. write_bson_entry_header(name, 0x12 /* int64 */);
  8925. write_number<std::int64_t, true>(static_cast<std::int64_t>(value));
  8926. }
  8927. else
  8928. {
  8929. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64"));
  8930. }
  8931. }
  8932. /*!
  8933. @brief Writes a BSON element with key @a name and object @a value
  8934. */
  8935. void write_bson_object_entry(const string_t& name,
  8936. const typename BasicJsonType::object_t& value)
  8937. {
  8938. write_bson_entry_header(name, 0x03); // object
  8939. write_bson_object(value);
  8940. }
  8941. /*!
  8942. @return The size of the BSON-encoded array @a value
  8943. */
  8944. static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value)
  8945. {
  8946. std::size_t embedded_document_size = 0ul;
  8947. std::size_t array_index = 0ul;
  8948. for (const auto& el : value)
  8949. {
  8950. embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el);
  8951. }
  8952. return sizeof(std::int32_t) + embedded_document_size + 1ul;
  8953. }
  8954. /*!
  8955. @brief Writes a BSON element with key @a name and array @a value
  8956. */
  8957. void write_bson_array(const string_t& name,
  8958. const typename BasicJsonType::array_t& value)
  8959. {
  8960. write_bson_entry_header(name, 0x04); // array
  8961. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value)));
  8962. std::size_t array_index = 0ul;
  8963. for (const auto& el : value)
  8964. {
  8965. write_bson_element(std::to_string(array_index++), el);
  8966. }
  8967. oa->write_character(to_char_type(0x00));
  8968. }
  8969. /*!
  8970. @brief Calculates the size necessary to serialize the JSON value @a j with its @a name
  8971. @return The calculated size for the BSON document entry for @a j with the given @a name.
  8972. */
  8973. static std::size_t calc_bson_element_size(const string_t& name,
  8974. const BasicJsonType& j)
  8975. {
  8976. const auto header_size = calc_bson_entry_header_size(name);
  8977. switch (j.type())
  8978. {
  8979. case value_t::object:
  8980. return header_size + calc_bson_object_size(*j.m_value.object);
  8981. case value_t::array:
  8982. return header_size + calc_bson_array_size(*j.m_value.array);
  8983. case value_t::boolean:
  8984. return header_size + 1ul;
  8985. case value_t::number_float:
  8986. return header_size + 8ul;
  8987. case value_t::number_integer:
  8988. return header_size + calc_bson_integer_size(j.m_value.number_integer);
  8989. case value_t::number_unsigned:
  8990. return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned);
  8991. case value_t::string:
  8992. return header_size + calc_bson_string_size(*j.m_value.string);
  8993. case value_t::null:
  8994. return header_size + 0ul;
  8995. // LCOV_EXCL_START
  8996. default:
  8997. assert(false);
  8998. return 0ul;
  8999. // LCOV_EXCL_STOP
  9000. }
  9001. }
  9002. /*!
  9003. @brief Serializes the JSON value @a j to BSON and associates it with the
  9004. key @a name.
  9005. @param name The name to associate with the JSON entity @a j within the
  9006. current BSON document
  9007. @return The size of the BSON entry
  9008. */
  9009. void write_bson_element(const string_t& name,
  9010. const BasicJsonType& j)
  9011. {
  9012. switch (j.type())
  9013. {
  9014. case value_t::object:
  9015. return write_bson_object_entry(name, *j.m_value.object);
  9016. case value_t::array:
  9017. return write_bson_array(name, *j.m_value.array);
  9018. case value_t::boolean:
  9019. return write_bson_boolean(name, j.m_value.boolean);
  9020. case value_t::number_float:
  9021. return write_bson_double(name, j.m_value.number_float);
  9022. case value_t::number_integer:
  9023. return write_bson_integer(name, j.m_value.number_integer);
  9024. case value_t::number_unsigned:
  9025. return write_bson_unsigned(name, j.m_value.number_unsigned);
  9026. case value_t::string:
  9027. return write_bson_string(name, *j.m_value.string);
  9028. case value_t::null:
  9029. return write_bson_null(name);
  9030. // LCOV_EXCL_START
  9031. default:
  9032. assert(false);
  9033. return;
  9034. // LCOV_EXCL_STOP
  9035. }
  9036. }
  9037. /*!
  9038. @brief Calculates the size of the BSON serialization of the given
  9039. JSON-object @a j.
  9040. @param[in] j JSON value to serialize
  9041. @pre j.type() == value_t::object
  9042. */
  9043. static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value)
  9044. {
  9045. std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul,
  9046. [](size_t result, const typename BasicJsonType::object_t::value_type & el)
  9047. {
  9048. return result += calc_bson_element_size(el.first, el.second);
  9049. });
  9050. return sizeof(std::int32_t) + document_size + 1ul;
  9051. }
  9052. /*!
  9053. @param[in] j JSON value to serialize
  9054. @pre j.type() == value_t::object
  9055. */
  9056. void write_bson_object(const typename BasicJsonType::object_t& value)
  9057. {
  9058. write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value)));
  9059. for (const auto& el : value)
  9060. {
  9061. write_bson_element(el.first, el.second);
  9062. }
  9063. oa->write_character(to_char_type(0x00));
  9064. }
  9065. //////////
  9066. // CBOR //
  9067. //////////
  9068. static constexpr CharType get_cbor_float_prefix(float /*unused*/)
  9069. {
  9070. return to_char_type(0xFA); // Single-Precision Float
  9071. }
  9072. static constexpr CharType get_cbor_float_prefix(double /*unused*/)
  9073. {
  9074. return to_char_type(0xFB); // Double-Precision Float
  9075. }
  9076. /////////////
  9077. // MsgPack //
  9078. /////////////
  9079. static constexpr CharType get_msgpack_float_prefix(float /*unused*/)
  9080. {
  9081. return to_char_type(0xCA); // float 32
  9082. }
  9083. static constexpr CharType get_msgpack_float_prefix(double /*unused*/)
  9084. {
  9085. return to_char_type(0xCB); // float 64
  9086. }
  9087. ////////////
  9088. // UBJSON //
  9089. ////////////
  9090. // UBJSON: write number (floating point)
  9091. template<typename NumberType, typename std::enable_if<
  9092. std::is_floating_point<NumberType>::value, int>::type = 0>
  9093. void write_number_with_ubjson_prefix(const NumberType n,
  9094. const bool add_prefix)
  9095. {
  9096. if (add_prefix)
  9097. {
  9098. oa->write_character(get_ubjson_float_prefix(n));
  9099. }
  9100. write_number(n);
  9101. }
  9102. // UBJSON: write number (unsigned integer)
  9103. template<typename NumberType, typename std::enable_if<
  9104. std::is_unsigned<NumberType>::value, int>::type = 0>
  9105. void write_number_with_ubjson_prefix(const NumberType n,
  9106. const bool add_prefix)
  9107. {
  9108. if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int8_t>::max)()))
  9109. {
  9110. if (add_prefix)
  9111. {
  9112. oa->write_character(to_char_type('i')); // int8
  9113. }
  9114. write_number(static_cast<std::uint8_t>(n));
  9115. }
  9116. else if (n <= (std::numeric_limits<std::uint8_t>::max)())
  9117. {
  9118. if (add_prefix)
  9119. {
  9120. oa->write_character(to_char_type('U')); // uint8
  9121. }
  9122. write_number(static_cast<std::uint8_t>(n));
  9123. }
  9124. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int16_t>::max)()))
  9125. {
  9126. if (add_prefix)
  9127. {
  9128. oa->write_character(to_char_type('I')); // int16
  9129. }
  9130. write_number(static_cast<std::int16_t>(n));
  9131. }
  9132. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)()))
  9133. {
  9134. if (add_prefix)
  9135. {
  9136. oa->write_character(to_char_type('l')); // int32
  9137. }
  9138. write_number(static_cast<std::int32_t>(n));
  9139. }
  9140. else if (n <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)()))
  9141. {
  9142. if (add_prefix)
  9143. {
  9144. oa->write_character(to_char_type('L')); // int64
  9145. }
  9146. write_number(static_cast<std::int64_t>(n));
  9147. }
  9148. else
  9149. {
  9150. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  9151. }
  9152. }
  9153. // UBJSON: write number (signed integer)
  9154. template<typename NumberType, typename std::enable_if<
  9155. std::is_signed<NumberType>::value and
  9156. not std::is_floating_point<NumberType>::value, int>::type = 0>
  9157. void write_number_with_ubjson_prefix(const NumberType n,
  9158. const bool add_prefix)
  9159. {
  9160. if ((std::numeric_limits<std::int8_t>::min)() <= n and n <= (std::numeric_limits<std::int8_t>::max)())
  9161. {
  9162. if (add_prefix)
  9163. {
  9164. oa->write_character(to_char_type('i')); // int8
  9165. }
  9166. write_number(static_cast<std::int8_t>(n));
  9167. }
  9168. else if (static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::min)()) <= n and n <= static_cast<std::int64_t>((std::numeric_limits<std::uint8_t>::max)()))
  9169. {
  9170. if (add_prefix)
  9171. {
  9172. oa->write_character(to_char_type('U')); // uint8
  9173. }
  9174. write_number(static_cast<std::uint8_t>(n));
  9175. }
  9176. else if ((std::numeric_limits<std::int16_t>::min)() <= n and n <= (std::numeric_limits<std::int16_t>::max)())
  9177. {
  9178. if (add_prefix)
  9179. {
  9180. oa->write_character(to_char_type('I')); // int16
  9181. }
  9182. write_number(static_cast<std::int16_t>(n));
  9183. }
  9184. else if ((std::numeric_limits<std::int32_t>::min)() <= n and n <= (std::numeric_limits<std::int32_t>::max)())
  9185. {
  9186. if (add_prefix)
  9187. {
  9188. oa->write_character(to_char_type('l')); // int32
  9189. }
  9190. write_number(static_cast<std::int32_t>(n));
  9191. }
  9192. else if ((std::numeric_limits<std::int64_t>::min)() <= n and n <= (std::numeric_limits<std::int64_t>::max)())
  9193. {
  9194. if (add_prefix)
  9195. {
  9196. oa->write_character(to_char_type('L')); // int64
  9197. }
  9198. write_number(static_cast<std::int64_t>(n));
  9199. }
  9200. // LCOV_EXCL_START
  9201. else
  9202. {
  9203. JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64"));
  9204. }
  9205. // LCOV_EXCL_STOP
  9206. }
  9207. /*!
  9208. @brief determine the type prefix of container values
  9209. @note This function does not need to be 100% accurate when it comes to
  9210. integer limits. In case a number exceeds the limits of int64_t,
  9211. this will be detected by a later call to function
  9212. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  9213. value that does not fit the previous limits.
  9214. */
  9215. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  9216. {
  9217. switch (j.type())
  9218. {
  9219. case value_t::null:
  9220. return 'Z';
  9221. case value_t::boolean:
  9222. return j.m_value.boolean ? 'T' : 'F';
  9223. case value_t::number_integer:
  9224. {
  9225. if ((std::numeric_limits<std::int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int8_t>::max)())
  9226. {
  9227. return 'i';
  9228. }
  9229. if ((std::numeric_limits<std::uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::uint8_t>::max)())
  9230. {
  9231. return 'U';
  9232. }
  9233. if ((std::numeric_limits<std::int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int16_t>::max)())
  9234. {
  9235. return 'I';
  9236. }
  9237. if ((std::numeric_limits<std::int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<std::int32_t>::max)())
  9238. {
  9239. return 'l';
  9240. }
  9241. // no check and assume int64_t (see note above)
  9242. return 'L';
  9243. }
  9244. case value_t::number_unsigned:
  9245. {
  9246. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int8_t>::max)())
  9247. {
  9248. return 'i';
  9249. }
  9250. if (j.m_value.number_unsigned <= (std::numeric_limits<std::uint8_t>::max)())
  9251. {
  9252. return 'U';
  9253. }
  9254. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int16_t>::max)())
  9255. {
  9256. return 'I';
  9257. }
  9258. if (j.m_value.number_unsigned <= (std::numeric_limits<std::int32_t>::max)())
  9259. {
  9260. return 'l';
  9261. }
  9262. // no check and assume int64_t (see note above)
  9263. return 'L';
  9264. }
  9265. case value_t::number_float:
  9266. return get_ubjson_float_prefix(j.m_value.number_float);
  9267. case value_t::string:
  9268. return 'S';
  9269. case value_t::array:
  9270. return '[';
  9271. case value_t::object:
  9272. return '{';
  9273. default: // discarded values
  9274. return 'N';
  9275. }
  9276. }
  9277. static constexpr CharType get_ubjson_float_prefix(float /*unused*/)
  9278. {
  9279. return 'd'; // float 32
  9280. }
  9281. static constexpr CharType get_ubjson_float_prefix(double /*unused*/)
  9282. {
  9283. return 'D'; // float 64
  9284. }
  9285. ///////////////////////
  9286. // Utility functions //
  9287. ///////////////////////
  9288. /*
  9289. @brief write a number to output input
  9290. @param[in] n number of type @a NumberType
  9291. @tparam NumberType the type of the number
  9292. @tparam OutputIsLittleEndian Set to true if output data is
  9293. required to be little endian
  9294. @note This function needs to respect the system's endianess, because bytes
  9295. in CBOR, MessagePack, and UBJSON are stored in network order (big
  9296. endian) and therefore need reordering on little endian systems.
  9297. */
  9298. template<typename NumberType, bool OutputIsLittleEndian = false>
  9299. void write_number(const NumberType n)
  9300. {
  9301. // step 1: write number to array of length NumberType
  9302. std::array<CharType, sizeof(NumberType)> vec;
  9303. std::memcpy(vec.data(), &n, sizeof(NumberType));
  9304. // step 2: write array to output (with possible reordering)
  9305. if (is_little_endian != OutputIsLittleEndian)
  9306. {
  9307. // reverse byte order prior to conversion if necessary
  9308. std::reverse(vec.begin(), vec.end());
  9309. }
  9310. oa->write_characters(vec.data(), sizeof(NumberType));
  9311. }
  9312. public:
  9313. // The following to_char_type functions are implement the conversion
  9314. // between uint8_t and CharType. In case CharType is not unsigned,
  9315. // such a conversion is required to allow values greater than 128.
  9316. // See <https://github.com/nlohmann/json/issues/1286> for a discussion.
  9317. template < typename C = CharType,
  9318. enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr >
  9319. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  9320. {
  9321. return *reinterpret_cast<char*>(&x);
  9322. }
  9323. template < typename C = CharType,
  9324. enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr >
  9325. static CharType to_char_type(std::uint8_t x) noexcept
  9326. {
  9327. static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t");
  9328. static_assert(std::is_pod<CharType>::value, "CharType must be POD");
  9329. CharType result;
  9330. std::memcpy(&result, &x, sizeof(x));
  9331. return result;
  9332. }
  9333. template<typename C = CharType,
  9334. enable_if_t<std::is_unsigned<C>::value>* = nullptr>
  9335. static constexpr CharType to_char_type(std::uint8_t x) noexcept
  9336. {
  9337. return x;
  9338. }
  9339. template < typename InputCharType, typename C = CharType,
  9340. enable_if_t <
  9341. std::is_signed<C>::value and
  9342. std::is_signed<char>::value and
  9343. std::is_same<char, typename std::remove_cv<InputCharType>::type>::value
  9344. > * = nullptr >
  9345. static constexpr CharType to_char_type(InputCharType x) noexcept
  9346. {
  9347. return x;
  9348. }
  9349. private:
  9350. /// whether we can assume little endianess
  9351. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  9352. /// the output
  9353. output_adapter_t<CharType> oa = nullptr;
  9354. };
  9355. } // namespace detail
  9356. } // namespace nlohmann
  9357. // #include <nlohmann/detail/output/output_adapters.hpp>
  9358. // #include <nlohmann/detail/output/serializer.hpp>
  9359. #include <algorithm> // reverse, remove, fill, find, none_of
  9360. #include <array> // array
  9361. #include <cassert> // assert
  9362. #include <ciso646> // and, or
  9363. #include <clocale> // localeconv, lconv
  9364. #include <cmath> // labs, isfinite, isnan, signbit
  9365. #include <cstddef> // size_t, ptrdiff_t
  9366. #include <cstdint> // uint8_t
  9367. #include <cstdio> // snprintf
  9368. #include <limits> // numeric_limits
  9369. #include <string> // string
  9370. #include <type_traits> // is_same
  9371. #include <utility> // move
  9372. // #include <nlohmann/detail/conversions/to_chars.hpp>
  9373. #include <array> // array
  9374. #include <cassert> // assert
  9375. #include <ciso646> // or, and, not
  9376. #include <cmath> // signbit, isfinite
  9377. #include <cstdint> // intN_t, uintN_t
  9378. #include <cstring> // memcpy, memmove
  9379. #include <limits> // numeric_limits
  9380. #include <type_traits> // conditional
  9381. namespace nlohmann
  9382. {
  9383. namespace detail
  9384. {
  9385. /*!
  9386. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  9387. conversion.
  9388. This implementation is a slightly modified version of the reference
  9389. implementation which may be obtained from
  9390. http://florian.loitsch.com/publications (bench.tar.gz).
  9391. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  9392. For a detailed description of the algorithm see:
  9393. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  9394. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  9395. Language Design and Implementation, PLDI 2010
  9396. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  9397. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  9398. Design and Implementation, PLDI 1996
  9399. */
  9400. namespace dtoa_impl
  9401. {
  9402. template <typename Target, typename Source>
  9403. Target reinterpret_bits(const Source source)
  9404. {
  9405. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  9406. Target target;
  9407. std::memcpy(&target, &source, sizeof(Source));
  9408. return target;
  9409. }
  9410. struct diyfp // f * 2^e
  9411. {
  9412. static constexpr int kPrecision = 64; // = q
  9413. std::uint64_t f = 0;
  9414. int e = 0;
  9415. constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  9416. /*!
  9417. @brief returns x - y
  9418. @pre x.e == y.e and x.f >= y.f
  9419. */
  9420. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  9421. {
  9422. assert(x.e == y.e);
  9423. assert(x.f >= y.f);
  9424. return {x.f - y.f, x.e};
  9425. }
  9426. /*!
  9427. @brief returns x * y
  9428. @note The result is rounded. (Only the upper q bits are returned.)
  9429. */
  9430. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  9431. {
  9432. static_assert(kPrecision == 64, "internal error");
  9433. // Computes:
  9434. // f = round((x.f * y.f) / 2^q)
  9435. // e = x.e + y.e + q
  9436. // Emulate the 64-bit * 64-bit multiplication:
  9437. //
  9438. // p = u * v
  9439. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  9440. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  9441. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  9442. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  9443. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  9444. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  9445. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  9446. //
  9447. // (Since Q might be larger than 2^32 - 1)
  9448. //
  9449. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  9450. //
  9451. // (Q_hi + H does not overflow a 64-bit int)
  9452. //
  9453. // = p_lo + 2^64 p_hi
  9454. const std::uint64_t u_lo = x.f & 0xFFFFFFFFu;
  9455. const std::uint64_t u_hi = x.f >> 32u;
  9456. const std::uint64_t v_lo = y.f & 0xFFFFFFFFu;
  9457. const std::uint64_t v_hi = y.f >> 32u;
  9458. const std::uint64_t p0 = u_lo * v_lo;
  9459. const std::uint64_t p1 = u_lo * v_hi;
  9460. const std::uint64_t p2 = u_hi * v_lo;
  9461. const std::uint64_t p3 = u_hi * v_hi;
  9462. const std::uint64_t p0_hi = p0 >> 32u;
  9463. const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu;
  9464. const std::uint64_t p1_hi = p1 >> 32u;
  9465. const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu;
  9466. const std::uint64_t p2_hi = p2 >> 32u;
  9467. std::uint64_t Q = p0_hi + p1_lo + p2_lo;
  9468. // The full product might now be computed as
  9469. //
  9470. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  9471. // p_lo = p0_lo + (Q << 32)
  9472. //
  9473. // But in this particular case here, the full p_lo is not required.
  9474. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  9475. // Q_hi + 1 does not overflow).
  9476. Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up
  9477. const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u);
  9478. return {h, x.e + y.e + 64};
  9479. }
  9480. /*!
  9481. @brief normalize x such that the significand is >= 2^(q-1)
  9482. @pre x.f != 0
  9483. */
  9484. static diyfp normalize(diyfp x) noexcept
  9485. {
  9486. assert(x.f != 0);
  9487. while ((x.f >> 63u) == 0)
  9488. {
  9489. x.f <<= 1u;
  9490. x.e--;
  9491. }
  9492. return x;
  9493. }
  9494. /*!
  9495. @brief normalize x such that the result has the exponent E
  9496. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  9497. */
  9498. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  9499. {
  9500. const int delta = x.e - target_exponent;
  9501. assert(delta >= 0);
  9502. assert(((x.f << delta) >> delta) == x.f);
  9503. return {x.f << delta, target_exponent};
  9504. }
  9505. };
  9506. struct boundaries
  9507. {
  9508. diyfp w;
  9509. diyfp minus;
  9510. diyfp plus;
  9511. };
  9512. /*!
  9513. Compute the (normalized) diyfp representing the input number 'value' and its
  9514. boundaries.
  9515. @pre value must be finite and positive
  9516. */
  9517. template <typename FloatType>
  9518. boundaries compute_boundaries(FloatType value)
  9519. {
  9520. assert(std::isfinite(value));
  9521. assert(value > 0);
  9522. // Convert the IEEE representation into a diyfp.
  9523. //
  9524. // If v is denormal:
  9525. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  9526. // If v is normalized:
  9527. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  9528. static_assert(std::numeric_limits<FloatType>::is_iec559,
  9529. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  9530. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  9531. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  9532. constexpr int kMinExp = 1 - kBias;
  9533. constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  9534. using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type;
  9535. const std::uint64_t bits = reinterpret_bits<bits_type>(value);
  9536. const std::uint64_t E = bits >> (kPrecision - 1);
  9537. const std::uint64_t F = bits & (kHiddenBit - 1);
  9538. const bool is_denormal = E == 0;
  9539. const diyfp v = is_denormal
  9540. ? diyfp(F, kMinExp)
  9541. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  9542. // Compute the boundaries m- and m+ of the floating-point value
  9543. // v = f * 2^e.
  9544. //
  9545. // Determine v- and v+, the floating-point predecessor and successor if v,
  9546. // respectively.
  9547. //
  9548. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  9549. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  9550. //
  9551. // v+ = v + 2^e
  9552. //
  9553. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  9554. // between m- and m+ round to v, regardless of how the input rounding
  9555. // algorithm breaks ties.
  9556. //
  9557. // ---+-------------+-------------+-------------+-------------+--- (A)
  9558. // v- m- v m+ v+
  9559. //
  9560. // -----------------+------+------+-------------+-------------+--- (B)
  9561. // v- m- v m+ v+
  9562. const bool lower_boundary_is_closer = F == 0 and E > 1;
  9563. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  9564. const diyfp m_minus = lower_boundary_is_closer
  9565. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  9566. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  9567. // Determine the normalized w+ = m+.
  9568. const diyfp w_plus = diyfp::normalize(m_plus);
  9569. // Determine w- = m- such that e_(w-) = e_(w+).
  9570. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  9571. return {diyfp::normalize(v), w_minus, w_plus};
  9572. }
  9573. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  9574. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  9575. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  9576. //
  9577. // alpha <= e = e_c + e_w + q <= gamma
  9578. //
  9579. // or
  9580. //
  9581. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  9582. // <= f_c * f_w * 2^gamma
  9583. //
  9584. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  9585. //
  9586. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  9587. //
  9588. // or
  9589. //
  9590. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  9591. //
  9592. // The choice of (alpha,gamma) determines the size of the table and the form of
  9593. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  9594. // in practice:
  9595. //
  9596. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  9597. // processed independently: An integral part p1, and a fractional part p2:
  9598. //
  9599. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  9600. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  9601. // = p1 + p2 * 2^e
  9602. //
  9603. // The conversion of p1 into decimal form requires a series of divisions and
  9604. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  9605. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  9606. // achieved by choosing
  9607. //
  9608. // -e >= 32 or e <= -32 := gamma
  9609. //
  9610. // In order to convert the fractional part
  9611. //
  9612. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  9613. //
  9614. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  9615. // d[-i] are extracted in order:
  9616. //
  9617. // (10 * p2) div 2^-e = d[-1]
  9618. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  9619. //
  9620. // The multiplication by 10 must not overflow. It is sufficient to choose
  9621. //
  9622. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  9623. //
  9624. // Since p2 = f mod 2^-e < 2^-e,
  9625. //
  9626. // -e <= 60 or e >= -60 := alpha
  9627. constexpr int kAlpha = -60;
  9628. constexpr int kGamma = -32;
  9629. struct cached_power // c = f * 2^e ~= 10^k
  9630. {
  9631. std::uint64_t f;
  9632. int e;
  9633. int k;
  9634. };
  9635. /*!
  9636. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  9637. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  9638. satisfies (Definition 3.2 from [1])
  9639. alpha <= e_c + e + q <= gamma.
  9640. */
  9641. inline cached_power get_cached_power_for_binary_exponent(int e)
  9642. {
  9643. // Now
  9644. //
  9645. // alpha <= e_c + e + q <= gamma (1)
  9646. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  9647. //
  9648. // and since the c's are normalized, 2^(q-1) <= f_c,
  9649. //
  9650. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  9651. // ==> 2^(alpha - e - 1) <= c
  9652. //
  9653. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  9654. //
  9655. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  9656. // = ceil( (alpha - e - 1) * log_10(2) )
  9657. //
  9658. // From the paper:
  9659. // "In theory the result of the procedure could be wrong since c is rounded,
  9660. // and the computation itself is approximated [...]. In practice, however,
  9661. // this simple function is sufficient."
  9662. //
  9663. // For IEEE double precision floating-point numbers converted into
  9664. // normalized diyfp's w = f * 2^e, with q = 64,
  9665. //
  9666. // e >= -1022 (min IEEE exponent)
  9667. // -52 (p - 1)
  9668. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  9669. // -11 (normalize the diyfp)
  9670. // = -1137
  9671. //
  9672. // and
  9673. //
  9674. // e <= +1023 (max IEEE exponent)
  9675. // -52 (p - 1)
  9676. // -11 (normalize the diyfp)
  9677. // = 960
  9678. //
  9679. // This binary exponent range [-1137,960] results in a decimal exponent
  9680. // range [-307,324]. One does not need to store a cached power for each
  9681. // k in this range. For each such k it suffices to find a cached power
  9682. // such that the exponent of the product lies in [alpha,gamma].
  9683. // This implies that the difference of the decimal exponents of adjacent
  9684. // table entries must be less than or equal to
  9685. //
  9686. // floor( (gamma - alpha) * log_10(2) ) = 8.
  9687. //
  9688. // (A smaller distance gamma-alpha would require a larger table.)
  9689. // NB:
  9690. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  9691. constexpr int kCachedPowersMinDecExp = -300;
  9692. constexpr int kCachedPowersDecStep = 8;
  9693. static constexpr std::array<cached_power, 79> kCachedPowers =
  9694. {
  9695. {
  9696. { 0xAB70FE17C79AC6CA, -1060, -300 },
  9697. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  9698. { 0xBE5691EF416BD60C, -1007, -284 },
  9699. { 0x8DD01FAD907FFC3C, -980, -276 },
  9700. { 0xD3515C2831559A83, -954, -268 },
  9701. { 0x9D71AC8FADA6C9B5, -927, -260 },
  9702. { 0xEA9C227723EE8BCB, -901, -252 },
  9703. { 0xAECC49914078536D, -874, -244 },
  9704. { 0x823C12795DB6CE57, -847, -236 },
  9705. { 0xC21094364DFB5637, -821, -228 },
  9706. { 0x9096EA6F3848984F, -794, -220 },
  9707. { 0xD77485CB25823AC7, -768, -212 },
  9708. { 0xA086CFCD97BF97F4, -741, -204 },
  9709. { 0xEF340A98172AACE5, -715, -196 },
  9710. { 0xB23867FB2A35B28E, -688, -188 },
  9711. { 0x84C8D4DFD2C63F3B, -661, -180 },
  9712. { 0xC5DD44271AD3CDBA, -635, -172 },
  9713. { 0x936B9FCEBB25C996, -608, -164 },
  9714. { 0xDBAC6C247D62A584, -582, -156 },
  9715. { 0xA3AB66580D5FDAF6, -555, -148 },
  9716. { 0xF3E2F893DEC3F126, -529, -140 },
  9717. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  9718. { 0x87625F056C7C4A8B, -475, -124 },
  9719. { 0xC9BCFF6034C13053, -449, -116 },
  9720. { 0x964E858C91BA2655, -422, -108 },
  9721. { 0xDFF9772470297EBD, -396, -100 },
  9722. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  9723. { 0xF8A95FCF88747D94, -343, -84 },
  9724. { 0xB94470938FA89BCF, -316, -76 },
  9725. { 0x8A08F0F8BF0F156B, -289, -68 },
  9726. { 0xCDB02555653131B6, -263, -60 },
  9727. { 0x993FE2C6D07B7FAC, -236, -52 },
  9728. { 0xE45C10C42A2B3B06, -210, -44 },
  9729. { 0xAA242499697392D3, -183, -36 },
  9730. { 0xFD87B5F28300CA0E, -157, -28 },
  9731. { 0xBCE5086492111AEB, -130, -20 },
  9732. { 0x8CBCCC096F5088CC, -103, -12 },
  9733. { 0xD1B71758E219652C, -77, -4 },
  9734. { 0x9C40000000000000, -50, 4 },
  9735. { 0xE8D4A51000000000, -24, 12 },
  9736. { 0xAD78EBC5AC620000, 3, 20 },
  9737. { 0x813F3978F8940984, 30, 28 },
  9738. { 0xC097CE7BC90715B3, 56, 36 },
  9739. { 0x8F7E32CE7BEA5C70, 83, 44 },
  9740. { 0xD5D238A4ABE98068, 109, 52 },
  9741. { 0x9F4F2726179A2245, 136, 60 },
  9742. { 0xED63A231D4C4FB27, 162, 68 },
  9743. { 0xB0DE65388CC8ADA8, 189, 76 },
  9744. { 0x83C7088E1AAB65DB, 216, 84 },
  9745. { 0xC45D1DF942711D9A, 242, 92 },
  9746. { 0x924D692CA61BE758, 269, 100 },
  9747. { 0xDA01EE641A708DEA, 295, 108 },
  9748. { 0xA26DA3999AEF774A, 322, 116 },
  9749. { 0xF209787BB47D6B85, 348, 124 },
  9750. { 0xB454E4A179DD1877, 375, 132 },
  9751. { 0x865B86925B9BC5C2, 402, 140 },
  9752. { 0xC83553C5C8965D3D, 428, 148 },
  9753. { 0x952AB45CFA97A0B3, 455, 156 },
  9754. { 0xDE469FBD99A05FE3, 481, 164 },
  9755. { 0xA59BC234DB398C25, 508, 172 },
  9756. { 0xF6C69A72A3989F5C, 534, 180 },
  9757. { 0xB7DCBF5354E9BECE, 561, 188 },
  9758. { 0x88FCF317F22241E2, 588, 196 },
  9759. { 0xCC20CE9BD35C78A5, 614, 204 },
  9760. { 0x98165AF37B2153DF, 641, 212 },
  9761. { 0xE2A0B5DC971F303A, 667, 220 },
  9762. { 0xA8D9D1535CE3B396, 694, 228 },
  9763. { 0xFB9B7CD9A4A7443C, 720, 236 },
  9764. { 0xBB764C4CA7A44410, 747, 244 },
  9765. { 0x8BAB8EEFB6409C1A, 774, 252 },
  9766. { 0xD01FEF10A657842C, 800, 260 },
  9767. { 0x9B10A4E5E9913129, 827, 268 },
  9768. { 0xE7109BFBA19C0C9D, 853, 276 },
  9769. { 0xAC2820D9623BF429, 880, 284 },
  9770. { 0x80444B5E7AA7CF85, 907, 292 },
  9771. { 0xBF21E44003ACDD2D, 933, 300 },
  9772. { 0x8E679C2F5E44FF8F, 960, 308 },
  9773. { 0xD433179D9C8CB841, 986, 316 },
  9774. { 0x9E19DB92B4E31BA9, 1013, 324 },
  9775. }
  9776. };
  9777. // This computation gives exactly the same results for k as
  9778. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  9779. // for |e| <= 1500, but doesn't require floating-point operations.
  9780. // NB: log_10(2) ~= 78913 / 2^18
  9781. assert(e >= -1500);
  9782. assert(e <= 1500);
  9783. const int f = kAlpha - e - 1;
  9784. const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0);
  9785. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  9786. assert(index >= 0);
  9787. assert(static_cast<std::size_t>(index) < kCachedPowers.size());
  9788. const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)];
  9789. assert(kAlpha <= cached.e + e + 64);
  9790. assert(kGamma >= cached.e + e + 64);
  9791. return cached;
  9792. }
  9793. /*!
  9794. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  9795. For n == 0, returns 1 and sets pow10 := 1.
  9796. */
  9797. inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10)
  9798. {
  9799. // LCOV_EXCL_START
  9800. if (n >= 1000000000)
  9801. {
  9802. pow10 = 1000000000;
  9803. return 10;
  9804. }
  9805. // LCOV_EXCL_STOP
  9806. else if (n >= 100000000)
  9807. {
  9808. pow10 = 100000000;
  9809. return 9;
  9810. }
  9811. else if (n >= 10000000)
  9812. {
  9813. pow10 = 10000000;
  9814. return 8;
  9815. }
  9816. else if (n >= 1000000)
  9817. {
  9818. pow10 = 1000000;
  9819. return 7;
  9820. }
  9821. else if (n >= 100000)
  9822. {
  9823. pow10 = 100000;
  9824. return 6;
  9825. }
  9826. else if (n >= 10000)
  9827. {
  9828. pow10 = 10000;
  9829. return 5;
  9830. }
  9831. else if (n >= 1000)
  9832. {
  9833. pow10 = 1000;
  9834. return 4;
  9835. }
  9836. else if (n >= 100)
  9837. {
  9838. pow10 = 100;
  9839. return 3;
  9840. }
  9841. else if (n >= 10)
  9842. {
  9843. pow10 = 10;
  9844. return 2;
  9845. }
  9846. else
  9847. {
  9848. pow10 = 1;
  9849. return 1;
  9850. }
  9851. }
  9852. inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta,
  9853. std::uint64_t rest, std::uint64_t ten_k)
  9854. {
  9855. assert(len >= 1);
  9856. assert(dist <= delta);
  9857. assert(rest <= delta);
  9858. assert(ten_k > 0);
  9859. // <--------------------------- delta ---->
  9860. // <---- dist --------->
  9861. // --------------[------------------+-------------------]--------------
  9862. // M- w M+
  9863. //
  9864. // ten_k
  9865. // <------>
  9866. // <---- rest ---->
  9867. // --------------[------------------+----+--------------]--------------
  9868. // w V
  9869. // = buf * 10^k
  9870. //
  9871. // ten_k represents a unit-in-the-last-place in the decimal representation
  9872. // stored in buf.
  9873. // Decrement buf by ten_k while this takes buf closer to w.
  9874. // The tests are written in this order to avoid overflow in unsigned
  9875. // integer arithmetic.
  9876. while (rest < dist
  9877. and delta - rest >= ten_k
  9878. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  9879. {
  9880. assert(buf[len - 1] != '0');
  9881. buf[len - 1]--;
  9882. rest += ten_k;
  9883. }
  9884. }
  9885. /*!
  9886. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  9887. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  9888. */
  9889. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  9890. diyfp M_minus, diyfp w, diyfp M_plus)
  9891. {
  9892. static_assert(kAlpha >= -60, "internal error");
  9893. static_assert(kGamma <= -32, "internal error");
  9894. // Generates the digits (and the exponent) of a decimal floating-point
  9895. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  9896. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  9897. //
  9898. // <--------------------------- delta ---->
  9899. // <---- dist --------->
  9900. // --------------[------------------+-------------------]--------------
  9901. // M- w M+
  9902. //
  9903. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  9904. // V is in [M-,M+].
  9905. assert(M_plus.e >= kAlpha);
  9906. assert(M_plus.e <= kGamma);
  9907. std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  9908. std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  9909. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  9910. //
  9911. // M+ = f * 2^e
  9912. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  9913. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  9914. // = p1 + p2 * 2^e
  9915. const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e);
  9916. 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.)
  9917. std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  9918. // 1)
  9919. //
  9920. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  9921. assert(p1 > 0);
  9922. std::uint32_t pow10;
  9923. const int k = find_largest_pow10(p1, pow10);
  9924. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  9925. //
  9926. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  9927. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  9928. //
  9929. // M+ = p1 + p2 * 2^e
  9930. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  9931. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  9932. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  9933. //
  9934. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  9935. //
  9936. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  9937. //
  9938. // but stop as soon as
  9939. //
  9940. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  9941. int n = k;
  9942. while (n > 0)
  9943. {
  9944. // Invariants:
  9945. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  9946. // pow10 = 10^(n-1) <= p1 < 10^n
  9947. //
  9948. const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  9949. const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  9950. //
  9951. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  9952. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  9953. //
  9954. assert(d <= 9);
  9955. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  9956. //
  9957. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  9958. //
  9959. p1 = r;
  9960. n--;
  9961. //
  9962. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  9963. // pow10 = 10^n
  9964. //
  9965. // Now check if enough digits have been generated.
  9966. // Compute
  9967. //
  9968. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  9969. //
  9970. // Note:
  9971. // Since rest and delta share the same exponent e, it suffices to
  9972. // compare the significands.
  9973. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2;
  9974. if (rest <= delta)
  9975. {
  9976. // V = buffer * 10^n, with M- <= V <= M+.
  9977. decimal_exponent += n;
  9978. // We may now just stop. But instead look if the buffer could be
  9979. // decremented to bring V closer to w.
  9980. //
  9981. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  9982. // The rounding procedure works with diyfp's with an implicit
  9983. // exponent of e.
  9984. //
  9985. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  9986. //
  9987. const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e;
  9988. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  9989. return;
  9990. }
  9991. pow10 /= 10;
  9992. //
  9993. // pow10 = 10^(n-1) <= p1 < 10^n
  9994. // Invariants restored.
  9995. }
  9996. // 2)
  9997. //
  9998. // The digits of the integral part have been generated:
  9999. //
  10000. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  10001. // = buffer + p2 * 2^e
  10002. //
  10003. // Now generate the digits of the fractional part p2 * 2^e.
  10004. //
  10005. // Note:
  10006. // No decimal point is generated: the exponent is adjusted instead.
  10007. //
  10008. // p2 actually represents the fraction
  10009. //
  10010. // p2 * 2^e
  10011. // = p2 / 2^-e
  10012. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  10013. //
  10014. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  10015. //
  10016. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  10017. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  10018. //
  10019. // using
  10020. //
  10021. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  10022. // = ( d) * 2^-e + ( r)
  10023. //
  10024. // or
  10025. // 10^m * p2 * 2^e = d + r * 2^e
  10026. //
  10027. // i.e.
  10028. //
  10029. // M+ = buffer + p2 * 2^e
  10030. // = buffer + 10^-m * (d + r * 2^e)
  10031. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  10032. //
  10033. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  10034. assert(p2 > delta);
  10035. int m = 0;
  10036. for (;;)
  10037. {
  10038. // Invariant:
  10039. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  10040. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  10041. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  10042. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  10043. //
  10044. assert(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10);
  10045. p2 *= 10;
  10046. const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  10047. const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  10048. //
  10049. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  10050. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  10051. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  10052. //
  10053. assert(d <= 9);
  10054. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  10055. //
  10056. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  10057. //
  10058. p2 = r;
  10059. m++;
  10060. //
  10061. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  10062. // Invariant restored.
  10063. // Check if enough digits have been generated.
  10064. //
  10065. // 10^-m * p2 * 2^e <= delta * 2^e
  10066. // p2 * 2^e <= 10^m * delta * 2^e
  10067. // p2 <= 10^m * delta
  10068. delta *= 10;
  10069. dist *= 10;
  10070. if (p2 <= delta)
  10071. {
  10072. break;
  10073. }
  10074. }
  10075. // V = buffer * 10^-m, with M- <= V <= M+.
  10076. decimal_exponent -= m;
  10077. // 1 ulp in the decimal representation is now 10^-m.
  10078. // Since delta and dist are now scaled by 10^m, we need to do the
  10079. // same with ulp in order to keep the units in sync.
  10080. //
  10081. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  10082. //
  10083. const std::uint64_t ten_m = one.f;
  10084. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  10085. // By construction this algorithm generates the shortest possible decimal
  10086. // number (Loitsch, Theorem 6.2) which rounds back to w.
  10087. // For an input number of precision p, at least
  10088. //
  10089. // N = 1 + ceil(p * log_10(2))
  10090. //
  10091. // decimal digits are sufficient to identify all binary floating-point
  10092. // numbers (Matula, "In-and-Out conversions").
  10093. // This implies that the algorithm does not produce more than N decimal
  10094. // digits.
  10095. //
  10096. // N = 17 for p = 53 (IEEE double precision)
  10097. // N = 9 for p = 24 (IEEE single precision)
  10098. }
  10099. /*!
  10100. v = buf * 10^decimal_exponent
  10101. len is the length of the buffer (number of decimal digits)
  10102. The buffer must be large enough, i.e. >= max_digits10.
  10103. */
  10104. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  10105. diyfp m_minus, diyfp v, diyfp m_plus)
  10106. {
  10107. assert(m_plus.e == m_minus.e);
  10108. assert(m_plus.e == v.e);
  10109. // --------(-----------------------+-----------------------)-------- (A)
  10110. // m- v m+
  10111. //
  10112. // --------------------(-----------+-----------------------)-------- (B)
  10113. // m- v m+
  10114. //
  10115. // First scale v (and m- and m+) such that the exponent is in the range
  10116. // [alpha, gamma].
  10117. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  10118. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  10119. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  10120. const diyfp w = diyfp::mul(v, c_minus_k);
  10121. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  10122. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  10123. // ----(---+---)---------------(---+---)---------------(---+---)----
  10124. // w- w w+
  10125. // = c*m- = c*v = c*m+
  10126. //
  10127. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  10128. // w+ are now off by a small amount.
  10129. // In fact:
  10130. //
  10131. // w - v * 10^k < 1 ulp
  10132. //
  10133. // To account for this inaccuracy, add resp. subtract 1 ulp.
  10134. //
  10135. // --------+---[---------------(---+---)---------------]---+--------
  10136. // w- M- w M+ w+
  10137. //
  10138. // Now any number in [M-, M+] (bounds included) will round to w when input,
  10139. // regardless of how the input rounding algorithm breaks ties.
  10140. //
  10141. // And digit_gen generates the shortest possible such number in [M-, M+].
  10142. // Note that this does not mean that Grisu2 always generates the shortest
  10143. // possible number in the interval (m-, m+).
  10144. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  10145. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  10146. decimal_exponent = -cached.k; // = -(-k) = k
  10147. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  10148. }
  10149. /*!
  10150. v = buf * 10^decimal_exponent
  10151. len is the length of the buffer (number of decimal digits)
  10152. The buffer must be large enough, i.e. >= max_digits10.
  10153. */
  10154. template <typename FloatType>
  10155. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  10156. {
  10157. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  10158. "internal error: not enough precision");
  10159. assert(std::isfinite(value));
  10160. assert(value > 0);
  10161. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  10162. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  10163. // decimal representations are not exactly "short".
  10164. //
  10165. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  10166. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  10167. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  10168. // does.
  10169. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  10170. // representation using the corresponding std::from_chars function recovers value exactly". That
  10171. // indicates that single precision floating-point numbers should be recovered using
  10172. // 'std::strtof'.
  10173. //
  10174. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  10175. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  10176. // value is off by 1 ulp.
  10177. #if 0
  10178. const boundaries w = compute_boundaries(static_cast<double>(value));
  10179. #else
  10180. const boundaries w = compute_boundaries(value);
  10181. #endif
  10182. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  10183. }
  10184. /*!
  10185. @brief appends a decimal representation of e to buf
  10186. @return a pointer to the element following the exponent.
  10187. @pre -1000 < e < 1000
  10188. */
  10189. inline char* append_exponent(char* buf, int e)
  10190. {
  10191. assert(e > -1000);
  10192. assert(e < 1000);
  10193. if (e < 0)
  10194. {
  10195. e = -e;
  10196. *buf++ = '-';
  10197. }
  10198. else
  10199. {
  10200. *buf++ = '+';
  10201. }
  10202. auto k = static_cast<std::uint32_t>(e);
  10203. if (k < 10)
  10204. {
  10205. // Always print at least two digits in the exponent.
  10206. // This is for compatibility with printf("%g").
  10207. *buf++ = '0';
  10208. *buf++ = static_cast<char>('0' + k);
  10209. }
  10210. else if (k < 100)
  10211. {
  10212. *buf++ = static_cast<char>('0' + k / 10);
  10213. k %= 10;
  10214. *buf++ = static_cast<char>('0' + k);
  10215. }
  10216. else
  10217. {
  10218. *buf++ = static_cast<char>('0' + k / 100);
  10219. k %= 100;
  10220. *buf++ = static_cast<char>('0' + k / 10);
  10221. k %= 10;
  10222. *buf++ = static_cast<char>('0' + k);
  10223. }
  10224. return buf;
  10225. }
  10226. /*!
  10227. @brief prettify v = buf * 10^decimal_exponent
  10228. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  10229. notation. Otherwise it will be printed in exponential notation.
  10230. @pre min_exp < 0
  10231. @pre max_exp > 0
  10232. */
  10233. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  10234. int min_exp, int max_exp)
  10235. {
  10236. assert(min_exp < 0);
  10237. assert(max_exp > 0);
  10238. const int k = len;
  10239. const int n = len + decimal_exponent;
  10240. // v = buf * 10^(n-k)
  10241. // k is the length of the buffer (number of decimal digits)
  10242. // n is the position of the decimal point relative to the start of the buffer.
  10243. if (k <= n and n <= max_exp)
  10244. {
  10245. // digits[000]
  10246. // len <= max_exp + 2
  10247. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  10248. // Make it look like a floating-point number (#362, #378)
  10249. buf[n + 0] = '.';
  10250. buf[n + 1] = '0';
  10251. return buf + (n + 2);
  10252. }
  10253. if (0 < n and n <= max_exp)
  10254. {
  10255. // dig.its
  10256. // len <= max_digits10 + 1
  10257. assert(k > n);
  10258. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  10259. buf[n] = '.';
  10260. return buf + (k + 1);
  10261. }
  10262. if (min_exp < n and n <= 0)
  10263. {
  10264. // 0.[000]digits
  10265. // len <= 2 + (-min_exp - 1) + max_digits10
  10266. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  10267. buf[0] = '0';
  10268. buf[1] = '.';
  10269. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  10270. return buf + (2 + (-n) + k);
  10271. }
  10272. if (k == 1)
  10273. {
  10274. // dE+123
  10275. // len <= 1 + 5
  10276. buf += 1;
  10277. }
  10278. else
  10279. {
  10280. // d.igitsE+123
  10281. // len <= max_digits10 + 1 + 5
  10282. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  10283. buf[1] = '.';
  10284. buf += 1 + k;
  10285. }
  10286. *buf++ = 'e';
  10287. return append_exponent(buf, n - 1);
  10288. }
  10289. } // namespace dtoa_impl
  10290. /*!
  10291. @brief generates a decimal representation of the floating-point number value in [first, last).
  10292. The format of the resulting decimal representation is similar to printf's %g
  10293. format. Returns an iterator pointing past-the-end of the decimal representation.
  10294. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  10295. @note The buffer must be large enough.
  10296. @note The result is NOT null-terminated.
  10297. */
  10298. template <typename FloatType>
  10299. char* to_chars(char* first, const char* last, FloatType value)
  10300. {
  10301. static_cast<void>(last); // maybe unused - fix warning
  10302. assert(std::isfinite(value));
  10303. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  10304. if (std::signbit(value))
  10305. {
  10306. value = -value;
  10307. *first++ = '-';
  10308. }
  10309. if (value == 0) // +-0
  10310. {
  10311. *first++ = '0';
  10312. // Make it look like a floating-point number (#362, #378)
  10313. *first++ = '.';
  10314. *first++ = '0';
  10315. return first;
  10316. }
  10317. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  10318. // Compute v = buffer * 10^decimal_exponent.
  10319. // The decimal digits are stored in the buffer, which needs to be interpreted
  10320. // as an unsigned decimal integer.
  10321. // len is the length of the buffer, i.e. the number of decimal digits.
  10322. int len = 0;
  10323. int decimal_exponent = 0;
  10324. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  10325. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  10326. // Format the buffer like printf("%.*g", prec, value)
  10327. constexpr int kMinExp = -4;
  10328. // Use digits10 here to increase compatibility with version 2.
  10329. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  10330. assert(last - first >= kMaxExp + 2);
  10331. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  10332. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  10333. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  10334. }
  10335. } // namespace detail
  10336. } // namespace nlohmann
  10337. // #include <nlohmann/detail/exceptions.hpp>
  10338. // #include <nlohmann/detail/macro_scope.hpp>
  10339. // #include <nlohmann/detail/meta/cpp_future.hpp>
  10340. // #include <nlohmann/detail/output/binary_writer.hpp>
  10341. // #include <nlohmann/detail/output/output_adapters.hpp>
  10342. // #include <nlohmann/detail/value_t.hpp>
  10343. namespace nlohmann
  10344. {
  10345. namespace detail
  10346. {
  10347. ///////////////////
  10348. // serialization //
  10349. ///////////////////
  10350. /// how to treat decoding errors
  10351. enum class error_handler_t
  10352. {
  10353. strict, ///< throw a type_error exception in case of invalid UTF-8
  10354. replace, ///< replace invalid UTF-8 sequences with U+FFFD
  10355. ignore ///< ignore invalid UTF-8 sequences
  10356. };
  10357. template<typename BasicJsonType>
  10358. class serializer
  10359. {
  10360. using string_t = typename BasicJsonType::string_t;
  10361. using number_float_t = typename BasicJsonType::number_float_t;
  10362. using number_integer_t = typename BasicJsonType::number_integer_t;
  10363. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  10364. static constexpr std::uint8_t UTF8_ACCEPT = 0;
  10365. static constexpr std::uint8_t UTF8_REJECT = 1;
  10366. public:
  10367. /*!
  10368. @param[in] s output stream to serialize to
  10369. @param[in] ichar indentation character to use
  10370. @param[in] error_handler_ how to react on decoding errors
  10371. */
  10372. serializer(output_adapter_t<char> s, const char ichar,
  10373. error_handler_t error_handler_ = error_handler_t::strict)
  10374. : o(std::move(s))
  10375. , loc(std::localeconv())
  10376. , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep))
  10377. , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point))
  10378. , indent_char(ichar)
  10379. , indent_string(512, indent_char)
  10380. , error_handler(error_handler_)
  10381. {}
  10382. // delete because of pointer members
  10383. serializer(const serializer&) = delete;
  10384. serializer& operator=(const serializer&) = delete;
  10385. serializer(serializer&&) = delete;
  10386. serializer& operator=(serializer&&) = delete;
  10387. ~serializer() = default;
  10388. /*!
  10389. @brief internal implementation of the serialization function
  10390. This function is called by the public member function dump and organizes
  10391. the serialization internally. The indentation level is propagated as
  10392. additional parameter. In case of arrays and objects, the function is
  10393. called recursively.
  10394. - strings and object keys are escaped using `escape_string()`
  10395. - integer numbers are converted implicitly via `operator<<`
  10396. - floating-point numbers are converted to a string using `"%g"` format
  10397. @param[in] val value to serialize
  10398. @param[in] pretty_print whether the output shall be pretty-printed
  10399. @param[in] indent_step the indent level
  10400. @param[in] current_indent the current indent level (only used internally)
  10401. */
  10402. void dump(const BasicJsonType& val, const bool pretty_print,
  10403. const bool ensure_ascii,
  10404. const unsigned int indent_step,
  10405. const unsigned int current_indent = 0)
  10406. {
  10407. switch (val.m_type)
  10408. {
  10409. case value_t::object:
  10410. {
  10411. if (val.m_value.object->empty())
  10412. {
  10413. o->write_characters("{}", 2);
  10414. return;
  10415. }
  10416. if (pretty_print)
  10417. {
  10418. o->write_characters("{\n", 2);
  10419. // variable to hold indentation for recursive calls
  10420. const auto new_indent = current_indent + indent_step;
  10421. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  10422. {
  10423. indent_string.resize(indent_string.size() * 2, ' ');
  10424. }
  10425. // first n-1 elements
  10426. auto i = val.m_value.object->cbegin();
  10427. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  10428. {
  10429. o->write_characters(indent_string.c_str(), new_indent);
  10430. o->write_character('\"');
  10431. dump_escaped(i->first, ensure_ascii);
  10432. o->write_characters("\": ", 3);
  10433. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  10434. o->write_characters(",\n", 2);
  10435. }
  10436. // last element
  10437. assert(i != val.m_value.object->cend());
  10438. assert(std::next(i) == val.m_value.object->cend());
  10439. o->write_characters(indent_string.c_str(), new_indent);
  10440. o->write_character('\"');
  10441. dump_escaped(i->first, ensure_ascii);
  10442. o->write_characters("\": ", 3);
  10443. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  10444. o->write_character('\n');
  10445. o->write_characters(indent_string.c_str(), current_indent);
  10446. o->write_character('}');
  10447. }
  10448. else
  10449. {
  10450. o->write_character('{');
  10451. // first n-1 elements
  10452. auto i = val.m_value.object->cbegin();
  10453. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  10454. {
  10455. o->write_character('\"');
  10456. dump_escaped(i->first, ensure_ascii);
  10457. o->write_characters("\":", 2);
  10458. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  10459. o->write_character(',');
  10460. }
  10461. // last element
  10462. assert(i != val.m_value.object->cend());
  10463. assert(std::next(i) == val.m_value.object->cend());
  10464. o->write_character('\"');
  10465. dump_escaped(i->first, ensure_ascii);
  10466. o->write_characters("\":", 2);
  10467. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  10468. o->write_character('}');
  10469. }
  10470. return;
  10471. }
  10472. case value_t::array:
  10473. {
  10474. if (val.m_value.array->empty())
  10475. {
  10476. o->write_characters("[]", 2);
  10477. return;
  10478. }
  10479. if (pretty_print)
  10480. {
  10481. o->write_characters("[\n", 2);
  10482. // variable to hold indentation for recursive calls
  10483. const auto new_indent = current_indent + indent_step;
  10484. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  10485. {
  10486. indent_string.resize(indent_string.size() * 2, ' ');
  10487. }
  10488. // first n-1 elements
  10489. for (auto i = val.m_value.array->cbegin();
  10490. i != val.m_value.array->cend() - 1; ++i)
  10491. {
  10492. o->write_characters(indent_string.c_str(), new_indent);
  10493. dump(*i, true, ensure_ascii, indent_step, new_indent);
  10494. o->write_characters(",\n", 2);
  10495. }
  10496. // last element
  10497. assert(not val.m_value.array->empty());
  10498. o->write_characters(indent_string.c_str(), new_indent);
  10499. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  10500. o->write_character('\n');
  10501. o->write_characters(indent_string.c_str(), current_indent);
  10502. o->write_character(']');
  10503. }
  10504. else
  10505. {
  10506. o->write_character('[');
  10507. // first n-1 elements
  10508. for (auto i = val.m_value.array->cbegin();
  10509. i != val.m_value.array->cend() - 1; ++i)
  10510. {
  10511. dump(*i, false, ensure_ascii, indent_step, current_indent);
  10512. o->write_character(',');
  10513. }
  10514. // last element
  10515. assert(not val.m_value.array->empty());
  10516. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  10517. o->write_character(']');
  10518. }
  10519. return;
  10520. }
  10521. case value_t::string:
  10522. {
  10523. o->write_character('\"');
  10524. dump_escaped(*val.m_value.string, ensure_ascii);
  10525. o->write_character('\"');
  10526. return;
  10527. }
  10528. case value_t::boolean:
  10529. {
  10530. if (val.m_value.boolean)
  10531. {
  10532. o->write_characters("true", 4);
  10533. }
  10534. else
  10535. {
  10536. o->write_characters("false", 5);
  10537. }
  10538. return;
  10539. }
  10540. case value_t::number_integer:
  10541. {
  10542. dump_integer(val.m_value.number_integer);
  10543. return;
  10544. }
  10545. case value_t::number_unsigned:
  10546. {
  10547. dump_integer(val.m_value.number_unsigned);
  10548. return;
  10549. }
  10550. case value_t::number_float:
  10551. {
  10552. dump_float(val.m_value.number_float);
  10553. return;
  10554. }
  10555. case value_t::discarded:
  10556. {
  10557. o->write_characters("<discarded>", 11);
  10558. return;
  10559. }
  10560. case value_t::null:
  10561. {
  10562. o->write_characters("null", 4);
  10563. return;
  10564. }
  10565. default: // LCOV_EXCL_LINE
  10566. assert(false); // LCOV_EXCL_LINE
  10567. }
  10568. }
  10569. private:
  10570. /*!
  10571. @brief dump escaped string
  10572. Escape a string by replacing certain special characters by a sequence of an
  10573. escape character (backslash) and another character and other control
  10574. characters by a sequence of "\u" followed by a four-digit hex
  10575. representation. The escaped string is written to output stream @a o.
  10576. @param[in] s the string to escape
  10577. @param[in] ensure_ascii whether to escape non-ASCII characters with
  10578. \uXXXX sequences
  10579. @complexity Linear in the length of string @a s.
  10580. */
  10581. void dump_escaped(const string_t& s, const bool ensure_ascii)
  10582. {
  10583. std::uint32_t codepoint;
  10584. std::uint8_t state = UTF8_ACCEPT;
  10585. std::size_t bytes = 0; // number of bytes written to string_buffer
  10586. // number of bytes written at the point of the last valid byte
  10587. std::size_t bytes_after_last_accept = 0;
  10588. std::size_t undumped_chars = 0;
  10589. for (std::size_t i = 0; i < s.size(); ++i)
  10590. {
  10591. const auto byte = static_cast<uint8_t>(s[i]);
  10592. switch (decode(state, codepoint, byte))
  10593. {
  10594. case UTF8_ACCEPT: // decode found a new code point
  10595. {
  10596. switch (codepoint)
  10597. {
  10598. case 0x08: // backspace
  10599. {
  10600. string_buffer[bytes++] = '\\';
  10601. string_buffer[bytes++] = 'b';
  10602. break;
  10603. }
  10604. case 0x09: // horizontal tab
  10605. {
  10606. string_buffer[bytes++] = '\\';
  10607. string_buffer[bytes++] = 't';
  10608. break;
  10609. }
  10610. case 0x0A: // newline
  10611. {
  10612. string_buffer[bytes++] = '\\';
  10613. string_buffer[bytes++] = 'n';
  10614. break;
  10615. }
  10616. case 0x0C: // formfeed
  10617. {
  10618. string_buffer[bytes++] = '\\';
  10619. string_buffer[bytes++] = 'f';
  10620. break;
  10621. }
  10622. case 0x0D: // carriage return
  10623. {
  10624. string_buffer[bytes++] = '\\';
  10625. string_buffer[bytes++] = 'r';
  10626. break;
  10627. }
  10628. case 0x22: // quotation mark
  10629. {
  10630. string_buffer[bytes++] = '\\';
  10631. string_buffer[bytes++] = '\"';
  10632. break;
  10633. }
  10634. case 0x5C: // reverse solidus
  10635. {
  10636. string_buffer[bytes++] = '\\';
  10637. string_buffer[bytes++] = '\\';
  10638. break;
  10639. }
  10640. default:
  10641. {
  10642. // escape control characters (0x00..0x1F) or, if
  10643. // ensure_ascii parameter is used, non-ASCII characters
  10644. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  10645. {
  10646. if (codepoint <= 0xFFFF)
  10647. {
  10648. (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x",
  10649. static_cast<std::uint16_t>(codepoint));
  10650. bytes += 6;
  10651. }
  10652. else
  10653. {
  10654. (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  10655. static_cast<std::uint16_t>(0xD7C0u + (codepoint >> 10u)),
  10656. static_cast<std::uint16_t>(0xDC00u + (codepoint & 0x3FFu)));
  10657. bytes += 12;
  10658. }
  10659. }
  10660. else
  10661. {
  10662. // copy byte to buffer (all previous bytes
  10663. // been copied have in default case above)
  10664. string_buffer[bytes++] = s[i];
  10665. }
  10666. break;
  10667. }
  10668. }
  10669. // write buffer and reset index; there must be 13 bytes
  10670. // left, as this is the maximal number of bytes to be
  10671. // written ("\uxxxx\uxxxx\0") for one code point
  10672. if (string_buffer.size() - bytes < 13)
  10673. {
  10674. o->write_characters(string_buffer.data(), bytes);
  10675. bytes = 0;
  10676. }
  10677. // remember the byte position of this accept
  10678. bytes_after_last_accept = bytes;
  10679. undumped_chars = 0;
  10680. break;
  10681. }
  10682. case UTF8_REJECT: // decode found invalid UTF-8 byte
  10683. {
  10684. switch (error_handler)
  10685. {
  10686. case error_handler_t::strict:
  10687. {
  10688. std::string sn(3, '\0');
  10689. (std::snprintf)(&sn[0], sn.size(), "%.2X", byte);
  10690. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  10691. }
  10692. case error_handler_t::ignore:
  10693. case error_handler_t::replace:
  10694. {
  10695. // in case we saw this character the first time, we
  10696. // would like to read it again, because the byte
  10697. // may be OK for itself, but just not OK for the
  10698. // previous sequence
  10699. if (undumped_chars > 0)
  10700. {
  10701. --i;
  10702. }
  10703. // reset length buffer to the last accepted index;
  10704. // thus removing/ignoring the invalid characters
  10705. bytes = bytes_after_last_accept;
  10706. if (error_handler == error_handler_t::replace)
  10707. {
  10708. // add a replacement character
  10709. if (ensure_ascii)
  10710. {
  10711. string_buffer[bytes++] = '\\';
  10712. string_buffer[bytes++] = 'u';
  10713. string_buffer[bytes++] = 'f';
  10714. string_buffer[bytes++] = 'f';
  10715. string_buffer[bytes++] = 'f';
  10716. string_buffer[bytes++] = 'd';
  10717. }
  10718. else
  10719. {
  10720. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF');
  10721. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF');
  10722. string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD');
  10723. }
  10724. // write buffer and reset index; there must be 13 bytes
  10725. // left, as this is the maximal number of bytes to be
  10726. // written ("\uxxxx\uxxxx\0") for one code point
  10727. if (string_buffer.size() - bytes < 13)
  10728. {
  10729. o->write_characters(string_buffer.data(), bytes);
  10730. bytes = 0;
  10731. }
  10732. bytes_after_last_accept = bytes;
  10733. }
  10734. undumped_chars = 0;
  10735. // continue processing the string
  10736. state = UTF8_ACCEPT;
  10737. break;
  10738. }
  10739. default: // LCOV_EXCL_LINE
  10740. assert(false); // LCOV_EXCL_LINE
  10741. }
  10742. break;
  10743. }
  10744. default: // decode found yet incomplete multi-byte code point
  10745. {
  10746. if (not ensure_ascii)
  10747. {
  10748. // code point will not be escaped - copy byte to buffer
  10749. string_buffer[bytes++] = s[i];
  10750. }
  10751. ++undumped_chars;
  10752. break;
  10753. }
  10754. }
  10755. }
  10756. // we finished processing the string
  10757. if (JSON_LIKELY(state == UTF8_ACCEPT))
  10758. {
  10759. // write buffer
  10760. if (bytes > 0)
  10761. {
  10762. o->write_characters(string_buffer.data(), bytes);
  10763. }
  10764. }
  10765. else
  10766. {
  10767. // we finish reading, but do not accept: string was incomplete
  10768. switch (error_handler)
  10769. {
  10770. case error_handler_t::strict:
  10771. {
  10772. std::string sn(3, '\0');
  10773. (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<std::uint8_t>(s.back()));
  10774. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  10775. }
  10776. case error_handler_t::ignore:
  10777. {
  10778. // write all accepted bytes
  10779. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  10780. break;
  10781. }
  10782. case error_handler_t::replace:
  10783. {
  10784. // write all accepted bytes
  10785. o->write_characters(string_buffer.data(), bytes_after_last_accept);
  10786. // add a replacement character
  10787. if (ensure_ascii)
  10788. {
  10789. o->write_characters("\\ufffd", 6);
  10790. }
  10791. else
  10792. {
  10793. o->write_characters("\xEF\xBF\xBD", 3);
  10794. }
  10795. break;
  10796. }
  10797. default: // LCOV_EXCL_LINE
  10798. assert(false); // LCOV_EXCL_LINE
  10799. }
  10800. }
  10801. }
  10802. /*!
  10803. @brief count digits
  10804. Count the number of decimal (base 10) digits for an input unsigned integer.
  10805. @param[in] x unsigned integer number to count its digits
  10806. @return number of decimal digits
  10807. */
  10808. inline unsigned int count_digits(number_unsigned_t x) noexcept
  10809. {
  10810. unsigned int n_digits = 1;
  10811. for (;;)
  10812. {
  10813. if (x < 10)
  10814. {
  10815. return n_digits;
  10816. }
  10817. if (x < 100)
  10818. {
  10819. return n_digits + 1;
  10820. }
  10821. if (x < 1000)
  10822. {
  10823. return n_digits + 2;
  10824. }
  10825. if (x < 10000)
  10826. {
  10827. return n_digits + 3;
  10828. }
  10829. x = x / 10000u;
  10830. n_digits += 4;
  10831. }
  10832. }
  10833. /*!
  10834. @brief dump an integer
  10835. Dump a given integer to output stream @a o. Works internally with
  10836. @a number_buffer.
  10837. @param[in] x integer number (signed or unsigned) to dump
  10838. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  10839. */
  10840. template<typename NumberType, detail::enable_if_t<
  10841. std::is_same<NumberType, number_unsigned_t>::value or
  10842. std::is_same<NumberType, number_integer_t>::value,
  10843. int> = 0>
  10844. void dump_integer(NumberType x)
  10845. {
  10846. static constexpr std::array<std::array<char, 2>, 100> digits_to_99
  10847. {
  10848. {
  10849. {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}},
  10850. {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}},
  10851. {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}},
  10852. {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}},
  10853. {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}},
  10854. {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}},
  10855. {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}},
  10856. {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}},
  10857. {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}},
  10858. {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}},
  10859. }
  10860. };
  10861. // special case for "0"
  10862. if (x == 0)
  10863. {
  10864. o->write_character('0');
  10865. return;
  10866. }
  10867. // use a pointer to fill the buffer
  10868. auto buffer_ptr = number_buffer.begin();
  10869. const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755
  10870. number_unsigned_t abs_value;
  10871. unsigned int n_chars;
  10872. if (is_negative)
  10873. {
  10874. *buffer_ptr = '-';
  10875. abs_value = static_cast<number_unsigned_t>(std::abs(static_cast<std::intmax_t>(x)));
  10876. // account one more byte for the minus sign
  10877. n_chars = 1 + count_digits(abs_value);
  10878. }
  10879. else
  10880. {
  10881. abs_value = static_cast<number_unsigned_t>(x);
  10882. n_chars = count_digits(abs_value);
  10883. }
  10884. // spare 1 byte for '\0'
  10885. assert(n_chars < number_buffer.size() - 1);
  10886. // jump to the end to generate the string from backward
  10887. // so we later avoid reversing the result
  10888. buffer_ptr += n_chars;
  10889. // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu
  10890. // See: https://www.youtube.com/watch?v=o4-CwDo2zpg
  10891. while (abs_value >= 100)
  10892. {
  10893. const auto digits_index = static_cast<unsigned>((abs_value % 100));
  10894. abs_value /= 100;
  10895. *(--buffer_ptr) = digits_to_99[digits_index][1];
  10896. *(--buffer_ptr) = digits_to_99[digits_index][0];
  10897. }
  10898. if (abs_value >= 10)
  10899. {
  10900. const auto digits_index = static_cast<unsigned>(abs_value);
  10901. *(--buffer_ptr) = digits_to_99[digits_index][1];
  10902. *(--buffer_ptr) = digits_to_99[digits_index][0];
  10903. }
  10904. else
  10905. {
  10906. *(--buffer_ptr) = static_cast<char>('0' + abs_value);
  10907. }
  10908. o->write_characters(number_buffer.data(), n_chars);
  10909. }
  10910. /*!
  10911. @brief dump a floating-point number
  10912. Dump a given floating-point number to output stream @a o. Works internally
  10913. with @a number_buffer.
  10914. @param[in] x floating-point number to dump
  10915. */
  10916. void dump_float(number_float_t x)
  10917. {
  10918. // NaN / inf
  10919. if (not std::isfinite(x))
  10920. {
  10921. o->write_characters("null", 4);
  10922. return;
  10923. }
  10924. // If number_float_t is an IEEE-754 single or double precision number,
  10925. // use the Grisu2 algorithm to produce short numbers which are
  10926. // guaranteed to round-trip, using strtof and strtod, resp.
  10927. //
  10928. // NB: The test below works if <long double> == <double>.
  10929. static constexpr bool is_ieee_single_or_double
  10930. = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
  10931. (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
  10932. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  10933. }
  10934. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  10935. {
  10936. char* begin = number_buffer.data();
  10937. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  10938. o->write_characters(begin, static_cast<size_t>(end - begin));
  10939. }
  10940. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  10941. {
  10942. // get number of digits for a float -> text -> float round-trip
  10943. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  10944. // the actual conversion
  10945. std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  10946. // negative value indicates an error
  10947. assert(len > 0);
  10948. // check if buffer was large enough
  10949. assert(static_cast<std::size_t>(len) < number_buffer.size());
  10950. // erase thousands separator
  10951. if (thousands_sep != '\0')
  10952. {
  10953. const auto end = std::remove(number_buffer.begin(),
  10954. number_buffer.begin() + len, thousands_sep);
  10955. std::fill(end, number_buffer.end(), '\0');
  10956. assert((end - number_buffer.begin()) <= len);
  10957. len = (end - number_buffer.begin());
  10958. }
  10959. // convert decimal point to '.'
  10960. if (decimal_point != '\0' and decimal_point != '.')
  10961. {
  10962. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  10963. if (dec_pos != number_buffer.end())
  10964. {
  10965. *dec_pos = '.';
  10966. }
  10967. }
  10968. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  10969. // determine if need to append ".0"
  10970. const bool value_is_int_like =
  10971. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  10972. [](char c)
  10973. {
  10974. return c == '.' or c == 'e';
  10975. });
  10976. if (value_is_int_like)
  10977. {
  10978. o->write_characters(".0", 2);
  10979. }
  10980. }
  10981. /*!
  10982. @brief check whether a string is UTF-8 encoded
  10983. The function checks each byte of a string whether it is UTF-8 encoded. The
  10984. result of the check is stored in the @a state parameter. The function must
  10985. be called initially with state 0 (accept). State 1 means the string must
  10986. be rejected, because the current byte is not allowed. If the string is
  10987. completely processed, but the state is non-zero, the string ended
  10988. prematurely; that is, the last byte indicated more bytes should have
  10989. followed.
  10990. @param[in,out] state the state of the decoding
  10991. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  10992. @param[in] byte next byte to decode
  10993. @return new state
  10994. @note The function has been edited: a std::array is used.
  10995. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  10996. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  10997. */
  10998. static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept
  10999. {
  11000. static const std::array<std::uint8_t, 400> utf8d =
  11001. {
  11002. {
  11003. 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
  11004. 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
  11005. 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
  11006. 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
  11007. 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
  11008. 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
  11009. 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
  11010. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  11011. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  11012. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  11013. 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
  11014. 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
  11015. 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
  11016. 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
  11017. }
  11018. };
  11019. const std::uint8_t type = utf8d[byte];
  11020. codep = (state != UTF8_ACCEPT)
  11021. ? (byte & 0x3fu) | (codep << 6u)
  11022. : (0xFFu >> type) & (byte);
  11023. state = utf8d[256u + state * 16u + type];
  11024. return state;
  11025. }
  11026. private:
  11027. /// the output of the serializer
  11028. output_adapter_t<char> o = nullptr;
  11029. /// a (hopefully) large enough character buffer
  11030. std::array<char, 64> number_buffer{{}};
  11031. /// the locale
  11032. const std::lconv* loc = nullptr;
  11033. /// the locale's thousand separator character
  11034. const char thousands_sep = '\0';
  11035. /// the locale's decimal point character
  11036. const char decimal_point = '\0';
  11037. /// string buffer
  11038. std::array<char, 512> string_buffer{{}};
  11039. /// the indentation character
  11040. const char indent_char;
  11041. /// the indentation string
  11042. string_t indent_string;
  11043. /// error_handler how to react on decoding errors
  11044. const error_handler_t error_handler;
  11045. };
  11046. } // namespace detail
  11047. } // namespace nlohmann
  11048. // #include <nlohmann/detail/value_t.hpp>
  11049. // #include <nlohmann/json_fwd.hpp>
  11050. /*!
  11051. @brief namespace for Niels Lohmann
  11052. @see https://github.com/nlohmann
  11053. @since version 1.0.0
  11054. */
  11055. namespace nlohmann
  11056. {
  11057. /*!
  11058. @brief a class to store JSON values
  11059. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  11060. in @ref object_t)
  11061. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  11062. in @ref array_t)
  11063. @tparam StringType type for JSON strings and object keys (`std::string` by
  11064. default; will be used in @ref string_t)
  11065. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  11066. in @ref boolean_t)
  11067. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  11068. default; will be used in @ref number_integer_t)
  11069. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  11070. `uint64_t` by default; will be used in @ref number_unsigned_t)
  11071. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  11072. default; will be used in @ref number_float_t)
  11073. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  11074. default)
  11075. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  11076. and `from_json()` (@ref adl_serializer by default)
  11077. @requirement The class satisfies the following concept requirements:
  11078. - Basic
  11079. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  11080. JSON values can be default constructed. The result will be a JSON null
  11081. value.
  11082. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  11083. A JSON value can be constructed from an rvalue argument.
  11084. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  11085. A JSON value can be copy-constructed from an lvalue expression.
  11086. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  11087. A JSON value van be assigned from an rvalue argument.
  11088. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  11089. A JSON value can be copy-assigned from an lvalue expression.
  11090. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  11091. JSON values can be destructed.
  11092. - Layout
  11093. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  11094. JSON values have
  11095. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  11096. All non-static data members are private and standard layout types, the
  11097. class has no virtual functions or (virtual) base classes.
  11098. - Library-wide
  11099. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  11100. JSON values can be compared with `==`, see @ref
  11101. operator==(const_reference,const_reference).
  11102. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  11103. JSON values can be compared with `<`, see @ref
  11104. operator<(const_reference,const_reference).
  11105. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  11106. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  11107. other compatible types, using unqualified function call @ref swap().
  11108. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  11109. JSON values can be compared against `std::nullptr_t` objects which are used
  11110. to model the `null` value.
  11111. - Container
  11112. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  11113. JSON values can be used like STL containers and provide iterator access.
  11114. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  11115. JSON values can be used like STL containers and provide reverse iterator
  11116. access.
  11117. @invariant The member variables @a m_value and @a m_type have the following
  11118. relationship:
  11119. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  11120. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  11121. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  11122. The invariants are checked by member function assert_invariant().
  11123. @internal
  11124. @note ObjectType trick from http://stackoverflow.com/a/9860911
  11125. @endinternal
  11126. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  11127. Format](http://rfc7159.net/rfc7159)
  11128. @since version 1.0.0
  11129. @nosubgrouping
  11130. */
  11131. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11132. class basic_json
  11133. {
  11134. private:
  11135. template<detail::value_t> friend struct detail::external_constructor;
  11136. friend ::nlohmann::json_pointer<basic_json>;
  11137. friend ::nlohmann::detail::parser<basic_json>;
  11138. friend ::nlohmann::detail::serializer<basic_json>;
  11139. template<typename BasicJsonType>
  11140. friend class ::nlohmann::detail::iter_impl;
  11141. template<typename BasicJsonType, typename CharType>
  11142. friend class ::nlohmann::detail::binary_writer;
  11143. template<typename BasicJsonType, typename SAX>
  11144. friend class ::nlohmann::detail::binary_reader;
  11145. template<typename BasicJsonType>
  11146. friend class ::nlohmann::detail::json_sax_dom_parser;
  11147. template<typename BasicJsonType>
  11148. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  11149. /// workaround type for MSVC
  11150. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  11151. // convenience aliases for types residing in namespace detail;
  11152. using lexer = ::nlohmann::detail::lexer<basic_json>;
  11153. using parser = ::nlohmann::detail::parser<basic_json>;
  11154. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  11155. template<typename BasicJsonType>
  11156. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  11157. template<typename BasicJsonType>
  11158. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  11159. template<typename Iterator>
  11160. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  11161. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  11162. template<typename CharType>
  11163. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  11164. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  11165. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  11166. using serializer = ::nlohmann::detail::serializer<basic_json>;
  11167. public:
  11168. using value_t = detail::value_t;
  11169. /// JSON Pointer, see @ref nlohmann::json_pointer
  11170. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  11171. template<typename T, typename SFINAE>
  11172. using json_serializer = JSONSerializer<T, SFINAE>;
  11173. /// how to treat decoding errors
  11174. using error_handler_t = detail::error_handler_t;
  11175. /// helper type for initializer lists of basic_json values
  11176. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  11177. using input_format_t = detail::input_format_t;
  11178. /// SAX interface type, see @ref nlohmann::json_sax
  11179. using json_sax_t = json_sax<basic_json>;
  11180. ////////////////
  11181. // exceptions //
  11182. ////////////////
  11183. /// @name exceptions
  11184. /// Classes to implement user-defined exceptions.
  11185. /// @{
  11186. /// @copydoc detail::exception
  11187. using exception = detail::exception;
  11188. /// @copydoc detail::parse_error
  11189. using parse_error = detail::parse_error;
  11190. /// @copydoc detail::invalid_iterator
  11191. using invalid_iterator = detail::invalid_iterator;
  11192. /// @copydoc detail::type_error
  11193. using type_error = detail::type_error;
  11194. /// @copydoc detail::out_of_range
  11195. using out_of_range = detail::out_of_range;
  11196. /// @copydoc detail::other_error
  11197. using other_error = detail::other_error;
  11198. /// @}
  11199. /////////////////////
  11200. // container types //
  11201. /////////////////////
  11202. /// @name container types
  11203. /// The canonic container types to use @ref basic_json like any other STL
  11204. /// container.
  11205. /// @{
  11206. /// the type of elements in a basic_json container
  11207. using value_type = basic_json;
  11208. /// the type of an element reference
  11209. using reference = value_type&;
  11210. /// the type of an element const reference
  11211. using const_reference = const value_type&;
  11212. /// a type to represent differences between iterators
  11213. using difference_type = std::ptrdiff_t;
  11214. /// a type to represent container sizes
  11215. using size_type = std::size_t;
  11216. /// the allocator type
  11217. using allocator_type = AllocatorType<basic_json>;
  11218. /// the type of an element pointer
  11219. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  11220. /// the type of an element const pointer
  11221. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  11222. /// an iterator for a basic_json container
  11223. using iterator = iter_impl<basic_json>;
  11224. /// a const iterator for a basic_json container
  11225. using const_iterator = iter_impl<const basic_json>;
  11226. /// a reverse iterator for a basic_json container
  11227. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  11228. /// a const reverse iterator for a basic_json container
  11229. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  11230. /// @}
  11231. /*!
  11232. @brief returns the allocator associated with the container
  11233. */
  11234. static allocator_type get_allocator()
  11235. {
  11236. return allocator_type();
  11237. }
  11238. /*!
  11239. @brief returns version information on the library
  11240. This function returns a JSON object with information about the library,
  11241. including the version number and information on the platform and compiler.
  11242. @return JSON object holding version information
  11243. key | description
  11244. ----------- | ---------------
  11245. `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).
  11246. `copyright` | The copyright line for the library as string.
  11247. `name` | The name of the library as string.
  11248. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  11249. `url` | The URL of the project as string.
  11250. `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).
  11251. @liveexample{The following code shows an example output of the `meta()`
  11252. function.,meta}
  11253. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11254. changes to any JSON value.
  11255. @complexity Constant.
  11256. @since 2.1.0
  11257. */
  11258. JSON_NODISCARD
  11259. static basic_json meta()
  11260. {
  11261. basic_json result;
  11262. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  11263. result["name"] = "JSON for Modern C++";
  11264. result["url"] = "https://github.com/nlohmann/json";
  11265. result["version"]["string"] =
  11266. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  11267. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  11268. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  11269. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  11270. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  11271. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  11272. #ifdef _WIN32
  11273. result["platform"] = "win32";
  11274. #elif defined __linux__
  11275. result["platform"] = "linux";
  11276. #elif defined __APPLE__
  11277. result["platform"] = "apple";
  11278. #elif defined __unix__
  11279. result["platform"] = "unix";
  11280. #else
  11281. result["platform"] = "unknown";
  11282. #endif
  11283. #if defined(__ICC) || defined(__INTEL_COMPILER)
  11284. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  11285. #elif defined(__clang__)
  11286. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  11287. #elif defined(__GNUC__) || defined(__GNUG__)
  11288. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  11289. #elif defined(__HP_cc) || defined(__HP_aCC)
  11290. result["compiler"] = "hp"
  11291. #elif defined(__IBMCPP__)
  11292. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  11293. #elif defined(_MSC_VER)
  11294. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  11295. #elif defined(__PGI)
  11296. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  11297. #elif defined(__SUNPRO_CC)
  11298. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  11299. #else
  11300. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  11301. #endif
  11302. #ifdef __cplusplus
  11303. result["compiler"]["c++"] = std::to_string(__cplusplus);
  11304. #else
  11305. result["compiler"]["c++"] = "unknown";
  11306. #endif
  11307. return result;
  11308. }
  11309. ///////////////////////////
  11310. // JSON value data types //
  11311. ///////////////////////////
  11312. /// @name JSON value data types
  11313. /// The data types to store a JSON value. These types are derived from
  11314. /// the template arguments passed to class @ref basic_json.
  11315. /// @{
  11316. #if defined(JSON_HAS_CPP_14)
  11317. // Use transparent comparator if possible, combined with perfect forwarding
  11318. // on find() and count() calls prevents unnecessary string construction.
  11319. using object_comparator_t = std::less<>;
  11320. #else
  11321. using object_comparator_t = std::less<StringType>;
  11322. #endif
  11323. /*!
  11324. @brief a type for an object
  11325. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  11326. > An object is an unordered collection of zero or more name/value pairs,
  11327. > where a name is a string and a value is a string, number, boolean, null,
  11328. > object, or array.
  11329. To store objects in C++, a type is defined by the template parameters
  11330. described below.
  11331. @tparam ObjectType the container to store objects (e.g., `std::map` or
  11332. `std::unordered_map`)
  11333. @tparam StringType the type of the keys or names (e.g., `std::string`).
  11334. The comparison function `std::less<StringType>` is used to order elements
  11335. inside the container.
  11336. @tparam AllocatorType the allocator to use for objects (e.g.,
  11337. `std::allocator`)
  11338. #### Default type
  11339. With the default values for @a ObjectType (`std::map`), @a StringType
  11340. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  11341. value for @a object_t is:
  11342. @code {.cpp}
  11343. std::map<
  11344. std::string, // key_type
  11345. basic_json, // value_type
  11346. std::less<std::string>, // key_compare
  11347. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  11348. >
  11349. @endcode
  11350. #### Behavior
  11351. The choice of @a object_t influences the behavior of the JSON class. With
  11352. the default type, objects have the following behavior:
  11353. - When all names are unique, objects will be interoperable in the sense
  11354. that all software implementations receiving that object will agree on
  11355. the name-value mappings.
  11356. - When the names within an object are not unique, it is unspecified which
  11357. one of the values for a given key will be chosen. For instance,
  11358. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  11359. `{"key": 2}`.
  11360. - Internally, name/value pairs are stored in lexicographical order of the
  11361. names. Objects will also be serialized (see @ref dump) in this order.
  11362. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  11363. and serialized as `{"a": 2, "b": 1}`.
  11364. - When comparing objects, the order of the name/value pairs is irrelevant.
  11365. This makes objects interoperable in the sense that they will not be
  11366. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  11367. `{"a": 2, "b": 1}` will be treated as equal.
  11368. #### Limits
  11369. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11370. > An implementation may set limits on the maximum depth of nesting.
  11371. In this class, the object's limit of nesting is not explicitly constrained.
  11372. However, a maximum depth of nesting may be introduced by the compiler or
  11373. runtime environment. A theoretical limit can be queried by calling the
  11374. @ref max_size function of a JSON object.
  11375. #### Storage
  11376. Objects are stored as pointers in a @ref basic_json type. That is, for any
  11377. access to object values, a pointer of type `object_t*` must be
  11378. dereferenced.
  11379. @sa @ref array_t -- type for an array value
  11380. @since version 1.0.0
  11381. @note The order name/value pairs are added to the object is *not*
  11382. preserved by the library. Therefore, iterating an object may return
  11383. name/value pairs in a different order than they were originally stored. In
  11384. fact, keys will be traversed in alphabetical order as `std::map` with
  11385. `std::less` is used by default. Please note this behavior conforms to [RFC
  11386. 7159](http://rfc7159.net/rfc7159), because any order implements the
  11387. specified "unordered" nature of JSON objects.
  11388. */
  11389. using object_t = ObjectType<StringType,
  11390. basic_json,
  11391. object_comparator_t,
  11392. AllocatorType<std::pair<const StringType,
  11393. basic_json>>>;
  11394. /*!
  11395. @brief a type for an array
  11396. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  11397. > An array is an ordered sequence of zero or more values.
  11398. To store objects in C++, a type is defined by the template parameters
  11399. explained below.
  11400. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  11401. `std::list`)
  11402. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  11403. #### Default type
  11404. With the default values for @a ArrayType (`std::vector`) and @a
  11405. AllocatorType (`std::allocator`), the default value for @a array_t is:
  11406. @code {.cpp}
  11407. std::vector<
  11408. basic_json, // value_type
  11409. std::allocator<basic_json> // allocator_type
  11410. >
  11411. @endcode
  11412. #### Limits
  11413. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11414. > An implementation may set limits on the maximum depth of nesting.
  11415. In this class, the array's limit of nesting is not explicitly constrained.
  11416. However, a maximum depth of nesting may be introduced by the compiler or
  11417. runtime environment. A theoretical limit can be queried by calling the
  11418. @ref max_size function of a JSON array.
  11419. #### Storage
  11420. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  11421. access to array values, a pointer of type `array_t*` must be dereferenced.
  11422. @sa @ref object_t -- type for an object value
  11423. @since version 1.0.0
  11424. */
  11425. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  11426. /*!
  11427. @brief a type for a string
  11428. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  11429. > A string is a sequence of zero or more Unicode characters.
  11430. To store objects in C++, a type is defined by the template parameter
  11431. described below. Unicode values are split by the JSON class into
  11432. byte-sized characters during deserialization.
  11433. @tparam StringType the container to store strings (e.g., `std::string`).
  11434. Note this container is used for keys/names in objects, see @ref object_t.
  11435. #### Default type
  11436. With the default values for @a StringType (`std::string`), the default
  11437. value for @a string_t is:
  11438. @code {.cpp}
  11439. std::string
  11440. @endcode
  11441. #### Encoding
  11442. Strings are stored in UTF-8 encoding. Therefore, functions like
  11443. `std::string::size()` or `std::string::length()` return the number of
  11444. bytes in the string rather than the number of characters or glyphs.
  11445. #### String comparison
  11446. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11447. > Software implementations are typically required to test names of object
  11448. > members for equality. Implementations that transform the textual
  11449. > representation into sequences of Unicode code units and then perform the
  11450. > comparison numerically, code unit by code unit, are interoperable in the
  11451. > sense that implementations will agree in all cases on equality or
  11452. > inequality of two strings. For example, implementations that compare
  11453. > strings with escaped characters unconverted may incorrectly find that
  11454. > `"a\\b"` and `"a\u005Cb"` are not equal.
  11455. This implementation is interoperable as it does compare strings code unit
  11456. by code unit.
  11457. #### Storage
  11458. String values are stored as pointers in a @ref basic_json type. That is,
  11459. for any access to string values, a pointer of type `string_t*` must be
  11460. dereferenced.
  11461. @since version 1.0.0
  11462. */
  11463. using string_t = StringType;
  11464. /*!
  11465. @brief a type for a boolean
  11466. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  11467. type which differentiates the two literals `true` and `false`.
  11468. To store objects in C++, a type is defined by the template parameter @a
  11469. BooleanType which chooses the type to use.
  11470. #### Default type
  11471. With the default values for @a BooleanType (`bool`), the default value for
  11472. @a boolean_t is:
  11473. @code {.cpp}
  11474. bool
  11475. @endcode
  11476. #### Storage
  11477. Boolean values are stored directly inside a @ref basic_json type.
  11478. @since version 1.0.0
  11479. */
  11480. using boolean_t = BooleanType;
  11481. /*!
  11482. @brief a type for a number (integer)
  11483. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11484. > The representation of numbers is similar to that used in most
  11485. > programming languages. A number is represented in base 10 using decimal
  11486. > digits. It contains an integer component that may be prefixed with an
  11487. > optional minus sign, which may be followed by a fraction part and/or an
  11488. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11489. > cannot be represented in the grammar below (such as Infinity and NaN)
  11490. > are not permitted.
  11491. This description includes both integer and floating-point numbers.
  11492. However, C++ allows more precise storage if it is known whether the number
  11493. is a signed integer, an unsigned integer or a floating-point number.
  11494. Therefore, three different types, @ref number_integer_t, @ref
  11495. number_unsigned_t and @ref number_float_t are used.
  11496. To store integer numbers in C++, a type is defined by the template
  11497. parameter @a NumberIntegerType which chooses the type to use.
  11498. #### Default type
  11499. With the default values for @a NumberIntegerType (`int64_t`), the default
  11500. value for @a number_integer_t is:
  11501. @code {.cpp}
  11502. int64_t
  11503. @endcode
  11504. #### Default behavior
  11505. - The restrictions about leading zeros is not enforced in C++. Instead,
  11506. leading zeros in integer literals lead to an interpretation as octal
  11507. number. Internally, the value will be stored as decimal number. For
  11508. instance, the C++ integer literal `010` will be serialized to `8`.
  11509. During deserialization, leading zeros yield an error.
  11510. - Not-a-number (NaN) values will be serialized to `null`.
  11511. #### Limits
  11512. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11513. > An implementation may set limits on the range and precision of numbers.
  11514. When the default type is used, the maximal integer number that can be
  11515. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  11516. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  11517. that are out of range will yield over/underflow when used in a
  11518. constructor. During deserialization, too large or small integer numbers
  11519. will be automatically be stored as @ref number_unsigned_t or @ref
  11520. number_float_t.
  11521. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11522. > Note that when such software is used, numbers that are integers and are
  11523. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11524. > that implementations will agree exactly on their numeric values.
  11525. As this range is a subrange of the exactly supported range [INT64_MIN,
  11526. INT64_MAX], this class's integer type is interoperable.
  11527. #### Storage
  11528. Integer number values are stored directly inside a @ref basic_json type.
  11529. @sa @ref number_float_t -- type for number values (floating-point)
  11530. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11531. @since version 1.0.0
  11532. */
  11533. using number_integer_t = NumberIntegerType;
  11534. /*!
  11535. @brief a type for a number (unsigned)
  11536. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11537. > The representation of numbers is similar to that used in most
  11538. > programming languages. A number is represented in base 10 using decimal
  11539. > digits. It contains an integer component that may be prefixed with an
  11540. > optional minus sign, which may be followed by a fraction part and/or an
  11541. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11542. > cannot be represented in the grammar below (such as Infinity and NaN)
  11543. > are not permitted.
  11544. This description includes both integer and floating-point numbers.
  11545. However, C++ allows more precise storage if it is known whether the number
  11546. is a signed integer, an unsigned integer or a floating-point number.
  11547. Therefore, three different types, @ref number_integer_t, @ref
  11548. number_unsigned_t and @ref number_float_t are used.
  11549. To store unsigned integer numbers in C++, a type is defined by the
  11550. template parameter @a NumberUnsignedType which chooses the type to use.
  11551. #### Default type
  11552. With the default values for @a NumberUnsignedType (`uint64_t`), the
  11553. default value for @a number_unsigned_t is:
  11554. @code {.cpp}
  11555. uint64_t
  11556. @endcode
  11557. #### Default behavior
  11558. - The restrictions about leading zeros is not enforced in C++. Instead,
  11559. leading zeros in integer literals lead to an interpretation as octal
  11560. number. Internally, the value will be stored as decimal number. For
  11561. instance, the C++ integer literal `010` will be serialized to `8`.
  11562. During deserialization, leading zeros yield an error.
  11563. - Not-a-number (NaN) values will be serialized to `null`.
  11564. #### Limits
  11565. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  11566. > An implementation may set limits on the range and precision of numbers.
  11567. When the default type is used, the maximal integer number that can be
  11568. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  11569. number that can be stored is `0`. Integer numbers that are out of range
  11570. will yield over/underflow when used in a constructor. During
  11571. deserialization, too large or small integer numbers will be automatically
  11572. be stored as @ref number_integer_t or @ref number_float_t.
  11573. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  11574. > Note that when such software is used, numbers that are integers and are
  11575. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  11576. > that implementations will agree exactly on their numeric values.
  11577. As this range is a subrange (when considered in conjunction with the
  11578. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  11579. this class's integer type is interoperable.
  11580. #### Storage
  11581. Integer number values are stored directly inside a @ref basic_json type.
  11582. @sa @ref number_float_t -- type for number values (floating-point)
  11583. @sa @ref number_integer_t -- type for number values (integer)
  11584. @since version 2.0.0
  11585. */
  11586. using number_unsigned_t = NumberUnsignedType;
  11587. /*!
  11588. @brief a type for a number (floating-point)
  11589. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  11590. > The representation of numbers is similar to that used in most
  11591. > programming languages. A number is represented in base 10 using decimal
  11592. > digits. It contains an integer component that may be prefixed with an
  11593. > optional minus sign, which may be followed by a fraction part and/or an
  11594. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  11595. > cannot be represented in the grammar below (such as Infinity and NaN)
  11596. > are not permitted.
  11597. This description includes both integer and floating-point numbers.
  11598. However, C++ allows more precise storage if it is known whether the number
  11599. is a signed integer, an unsigned integer or a floating-point number.
  11600. Therefore, three different types, @ref number_integer_t, @ref
  11601. number_unsigned_t and @ref number_float_t are used.
  11602. To store floating-point numbers in C++, a type is defined by the template
  11603. parameter @a NumberFloatType which chooses the type to use.
  11604. #### Default type
  11605. With the default values for @a NumberFloatType (`double`), the default
  11606. value for @a number_float_t is:
  11607. @code {.cpp}
  11608. double
  11609. @endcode
  11610. #### Default behavior
  11611. - The restrictions about leading zeros is not enforced in C++. Instead,
  11612. leading zeros in floating-point literals will be ignored. Internally,
  11613. the value will be stored as decimal number. For instance, the C++
  11614. floating-point literal `01.2` will be serialized to `1.2`. During
  11615. deserialization, leading zeros yield an error.
  11616. - Not-a-number (NaN) values will be serialized to `null`.
  11617. #### Limits
  11618. [RFC 7159](http://rfc7159.net/rfc7159) states:
  11619. > This specification allows implementations to set limits on the range and
  11620. > precision of numbers accepted. Since software that implements IEEE
  11621. > 754-2008 binary64 (double precision) numbers is generally available and
  11622. > widely used, good interoperability can be achieved by implementations
  11623. > that expect no more precision or range than these provide, in the sense
  11624. > that implementations will approximate JSON numbers within the expected
  11625. > precision.
  11626. This implementation does exactly follow this approach, as it uses double
  11627. precision floating-point numbers. Note values smaller than
  11628. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  11629. will be stored as NaN internally and be serialized to `null`.
  11630. #### Storage
  11631. Floating-point number values are stored directly inside a @ref basic_json
  11632. type.
  11633. @sa @ref number_integer_t -- type for number values (integer)
  11634. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  11635. @since version 1.0.0
  11636. */
  11637. using number_float_t = NumberFloatType;
  11638. /// @}
  11639. private:
  11640. /// helper for exception-safe object creation
  11641. template<typename T, typename... Args>
  11642. static T* create(Args&& ... args)
  11643. {
  11644. AllocatorType<T> alloc;
  11645. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  11646. auto deleter = [&](T * object)
  11647. {
  11648. AllocatorTraits::deallocate(alloc, object, 1);
  11649. };
  11650. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  11651. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  11652. assert(object != nullptr);
  11653. return object.release();
  11654. }
  11655. ////////////////////////
  11656. // JSON value storage //
  11657. ////////////////////////
  11658. /*!
  11659. @brief a JSON value
  11660. The actual storage for a JSON value of the @ref basic_json class. This
  11661. union combines the different storage types for the JSON value types
  11662. defined in @ref value_t.
  11663. JSON type | value_t type | used type
  11664. --------- | --------------- | ------------------------
  11665. object | object | pointer to @ref object_t
  11666. array | array | pointer to @ref array_t
  11667. string | string | pointer to @ref string_t
  11668. boolean | boolean | @ref boolean_t
  11669. number | number_integer | @ref number_integer_t
  11670. number | number_unsigned | @ref number_unsigned_t
  11671. number | number_float | @ref number_float_t
  11672. null | null | *no value is stored*
  11673. @note Variable-length types (objects, arrays, and strings) are stored as
  11674. pointers. The size of the union should not exceed 64 bits if the default
  11675. value types are used.
  11676. @since version 1.0.0
  11677. */
  11678. union json_value
  11679. {
  11680. /// object (stored with pointer to save storage)
  11681. object_t* object;
  11682. /// array (stored with pointer to save storage)
  11683. array_t* array;
  11684. /// string (stored with pointer to save storage)
  11685. string_t* string;
  11686. /// boolean
  11687. boolean_t boolean;
  11688. /// number (integer)
  11689. number_integer_t number_integer;
  11690. /// number (unsigned integer)
  11691. number_unsigned_t number_unsigned;
  11692. /// number (floating-point)
  11693. number_float_t number_float;
  11694. /// default constructor (for null values)
  11695. json_value() = default;
  11696. /// constructor for booleans
  11697. json_value(boolean_t v) noexcept : boolean(v) {}
  11698. /// constructor for numbers (integer)
  11699. json_value(number_integer_t v) noexcept : number_integer(v) {}
  11700. /// constructor for numbers (unsigned)
  11701. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  11702. /// constructor for numbers (floating-point)
  11703. json_value(number_float_t v) noexcept : number_float(v) {}
  11704. /// constructor for empty values of a given type
  11705. json_value(value_t t)
  11706. {
  11707. switch (t)
  11708. {
  11709. case value_t::object:
  11710. {
  11711. object = create<object_t>();
  11712. break;
  11713. }
  11714. case value_t::array:
  11715. {
  11716. array = create<array_t>();
  11717. break;
  11718. }
  11719. case value_t::string:
  11720. {
  11721. string = create<string_t>("");
  11722. break;
  11723. }
  11724. case value_t::boolean:
  11725. {
  11726. boolean = boolean_t(false);
  11727. break;
  11728. }
  11729. case value_t::number_integer:
  11730. {
  11731. number_integer = number_integer_t(0);
  11732. break;
  11733. }
  11734. case value_t::number_unsigned:
  11735. {
  11736. number_unsigned = number_unsigned_t(0);
  11737. break;
  11738. }
  11739. case value_t::number_float:
  11740. {
  11741. number_float = number_float_t(0.0);
  11742. break;
  11743. }
  11744. case value_t::null:
  11745. {
  11746. object = nullptr; // silence warning, see #821
  11747. break;
  11748. }
  11749. default:
  11750. {
  11751. object = nullptr; // silence warning, see #821
  11752. if (JSON_UNLIKELY(t == value_t::null))
  11753. {
  11754. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.6.1")); // LCOV_EXCL_LINE
  11755. }
  11756. break;
  11757. }
  11758. }
  11759. }
  11760. /// constructor for strings
  11761. json_value(const string_t& value)
  11762. {
  11763. string = create<string_t>(value);
  11764. }
  11765. /// constructor for rvalue strings
  11766. json_value(string_t&& value)
  11767. {
  11768. string = create<string_t>(std::move(value));
  11769. }
  11770. /// constructor for objects
  11771. json_value(const object_t& value)
  11772. {
  11773. object = create<object_t>(value);
  11774. }
  11775. /// constructor for rvalue objects
  11776. json_value(object_t&& value)
  11777. {
  11778. object = create<object_t>(std::move(value));
  11779. }
  11780. /// constructor for arrays
  11781. json_value(const array_t& value)
  11782. {
  11783. array = create<array_t>(value);
  11784. }
  11785. /// constructor for rvalue arrays
  11786. json_value(array_t&& value)
  11787. {
  11788. array = create<array_t>(std::move(value));
  11789. }
  11790. void destroy(value_t t) noexcept
  11791. {
  11792. switch (t)
  11793. {
  11794. case value_t::object:
  11795. {
  11796. AllocatorType<object_t> alloc;
  11797. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  11798. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  11799. break;
  11800. }
  11801. case value_t::array:
  11802. {
  11803. AllocatorType<array_t> alloc;
  11804. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  11805. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  11806. break;
  11807. }
  11808. case value_t::string:
  11809. {
  11810. AllocatorType<string_t> alloc;
  11811. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  11812. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  11813. break;
  11814. }
  11815. default:
  11816. {
  11817. break;
  11818. }
  11819. }
  11820. }
  11821. };
  11822. /*!
  11823. @brief checks the class invariants
  11824. This function asserts the class invariants. It needs to be called at the
  11825. end of every constructor to make sure that created objects respect the
  11826. invariant. Furthermore, it has to be called each time the type of a JSON
  11827. value is changed, because the invariant expresses a relationship between
  11828. @a m_type and @a m_value.
  11829. */
  11830. void assert_invariant() const noexcept
  11831. {
  11832. assert(m_type != value_t::object or m_value.object != nullptr);
  11833. assert(m_type != value_t::array or m_value.array != nullptr);
  11834. assert(m_type != value_t::string or m_value.string != nullptr);
  11835. }
  11836. public:
  11837. //////////////////////////
  11838. // JSON parser callback //
  11839. //////////////////////////
  11840. /*!
  11841. @brief parser event types
  11842. The parser callback distinguishes the following events:
  11843. - `object_start`: the parser read `{` and started to process a JSON object
  11844. - `key`: the parser read a key of a value in an object
  11845. - `object_end`: the parser read `}` and finished processing a JSON object
  11846. - `array_start`: the parser read `[` and started to process a JSON array
  11847. - `array_end`: the parser read `]` and finished processing a JSON array
  11848. - `value`: the parser finished reading a JSON value
  11849. @image html callback_events.png "Example when certain parse events are triggered"
  11850. @sa @ref parser_callback_t for more information and examples
  11851. */
  11852. using parse_event_t = typename parser::parse_event_t;
  11853. /*!
  11854. @brief per-element parser callback type
  11855. With a parser callback function, the result of parsing a JSON text can be
  11856. influenced. When passed to @ref parse, it is called on certain events
  11857. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  11858. depth @a depth and context JSON value @a parsed. The return value of the
  11859. callback function is a boolean indicating whether the element that emitted
  11860. the callback shall be kept or not.
  11861. We distinguish six scenarios (determined by the event type) in which the
  11862. callback function can be called. The following table describes the values
  11863. of the parameters @a depth, @a event, and @a parsed.
  11864. parameter @a event | description | parameter @a depth | parameter @a parsed
  11865. ------------------ | ----------- | ------------------ | -------------------
  11866. 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
  11867. 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
  11868. 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
  11869. 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
  11870. 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
  11871. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  11872. @image html callback_events.png "Example when certain parse events are triggered"
  11873. Discarding a value (i.e., returning `false`) has different effects
  11874. depending on the context in which function was called:
  11875. - Discarded values in structured types are skipped. That is, the parser
  11876. will behave as if the discarded value was never read.
  11877. - In case a value outside a structured type is skipped, it is replaced
  11878. with `null`. This case happens if the top-level element is skipped.
  11879. @param[in] depth the depth of the recursion during parsing
  11880. @param[in] event an event of type parse_event_t indicating the context in
  11881. the callback function has been called
  11882. @param[in,out] parsed the current intermediate parse result; note that
  11883. writing to this value has no effect for parse_event_t::key events
  11884. @return Whether the JSON value which called the function during parsing
  11885. should be kept (`true`) or not (`false`). In the latter case, it is either
  11886. skipped completely or replaced by an empty discarded object.
  11887. @sa @ref parse for examples
  11888. @since version 1.0.0
  11889. */
  11890. using parser_callback_t = typename parser::parser_callback_t;
  11891. //////////////////
  11892. // constructors //
  11893. //////////////////
  11894. /// @name constructors and destructors
  11895. /// Constructors of class @ref basic_json, copy/move constructor, copy
  11896. /// assignment, static functions creating objects, and the destructor.
  11897. /// @{
  11898. /*!
  11899. @brief create an empty value with a given type
  11900. Create an empty JSON value with a given type. The value will be default
  11901. initialized with an empty value which depends on the type:
  11902. Value type | initial value
  11903. ----------- | -------------
  11904. null | `null`
  11905. boolean | `false`
  11906. string | `""`
  11907. number | `0`
  11908. object | `{}`
  11909. array | `[]`
  11910. @param[in] v the type of the value to create
  11911. @complexity Constant.
  11912. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11913. changes to any JSON value.
  11914. @liveexample{The following code shows the constructor for different @ref
  11915. value_t values,basic_json__value_t}
  11916. @sa @ref clear() -- restores the postcondition of this constructor
  11917. @since version 1.0.0
  11918. */
  11919. basic_json(const value_t v)
  11920. : m_type(v), m_value(v)
  11921. {
  11922. assert_invariant();
  11923. }
  11924. /*!
  11925. @brief create a null object
  11926. Create a `null` JSON value. It either takes a null pointer as parameter
  11927. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  11928. The passed null pointer itself is not read -- it is only used to choose
  11929. the right constructor.
  11930. @complexity Constant.
  11931. @exceptionsafety No-throw guarantee: this constructor never throws
  11932. exceptions.
  11933. @liveexample{The following code shows the constructor with and without a
  11934. null pointer parameter.,basic_json__nullptr_t}
  11935. @since version 1.0.0
  11936. */
  11937. basic_json(std::nullptr_t = nullptr) noexcept
  11938. : basic_json(value_t::null)
  11939. {
  11940. assert_invariant();
  11941. }
  11942. /*!
  11943. @brief create a JSON value
  11944. This is a "catch all" constructor for all compatible JSON types; that is,
  11945. types for which a `to_json()` method exists. The constructor forwards the
  11946. parameter @a val to that method (to `json_serializer<U>::to_json` method
  11947. with `U = uncvref_t<CompatibleType>`, to be exact).
  11948. Template type @a CompatibleType includes, but is not limited to, the
  11949. following types:
  11950. - **arrays**: @ref array_t and all kinds of compatible containers such as
  11951. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  11952. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  11953. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  11954. which a @ref basic_json value can be constructed.
  11955. - **objects**: @ref object_t and all kinds of compatible associative
  11956. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  11957. and `std::unordered_multimap` with a `key_type` compatible to
  11958. @ref string_t and a `value_type` from which a @ref basic_json value can
  11959. be constructed.
  11960. - **strings**: @ref string_t, string literals, and all compatible string
  11961. containers can be used.
  11962. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  11963. @ref number_float_t, and all convertible number types such as `int`,
  11964. `size_t`, `int64_t`, `float` or `double` can be used.
  11965. - **boolean**: @ref boolean_t / `bool` can be used.
  11966. See the examples below.
  11967. @tparam CompatibleType a type such that:
  11968. - @a CompatibleType is not derived from `std::istream`,
  11969. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  11970. constructors),
  11971. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  11972. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  11973. @ref json_pointer, @ref iterator, etc ...)
  11974. - @ref @ref json_serializer<U> has a
  11975. `to_json(basic_json_t&, CompatibleType&&)` method
  11976. @tparam U = `uncvref_t<CompatibleType>`
  11977. @param[in] val the value to be forwarded to the respective constructor
  11978. @complexity Usually linear in the size of the passed @a val, also
  11979. depending on the implementation of the called `to_json()`
  11980. method.
  11981. @exceptionsafety Depends on the called constructor. For types directly
  11982. supported by the library (i.e., all types for which no `to_json()` function
  11983. was provided), strong guarantee holds: if an exception is thrown, there are
  11984. no changes to any JSON value.
  11985. @liveexample{The following code shows the constructor with several
  11986. compatible types.,basic_json__CompatibleType}
  11987. @since version 2.1.0
  11988. */
  11989. template <typename CompatibleType,
  11990. typename U = detail::uncvref_t<CompatibleType>,
  11991. detail::enable_if_t<
  11992. not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  11993. basic_json(CompatibleType && val) noexcept(noexcept(
  11994. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  11995. std::forward<CompatibleType>(val))))
  11996. {
  11997. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  11998. assert_invariant();
  11999. }
  12000. /*!
  12001. @brief create a JSON value from an existing one
  12002. This is a constructor for existing @ref basic_json types.
  12003. It does not hijack copy/move constructors, since the parameter has different
  12004. template arguments than the current ones.
  12005. The constructor tries to convert the internal @ref m_value of the parameter.
  12006. @tparam BasicJsonType a type such that:
  12007. - @a BasicJsonType is a @ref basic_json type.
  12008. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  12009. @param[in] val the @ref basic_json value to be converted.
  12010. @complexity Usually linear in the size of the passed @a val, also
  12011. depending on the implementation of the called `to_json()`
  12012. method.
  12013. @exceptionsafety Depends on the called constructor. For types directly
  12014. supported by the library (i.e., all types for which no `to_json()` function
  12015. was provided), strong guarantee holds: if an exception is thrown, there are
  12016. no changes to any JSON value.
  12017. @since version 3.2.0
  12018. */
  12019. template <typename BasicJsonType,
  12020. detail::enable_if_t<
  12021. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  12022. basic_json(const BasicJsonType& val)
  12023. {
  12024. using other_boolean_t = typename BasicJsonType::boolean_t;
  12025. using other_number_float_t = typename BasicJsonType::number_float_t;
  12026. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  12027. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  12028. using other_string_t = typename BasicJsonType::string_t;
  12029. using other_object_t = typename BasicJsonType::object_t;
  12030. using other_array_t = typename BasicJsonType::array_t;
  12031. switch (val.type())
  12032. {
  12033. case value_t::boolean:
  12034. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  12035. break;
  12036. case value_t::number_float:
  12037. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  12038. break;
  12039. case value_t::number_integer:
  12040. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  12041. break;
  12042. case value_t::number_unsigned:
  12043. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  12044. break;
  12045. case value_t::string:
  12046. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  12047. break;
  12048. case value_t::object:
  12049. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  12050. break;
  12051. case value_t::array:
  12052. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  12053. break;
  12054. case value_t::null:
  12055. *this = nullptr;
  12056. break;
  12057. case value_t::discarded:
  12058. m_type = value_t::discarded;
  12059. break;
  12060. default: // LCOV_EXCL_LINE
  12061. assert(false); // LCOV_EXCL_LINE
  12062. }
  12063. assert_invariant();
  12064. }
  12065. /*!
  12066. @brief create a container (array or object) from an initializer list
  12067. Creates a JSON value of type array or object from the passed initializer
  12068. list @a init. In case @a type_deduction is `true` (default), the type of
  12069. the JSON value to be created is deducted from the initializer list @a init
  12070. according to the following rules:
  12071. 1. If the list is empty, an empty JSON object value `{}` is created.
  12072. 2. If the list consists of pairs whose first element is a string, a JSON
  12073. object value is created where the first elements of the pairs are
  12074. treated as keys and the second elements are as values.
  12075. 3. In all other cases, an array is created.
  12076. The rules aim to create the best fit between a C++ initializer list and
  12077. JSON values. The rationale is as follows:
  12078. 1. The empty initializer list is written as `{}` which is exactly an empty
  12079. JSON object.
  12080. 2. C++ has no way of describing mapped types other than to list a list of
  12081. pairs. As JSON requires that keys must be of type string, rule 2 is the
  12082. weakest constraint one can pose on initializer lists to interpret them
  12083. as an object.
  12084. 3. In all other cases, the initializer list could not be interpreted as
  12085. JSON object type, so interpreting it as JSON array type is safe.
  12086. With the rules described above, the following JSON values cannot be
  12087. expressed by an initializer list:
  12088. - the empty array (`[]`): use @ref array(initializer_list_t)
  12089. with an empty initializer list in this case
  12090. - arrays whose elements satisfy rule 2: use @ref
  12091. array(initializer_list_t) with the same initializer list
  12092. in this case
  12093. @note When used without parentheses around an empty initializer list, @ref
  12094. basic_json() is called instead of this function, yielding the JSON null
  12095. value.
  12096. @param[in] init initializer list with JSON values
  12097. @param[in] type_deduction internal parameter; when set to `true`, the type
  12098. of the JSON value is deducted from the initializer list @a init; when set
  12099. to `false`, the type provided via @a manual_type is forced. This mode is
  12100. used by the functions @ref array(initializer_list_t) and
  12101. @ref object(initializer_list_t).
  12102. @param[in] manual_type internal parameter; when @a type_deduction is set
  12103. to `false`, the created JSON value will use the provided type (only @ref
  12104. value_t::array and @ref value_t::object are valid); when @a type_deduction
  12105. is set to `true`, this parameter has no effect
  12106. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  12107. `value_t::object`, but @a init contains an element which is not a pair
  12108. whose first element is a string. In this case, the constructor could not
  12109. create an object. If @a type_deduction would have be `true`, an array
  12110. would have been created. See @ref object(initializer_list_t)
  12111. for an example.
  12112. @complexity Linear in the size of the initializer list @a init.
  12113. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12114. changes to any JSON value.
  12115. @liveexample{The example below shows how JSON values are created from
  12116. initializer lists.,basic_json__list_init_t}
  12117. @sa @ref array(initializer_list_t) -- create a JSON array
  12118. value from an initializer list
  12119. @sa @ref object(initializer_list_t) -- create a JSON object
  12120. value from an initializer list
  12121. @since version 1.0.0
  12122. */
  12123. basic_json(initializer_list_t init,
  12124. bool type_deduction = true,
  12125. value_t manual_type = value_t::array)
  12126. {
  12127. // check if each element is an array with two elements whose first
  12128. // element is a string
  12129. bool is_an_object = std::all_of(init.begin(), init.end(),
  12130. [](const detail::json_ref<basic_json>& element_ref)
  12131. {
  12132. return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
  12133. });
  12134. // adjust type if type deduction is not wanted
  12135. if (not type_deduction)
  12136. {
  12137. // if array is wanted, do not create an object though possible
  12138. if (manual_type == value_t::array)
  12139. {
  12140. is_an_object = false;
  12141. }
  12142. // if object is wanted but impossible, throw an exception
  12143. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  12144. {
  12145. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  12146. }
  12147. }
  12148. if (is_an_object)
  12149. {
  12150. // the initializer list is a list of pairs -> create object
  12151. m_type = value_t::object;
  12152. m_value = value_t::object;
  12153. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  12154. {
  12155. auto element = element_ref.moved_or_copied();
  12156. m_value.object->emplace(
  12157. std::move(*((*element.m_value.array)[0].m_value.string)),
  12158. std::move((*element.m_value.array)[1]));
  12159. });
  12160. }
  12161. else
  12162. {
  12163. // the initializer list describes an array -> create array
  12164. m_type = value_t::array;
  12165. m_value.array = create<array_t>(init.begin(), init.end());
  12166. }
  12167. assert_invariant();
  12168. }
  12169. /*!
  12170. @brief explicitly create an array from an initializer list
  12171. Creates a JSON array value from a given initializer list. That is, given a
  12172. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  12173. initializer list is empty, the empty array `[]` is created.
  12174. @note This function is only needed to express two edge cases that cannot
  12175. be realized with the initializer list constructor (@ref
  12176. basic_json(initializer_list_t, bool, value_t)). These cases
  12177. are:
  12178. 1. creating an array whose elements are all pairs whose first element is a
  12179. string -- in this case, the initializer list constructor would create an
  12180. object, taking the first elements as keys
  12181. 2. creating an empty array -- passing the empty initializer list to the
  12182. initializer list constructor yields an empty object
  12183. @param[in] init initializer list with JSON values to create an array from
  12184. (optional)
  12185. @return JSON array value
  12186. @complexity Linear in the size of @a init.
  12187. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12188. changes to any JSON value.
  12189. @liveexample{The following code shows an example for the `array`
  12190. function.,array}
  12191. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  12192. create a JSON value from an initializer list
  12193. @sa @ref object(initializer_list_t) -- create a JSON object
  12194. value from an initializer list
  12195. @since version 1.0.0
  12196. */
  12197. JSON_NODISCARD
  12198. static basic_json array(initializer_list_t init = {})
  12199. {
  12200. return basic_json(init, false, value_t::array);
  12201. }
  12202. /*!
  12203. @brief explicitly create an object from an initializer list
  12204. Creates a JSON object value from a given initializer list. The initializer
  12205. lists elements must be pairs, and their first elements must be strings. If
  12206. the initializer list is empty, the empty object `{}` is created.
  12207. @note This function is only added for symmetry reasons. In contrast to the
  12208. related function @ref array(initializer_list_t), there are
  12209. no cases which can only be expressed by this function. That is, any
  12210. initializer list @a init can also be passed to the initializer list
  12211. constructor @ref basic_json(initializer_list_t, bool, value_t).
  12212. @param[in] init initializer list to create an object from (optional)
  12213. @return JSON object value
  12214. @throw type_error.301 if @a init is not a list of pairs whose first
  12215. elements are strings. In this case, no object can be created. When such a
  12216. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  12217. an array would have been created from the passed initializer list @a init.
  12218. See example below.
  12219. @complexity Linear in the size of @a init.
  12220. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12221. changes to any JSON value.
  12222. @liveexample{The following code shows an example for the `object`
  12223. function.,object}
  12224. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  12225. create a JSON value from an initializer list
  12226. @sa @ref array(initializer_list_t) -- create a JSON array
  12227. value from an initializer list
  12228. @since version 1.0.0
  12229. */
  12230. JSON_NODISCARD
  12231. static basic_json object(initializer_list_t init = {})
  12232. {
  12233. return basic_json(init, false, value_t::object);
  12234. }
  12235. /*!
  12236. @brief construct an array with count copies of given value
  12237. Constructs a JSON array value by creating @a cnt copies of a passed value.
  12238. In case @a cnt is `0`, an empty array is created.
  12239. @param[in] cnt the number of JSON copies of @a val to create
  12240. @param[in] val the JSON value to copy
  12241. @post `std::distance(begin(),end()) == cnt` holds.
  12242. @complexity Linear in @a cnt.
  12243. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12244. changes to any JSON value.
  12245. @liveexample{The following code shows examples for the @ref
  12246. basic_json(size_type\, const basic_json&)
  12247. constructor.,basic_json__size_type_basic_json}
  12248. @since version 1.0.0
  12249. */
  12250. basic_json(size_type cnt, const basic_json& val)
  12251. : m_type(value_t::array)
  12252. {
  12253. m_value.array = create<array_t>(cnt, val);
  12254. assert_invariant();
  12255. }
  12256. /*!
  12257. @brief construct a JSON container given an iterator range
  12258. Constructs the JSON value with the contents of the range `[first, last)`.
  12259. The semantics depends on the different types a JSON value can have:
  12260. - In case of a null type, invalid_iterator.206 is thrown.
  12261. - In case of other primitive types (number, boolean, or string), @a first
  12262. must be `begin()` and @a last must be `end()`. In this case, the value is
  12263. copied. Otherwise, invalid_iterator.204 is thrown.
  12264. - In case of structured types (array, object), the constructor behaves as
  12265. similar versions for `std::vector` or `std::map`; that is, a JSON array
  12266. or object is constructed from the values in the range.
  12267. @tparam InputIT an input iterator type (@ref iterator or @ref
  12268. const_iterator)
  12269. @param[in] first begin of the range to copy from (included)
  12270. @param[in] last end of the range to copy from (excluded)
  12271. @pre Iterators @a first and @a last must be initialized. **This
  12272. precondition is enforced with an assertion (see warning).** If
  12273. assertions are switched off, a violation of this precondition yields
  12274. undefined behavior.
  12275. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  12276. checked efficiently. Only certain edge cases are detected; see the
  12277. description of the exceptions below. A violation of this precondition
  12278. yields undefined behavior.
  12279. @warning A precondition is enforced with a runtime assertion that will
  12280. result in calling `std::abort` if this precondition is not met.
  12281. Assertions can be disabled by defining `NDEBUG` at compile time.
  12282. See https://en.cppreference.com/w/cpp/error/assert for more
  12283. information.
  12284. @throw invalid_iterator.201 if iterators @a first and @a last are not
  12285. compatible (i.e., do not belong to the same JSON value). In this case,
  12286. the range `[first, last)` is undefined.
  12287. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  12288. primitive type (number, boolean, or string), but @a first does not point
  12289. to the first element any more. In this case, the range `[first, last)` is
  12290. undefined. See example code below.
  12291. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  12292. null value. In this case, the range `[first, last)` is undefined.
  12293. @complexity Linear in distance between @a first and @a last.
  12294. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12295. changes to any JSON value.
  12296. @liveexample{The example below shows several ways to create JSON values by
  12297. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  12298. @since version 1.0.0
  12299. */
  12300. template<class InputIT, typename std::enable_if<
  12301. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  12302. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  12303. basic_json(InputIT first, InputIT last)
  12304. {
  12305. assert(first.m_object != nullptr);
  12306. assert(last.m_object != nullptr);
  12307. // make sure iterator fits the current value
  12308. if (JSON_UNLIKELY(first.m_object != last.m_object))
  12309. {
  12310. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  12311. }
  12312. // copy type from first iterator
  12313. m_type = first.m_object->m_type;
  12314. // check if iterator range is complete for primitive values
  12315. switch (m_type)
  12316. {
  12317. case value_t::boolean:
  12318. case value_t::number_float:
  12319. case value_t::number_integer:
  12320. case value_t::number_unsigned:
  12321. case value_t::string:
  12322. {
  12323. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  12324. or not last.m_it.primitive_iterator.is_end()))
  12325. {
  12326. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  12327. }
  12328. break;
  12329. }
  12330. default:
  12331. break;
  12332. }
  12333. switch (m_type)
  12334. {
  12335. case value_t::number_integer:
  12336. {
  12337. m_value.number_integer = first.m_object->m_value.number_integer;
  12338. break;
  12339. }
  12340. case value_t::number_unsigned:
  12341. {
  12342. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  12343. break;
  12344. }
  12345. case value_t::number_float:
  12346. {
  12347. m_value.number_float = first.m_object->m_value.number_float;
  12348. break;
  12349. }
  12350. case value_t::boolean:
  12351. {
  12352. m_value.boolean = first.m_object->m_value.boolean;
  12353. break;
  12354. }
  12355. case value_t::string:
  12356. {
  12357. m_value = *first.m_object->m_value.string;
  12358. break;
  12359. }
  12360. case value_t::object:
  12361. {
  12362. m_value.object = create<object_t>(first.m_it.object_iterator,
  12363. last.m_it.object_iterator);
  12364. break;
  12365. }
  12366. case value_t::array:
  12367. {
  12368. m_value.array = create<array_t>(first.m_it.array_iterator,
  12369. last.m_it.array_iterator);
  12370. break;
  12371. }
  12372. default:
  12373. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  12374. std::string(first.m_object->type_name())));
  12375. }
  12376. assert_invariant();
  12377. }
  12378. ///////////////////////////////////////
  12379. // other constructors and destructor //
  12380. ///////////////////////////////////////
  12381. /// @private
  12382. basic_json(const detail::json_ref<basic_json>& ref)
  12383. : basic_json(ref.moved_or_copied())
  12384. {}
  12385. /*!
  12386. @brief copy constructor
  12387. Creates a copy of a given JSON value.
  12388. @param[in] other the JSON value to copy
  12389. @post `*this == other`
  12390. @complexity Linear in the size of @a other.
  12391. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12392. changes to any JSON value.
  12393. @requirement This function helps `basic_json` satisfying the
  12394. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12395. requirements:
  12396. - The complexity is linear.
  12397. - As postcondition, it holds: `other == basic_json(other)`.
  12398. @liveexample{The following code shows an example for the copy
  12399. constructor.,basic_json__basic_json}
  12400. @since version 1.0.0
  12401. */
  12402. basic_json(const basic_json& other)
  12403. : m_type(other.m_type)
  12404. {
  12405. // check of passed value is valid
  12406. other.assert_invariant();
  12407. switch (m_type)
  12408. {
  12409. case value_t::object:
  12410. {
  12411. m_value = *other.m_value.object;
  12412. break;
  12413. }
  12414. case value_t::array:
  12415. {
  12416. m_value = *other.m_value.array;
  12417. break;
  12418. }
  12419. case value_t::string:
  12420. {
  12421. m_value = *other.m_value.string;
  12422. break;
  12423. }
  12424. case value_t::boolean:
  12425. {
  12426. m_value = other.m_value.boolean;
  12427. break;
  12428. }
  12429. case value_t::number_integer:
  12430. {
  12431. m_value = other.m_value.number_integer;
  12432. break;
  12433. }
  12434. case value_t::number_unsigned:
  12435. {
  12436. m_value = other.m_value.number_unsigned;
  12437. break;
  12438. }
  12439. case value_t::number_float:
  12440. {
  12441. m_value = other.m_value.number_float;
  12442. break;
  12443. }
  12444. default:
  12445. break;
  12446. }
  12447. assert_invariant();
  12448. }
  12449. /*!
  12450. @brief move constructor
  12451. Move constructor. Constructs a JSON value with the contents of the given
  12452. value @a other using move semantics. It "steals" the resources from @a
  12453. other and leaves it as JSON null value.
  12454. @param[in,out] other value to move to this object
  12455. @post `*this` has the same value as @a other before the call.
  12456. @post @a other is a JSON null value.
  12457. @complexity Constant.
  12458. @exceptionsafety No-throw guarantee: this constructor never throws
  12459. exceptions.
  12460. @requirement This function helps `basic_json` satisfying the
  12461. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  12462. requirements.
  12463. @liveexample{The code below shows the move constructor explicitly called
  12464. via std::move.,basic_json__moveconstructor}
  12465. @since version 1.0.0
  12466. */
  12467. basic_json(basic_json&& other) noexcept
  12468. : m_type(std::move(other.m_type)),
  12469. m_value(std::move(other.m_value))
  12470. {
  12471. // check that passed value is valid
  12472. other.assert_invariant();
  12473. // invalidate payload
  12474. other.m_type = value_t::null;
  12475. other.m_value = {};
  12476. assert_invariant();
  12477. }
  12478. /*!
  12479. @brief copy assignment
  12480. Copy assignment operator. Copies a JSON value via the "copy and swap"
  12481. strategy: It is expressed in terms of the copy constructor, destructor,
  12482. and the `swap()` member function.
  12483. @param[in] other value to copy from
  12484. @complexity Linear.
  12485. @requirement This function helps `basic_json` satisfying the
  12486. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12487. requirements:
  12488. - The complexity is linear.
  12489. @liveexample{The code below shows and example for the copy assignment. It
  12490. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  12491. copy of `a` (which is the null value after the swap) is
  12492. destroyed.,basic_json__copyassignment}
  12493. @since version 1.0.0
  12494. */
  12495. basic_json& operator=(basic_json other) noexcept (
  12496. std::is_nothrow_move_constructible<value_t>::value and
  12497. std::is_nothrow_move_assignable<value_t>::value and
  12498. std::is_nothrow_move_constructible<json_value>::value and
  12499. std::is_nothrow_move_assignable<json_value>::value
  12500. )
  12501. {
  12502. // check that passed value is valid
  12503. other.assert_invariant();
  12504. using std::swap;
  12505. swap(m_type, other.m_type);
  12506. swap(m_value, other.m_value);
  12507. assert_invariant();
  12508. return *this;
  12509. }
  12510. /*!
  12511. @brief destructor
  12512. Destroys the JSON value and frees all allocated memory.
  12513. @complexity Linear.
  12514. @requirement This function helps `basic_json` satisfying the
  12515. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12516. requirements:
  12517. - The complexity is linear.
  12518. - All stored elements are destroyed and all memory is freed.
  12519. @since version 1.0.0
  12520. */
  12521. ~basic_json() noexcept
  12522. {
  12523. assert_invariant();
  12524. m_value.destroy(m_type);
  12525. }
  12526. /// @}
  12527. public:
  12528. ///////////////////////
  12529. // object inspection //
  12530. ///////////////////////
  12531. /// @name object inspection
  12532. /// Functions to inspect the type of a JSON value.
  12533. /// @{
  12534. /*!
  12535. @brief serialization
  12536. Serialization function for JSON values. The function tries to mimic
  12537. Python's `json.dumps()` function, and currently supports its @a indent
  12538. and @a ensure_ascii parameters.
  12539. @param[in] indent If indent is nonnegative, then array elements and object
  12540. members will be pretty-printed with that indent level. An indent level of
  12541. `0` will only insert newlines. `-1` (the default) selects the most compact
  12542. representation.
  12543. @param[in] indent_char The character to use for indentation if @a indent is
  12544. greater than `0`. The default is ` ` (space).
  12545. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  12546. in the output are escaped with `\uXXXX` sequences, and the result consists
  12547. of ASCII characters only.
  12548. @param[in] error_handler how to react on decoding errors; there are three
  12549. possible values: `strict` (throws and exception in case a decoding error
  12550. occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
  12551. and `ignore` (ignore invalid UTF-8 sequences during serialization).
  12552. @return string containing the serialization of the JSON value
  12553. @throw type_error.316 if a string stored inside the JSON value is not
  12554. UTF-8 encoded
  12555. @complexity Linear.
  12556. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12557. changes in the JSON value.
  12558. @liveexample{The following example shows the effect of different @a indent\,
  12559. @a indent_char\, and @a ensure_ascii parameters to the result of the
  12560. serialization.,dump}
  12561. @see https://docs.python.org/2/library/json.html#json.dump
  12562. @since version 1.0.0; indentation character @a indent_char, option
  12563. @a ensure_ascii and exceptions added in version 3.0.0; error
  12564. handlers added in version 3.4.0.
  12565. */
  12566. string_t dump(const int indent = -1,
  12567. const char indent_char = ' ',
  12568. const bool ensure_ascii = false,
  12569. const error_handler_t error_handler = error_handler_t::strict) const
  12570. {
  12571. string_t result;
  12572. serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
  12573. if (indent >= 0)
  12574. {
  12575. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  12576. }
  12577. else
  12578. {
  12579. s.dump(*this, false, ensure_ascii, 0);
  12580. }
  12581. return result;
  12582. }
  12583. /*!
  12584. @brief return the type of the JSON value (explicit)
  12585. Return the type of the JSON value as a value from the @ref value_t
  12586. enumeration.
  12587. @return the type of the JSON value
  12588. Value type | return value
  12589. ------------------------- | -------------------------
  12590. null | value_t::null
  12591. boolean | value_t::boolean
  12592. string | value_t::string
  12593. number (integer) | value_t::number_integer
  12594. number (unsigned integer) | value_t::number_unsigned
  12595. number (floating-point) | value_t::number_float
  12596. object | value_t::object
  12597. array | value_t::array
  12598. discarded | value_t::discarded
  12599. @complexity Constant.
  12600. @exceptionsafety No-throw guarantee: this member function never throws
  12601. exceptions.
  12602. @liveexample{The following code exemplifies `type()` for all JSON
  12603. types.,type}
  12604. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  12605. @sa @ref type_name() -- return the type as string
  12606. @since version 1.0.0
  12607. */
  12608. constexpr value_t type() const noexcept
  12609. {
  12610. return m_type;
  12611. }
  12612. /*!
  12613. @brief return whether type is primitive
  12614. This function returns true if and only if the JSON type is primitive
  12615. (string, number, boolean, or null).
  12616. @return `true` if type is primitive (string, number, boolean, or null),
  12617. `false` otherwise.
  12618. @complexity Constant.
  12619. @exceptionsafety No-throw guarantee: this member function never throws
  12620. exceptions.
  12621. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  12622. types.,is_primitive}
  12623. @sa @ref is_structured() -- returns whether JSON value is structured
  12624. @sa @ref is_null() -- returns whether JSON value is `null`
  12625. @sa @ref is_string() -- returns whether JSON value is a string
  12626. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  12627. @sa @ref is_number() -- returns whether JSON value is a number
  12628. @since version 1.0.0
  12629. */
  12630. constexpr bool is_primitive() const noexcept
  12631. {
  12632. return is_null() or is_string() or is_boolean() or is_number();
  12633. }
  12634. /*!
  12635. @brief return whether type is structured
  12636. This function returns true if and only if the JSON type is structured
  12637. (array or object).
  12638. @return `true` if type is structured (array or object), `false` otherwise.
  12639. @complexity Constant.
  12640. @exceptionsafety No-throw guarantee: this member function never throws
  12641. exceptions.
  12642. @liveexample{The following code exemplifies `is_structured()` for all JSON
  12643. types.,is_structured}
  12644. @sa @ref is_primitive() -- returns whether value is primitive
  12645. @sa @ref is_array() -- returns whether value is an array
  12646. @sa @ref is_object() -- returns whether value is an object
  12647. @since version 1.0.0
  12648. */
  12649. constexpr bool is_structured() const noexcept
  12650. {
  12651. return is_array() or is_object();
  12652. }
  12653. /*!
  12654. @brief return whether value is null
  12655. This function returns true if and only if the JSON value is null.
  12656. @return `true` if type is null, `false` otherwise.
  12657. @complexity Constant.
  12658. @exceptionsafety No-throw guarantee: this member function never throws
  12659. exceptions.
  12660. @liveexample{The following code exemplifies `is_null()` for all JSON
  12661. types.,is_null}
  12662. @since version 1.0.0
  12663. */
  12664. constexpr bool is_null() const noexcept
  12665. {
  12666. return m_type == value_t::null;
  12667. }
  12668. /*!
  12669. @brief return whether value is a boolean
  12670. This function returns true if and only if the JSON value is a boolean.
  12671. @return `true` if type is boolean, `false` otherwise.
  12672. @complexity Constant.
  12673. @exceptionsafety No-throw guarantee: this member function never throws
  12674. exceptions.
  12675. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  12676. types.,is_boolean}
  12677. @since version 1.0.0
  12678. */
  12679. constexpr bool is_boolean() const noexcept
  12680. {
  12681. return m_type == value_t::boolean;
  12682. }
  12683. /*!
  12684. @brief return whether value is a number
  12685. This function returns true if and only if the JSON value is a number. This
  12686. includes both integer (signed and unsigned) and floating-point values.
  12687. @return `true` if type is number (regardless whether integer, unsigned
  12688. integer or floating-type), `false` otherwise.
  12689. @complexity Constant.
  12690. @exceptionsafety No-throw guarantee: this member function never throws
  12691. exceptions.
  12692. @liveexample{The following code exemplifies `is_number()` for all JSON
  12693. types.,is_number}
  12694. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12695. integer number
  12696. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12697. number
  12698. @sa @ref is_number_float() -- check if value is a floating-point number
  12699. @since version 1.0.0
  12700. */
  12701. constexpr bool is_number() const noexcept
  12702. {
  12703. return is_number_integer() or is_number_float();
  12704. }
  12705. /*!
  12706. @brief return whether value is an integer number
  12707. This function returns true if and only if the JSON value is a signed or
  12708. unsigned integer number. This excludes floating-point values.
  12709. @return `true` if type is an integer or unsigned integer number, `false`
  12710. otherwise.
  12711. @complexity Constant.
  12712. @exceptionsafety No-throw guarantee: this member function never throws
  12713. exceptions.
  12714. @liveexample{The following code exemplifies `is_number_integer()` for all
  12715. JSON types.,is_number_integer}
  12716. @sa @ref is_number() -- check if value is a number
  12717. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12718. number
  12719. @sa @ref is_number_float() -- check if value is a floating-point number
  12720. @since version 1.0.0
  12721. */
  12722. constexpr bool is_number_integer() const noexcept
  12723. {
  12724. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  12725. }
  12726. /*!
  12727. @brief return whether value is an unsigned integer number
  12728. This function returns true if and only if the JSON value is an unsigned
  12729. integer number. This excludes floating-point and signed integer values.
  12730. @return `true` if type is an unsigned integer number, `false` otherwise.
  12731. @complexity Constant.
  12732. @exceptionsafety No-throw guarantee: this member function never throws
  12733. exceptions.
  12734. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  12735. JSON types.,is_number_unsigned}
  12736. @sa @ref is_number() -- check if value is a number
  12737. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  12738. integer number
  12739. @sa @ref is_number_float() -- check if value is a floating-point number
  12740. @since version 2.0.0
  12741. */
  12742. constexpr bool is_number_unsigned() const noexcept
  12743. {
  12744. return m_type == value_t::number_unsigned;
  12745. }
  12746. /*!
  12747. @brief return whether value is a floating-point number
  12748. This function returns true if and only if the JSON value is a
  12749. floating-point number. This excludes signed and unsigned integer values.
  12750. @return `true` if type is a floating-point number, `false` otherwise.
  12751. @complexity Constant.
  12752. @exceptionsafety No-throw guarantee: this member function never throws
  12753. exceptions.
  12754. @liveexample{The following code exemplifies `is_number_float()` for all
  12755. JSON types.,is_number_float}
  12756. @sa @ref is_number() -- check if value is number
  12757. @sa @ref is_number_integer() -- check if value is an integer number
  12758. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  12759. number
  12760. @since version 1.0.0
  12761. */
  12762. constexpr bool is_number_float() const noexcept
  12763. {
  12764. return m_type == value_t::number_float;
  12765. }
  12766. /*!
  12767. @brief return whether value is an object
  12768. This function returns true if and only if the JSON value is an object.
  12769. @return `true` if type is object, `false` otherwise.
  12770. @complexity Constant.
  12771. @exceptionsafety No-throw guarantee: this member function never throws
  12772. exceptions.
  12773. @liveexample{The following code exemplifies `is_object()` for all JSON
  12774. types.,is_object}
  12775. @since version 1.0.0
  12776. */
  12777. constexpr bool is_object() const noexcept
  12778. {
  12779. return m_type == value_t::object;
  12780. }
  12781. /*!
  12782. @brief return whether value is an array
  12783. This function returns true if and only if the JSON value is an array.
  12784. @return `true` if type is array, `false` otherwise.
  12785. @complexity Constant.
  12786. @exceptionsafety No-throw guarantee: this member function never throws
  12787. exceptions.
  12788. @liveexample{The following code exemplifies `is_array()` for all JSON
  12789. types.,is_array}
  12790. @since version 1.0.0
  12791. */
  12792. constexpr bool is_array() const noexcept
  12793. {
  12794. return m_type == value_t::array;
  12795. }
  12796. /*!
  12797. @brief return whether value is a string
  12798. This function returns true if and only if the JSON value is a string.
  12799. @return `true` if type is string, `false` otherwise.
  12800. @complexity Constant.
  12801. @exceptionsafety No-throw guarantee: this member function never throws
  12802. exceptions.
  12803. @liveexample{The following code exemplifies `is_string()` for all JSON
  12804. types.,is_string}
  12805. @since version 1.0.0
  12806. */
  12807. constexpr bool is_string() const noexcept
  12808. {
  12809. return m_type == value_t::string;
  12810. }
  12811. /*!
  12812. @brief return whether value is discarded
  12813. This function returns true if and only if the JSON value was discarded
  12814. during parsing with a callback function (see @ref parser_callback_t).
  12815. @note This function will always be `false` for JSON values after parsing.
  12816. That is, discarded values can only occur during parsing, but will be
  12817. removed when inside a structured value or replaced by null in other cases.
  12818. @return `true` if type is discarded, `false` otherwise.
  12819. @complexity Constant.
  12820. @exceptionsafety No-throw guarantee: this member function never throws
  12821. exceptions.
  12822. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  12823. types.,is_discarded}
  12824. @since version 1.0.0
  12825. */
  12826. constexpr bool is_discarded() const noexcept
  12827. {
  12828. return m_type == value_t::discarded;
  12829. }
  12830. /*!
  12831. @brief return the type of the JSON value (implicit)
  12832. Implicitly return the type of the JSON value as a value from the @ref
  12833. value_t enumeration.
  12834. @return the type of the JSON value
  12835. @complexity Constant.
  12836. @exceptionsafety No-throw guarantee: this member function never throws
  12837. exceptions.
  12838. @liveexample{The following code exemplifies the @ref value_t operator for
  12839. all JSON types.,operator__value_t}
  12840. @sa @ref type() -- return the type of the JSON value (explicit)
  12841. @sa @ref type_name() -- return the type as string
  12842. @since version 1.0.0
  12843. */
  12844. constexpr operator value_t() const noexcept
  12845. {
  12846. return m_type;
  12847. }
  12848. /// @}
  12849. private:
  12850. //////////////////
  12851. // value access //
  12852. //////////////////
  12853. /// get a boolean (explicit)
  12854. boolean_t get_impl(boolean_t* /*unused*/) const
  12855. {
  12856. if (JSON_LIKELY(is_boolean()))
  12857. {
  12858. return m_value.boolean;
  12859. }
  12860. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  12861. }
  12862. /// get a pointer to the value (object)
  12863. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  12864. {
  12865. return is_object() ? m_value.object : nullptr;
  12866. }
  12867. /// get a pointer to the value (object)
  12868. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  12869. {
  12870. return is_object() ? m_value.object : nullptr;
  12871. }
  12872. /// get a pointer to the value (array)
  12873. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  12874. {
  12875. return is_array() ? m_value.array : nullptr;
  12876. }
  12877. /// get a pointer to the value (array)
  12878. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  12879. {
  12880. return is_array() ? m_value.array : nullptr;
  12881. }
  12882. /// get a pointer to the value (string)
  12883. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  12884. {
  12885. return is_string() ? m_value.string : nullptr;
  12886. }
  12887. /// get a pointer to the value (string)
  12888. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  12889. {
  12890. return is_string() ? m_value.string : nullptr;
  12891. }
  12892. /// get a pointer to the value (boolean)
  12893. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  12894. {
  12895. return is_boolean() ? &m_value.boolean : nullptr;
  12896. }
  12897. /// get a pointer to the value (boolean)
  12898. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  12899. {
  12900. return is_boolean() ? &m_value.boolean : nullptr;
  12901. }
  12902. /// get a pointer to the value (integer number)
  12903. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  12904. {
  12905. return is_number_integer() ? &m_value.number_integer : nullptr;
  12906. }
  12907. /// get a pointer to the value (integer number)
  12908. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  12909. {
  12910. return is_number_integer() ? &m_value.number_integer : nullptr;
  12911. }
  12912. /// get a pointer to the value (unsigned number)
  12913. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  12914. {
  12915. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12916. }
  12917. /// get a pointer to the value (unsigned number)
  12918. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  12919. {
  12920. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  12921. }
  12922. /// get a pointer to the value (floating-point number)
  12923. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  12924. {
  12925. return is_number_float() ? &m_value.number_float : nullptr;
  12926. }
  12927. /// get a pointer to the value (floating-point number)
  12928. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  12929. {
  12930. return is_number_float() ? &m_value.number_float : nullptr;
  12931. }
  12932. /*!
  12933. @brief helper function to implement get_ref()
  12934. This function helps to implement get_ref() without code duplication for
  12935. const and non-const overloads
  12936. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  12937. @throw type_error.303 if ReferenceType does not match underlying value
  12938. type of the current JSON
  12939. */
  12940. template<typename ReferenceType, typename ThisType>
  12941. static ReferenceType get_ref_impl(ThisType& obj)
  12942. {
  12943. // delegate the call to get_ptr<>()
  12944. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  12945. if (JSON_LIKELY(ptr != nullptr))
  12946. {
  12947. return *ptr;
  12948. }
  12949. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  12950. }
  12951. public:
  12952. /// @name value access
  12953. /// Direct access to the stored value of a JSON value.
  12954. /// @{
  12955. /*!
  12956. @brief get special-case overload
  12957. This overloads avoids a lot of template boilerplate, it can be seen as the
  12958. identity method
  12959. @tparam BasicJsonType == @ref basic_json
  12960. @return a copy of *this
  12961. @complexity Constant.
  12962. @since version 2.1.0
  12963. */
  12964. template<typename BasicJsonType, detail::enable_if_t<
  12965. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  12966. int> = 0>
  12967. basic_json get() const
  12968. {
  12969. return *this;
  12970. }
  12971. /*!
  12972. @brief get special-case overload
  12973. This overloads converts the current @ref basic_json in a different
  12974. @ref basic_json type
  12975. @tparam BasicJsonType == @ref basic_json
  12976. @return a copy of *this, converted into @tparam BasicJsonType
  12977. @complexity Depending on the implementation of the called `from_json()`
  12978. method.
  12979. @since version 3.2.0
  12980. */
  12981. template<typename BasicJsonType, detail::enable_if_t<
  12982. not std::is_same<BasicJsonType, basic_json>::value and
  12983. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  12984. BasicJsonType get() const
  12985. {
  12986. return *this;
  12987. }
  12988. /*!
  12989. @brief get a value (explicit)
  12990. Explicit type conversion between the JSON value and a compatible value
  12991. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  12992. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  12993. The value is converted by calling the @ref json_serializer<ValueType>
  12994. `from_json()` method.
  12995. The function is equivalent to executing
  12996. @code {.cpp}
  12997. ValueType ret;
  12998. JSONSerializer<ValueType>::from_json(*this, ret);
  12999. return ret;
  13000. @endcode
  13001. This overloads is chosen if:
  13002. - @a ValueType is not @ref basic_json,
  13003. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13004. `void from_json(const basic_json&, ValueType&)`, and
  13005. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  13006. the form `ValueType from_json(const basic_json&)`
  13007. @tparam ValueTypeCV the provided value type
  13008. @tparam ValueType the returned value type
  13009. @return copy of the JSON value, converted to @a ValueType
  13010. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13011. @liveexample{The example below shows several conversions from JSON values
  13012. to other types. There a few things to note: (1) Floating-point numbers can
  13013. be converted to integers\, (2) A JSON array can be converted to a standard
  13014. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13015. associative containers such as `std::unordered_map<std::string\,
  13016. json>`.,get__ValueType_const}
  13017. @since version 2.1.0
  13018. */
  13019. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  13020. detail::enable_if_t <
  13021. not detail::is_basic_json<ValueType>::value and
  13022. detail::has_from_json<basic_json_t, ValueType>::value and
  13023. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  13024. int> = 0>
  13025. ValueType get() const noexcept(noexcept(
  13026. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  13027. {
  13028. // we cannot static_assert on ValueTypeCV being non-const, because
  13029. // there is support for get<const basic_json_t>(), which is why we
  13030. // still need the uncvref
  13031. static_assert(not std::is_reference<ValueTypeCV>::value,
  13032. "get() cannot be used with reference types, you might want to use get_ref()");
  13033. static_assert(std::is_default_constructible<ValueType>::value,
  13034. "types must be DefaultConstructible when used with get()");
  13035. ValueType ret;
  13036. JSONSerializer<ValueType>::from_json(*this, ret);
  13037. return ret;
  13038. }
  13039. /*!
  13040. @brief get a value (explicit); special case
  13041. Explicit type conversion between the JSON value and a compatible value
  13042. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  13043. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  13044. The value is converted by calling the @ref json_serializer<ValueType>
  13045. `from_json()` method.
  13046. The function is equivalent to executing
  13047. @code {.cpp}
  13048. return JSONSerializer<ValueTypeCV>::from_json(*this);
  13049. @endcode
  13050. This overloads is chosen if:
  13051. - @a ValueType is not @ref basic_json and
  13052. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13053. `ValueType from_json(const basic_json&)`
  13054. @note If @ref json_serializer<ValueType> has both overloads of
  13055. `from_json()`, this one is chosen.
  13056. @tparam ValueTypeCV the provided value type
  13057. @tparam ValueType the returned value type
  13058. @return copy of the JSON value, converted to @a ValueType
  13059. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13060. @since version 2.1.0
  13061. */
  13062. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  13063. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  13064. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  13065. int> = 0>
  13066. ValueType get() const noexcept(noexcept(
  13067. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  13068. {
  13069. static_assert(not std::is_reference<ValueTypeCV>::value,
  13070. "get() cannot be used with reference types, you might want to use get_ref()");
  13071. return JSONSerializer<ValueTypeCV>::from_json(*this);
  13072. }
  13073. /*!
  13074. @brief get a value (explicit)
  13075. Explicit type conversion between the JSON value and a compatible value.
  13076. The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
  13077. `from_json()` method.
  13078. The function is equivalent to executing
  13079. @code {.cpp}
  13080. ValueType v;
  13081. JSONSerializer<ValueType>::from_json(*this, v);
  13082. @endcode
  13083. This overloads is chosen if:
  13084. - @a ValueType is not @ref basic_json,
  13085. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  13086. `void from_json(const basic_json&, ValueType&)`, and
  13087. @tparam ValueType the input parameter type.
  13088. @return the input parameter, allowing chaining calls.
  13089. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  13090. @liveexample{The example below shows several conversions from JSON values
  13091. to other types. There a few things to note: (1) Floating-point numbers can
  13092. be converted to integers\, (2) A JSON array can be converted to a standard
  13093. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13094. associative containers such as `std::unordered_map<std::string\,
  13095. json>`.,get_to}
  13096. @since version 3.3.0
  13097. */
  13098. template<typename ValueType,
  13099. detail::enable_if_t <
  13100. not detail::is_basic_json<ValueType>::value and
  13101. detail::has_from_json<basic_json_t, ValueType>::value,
  13102. int> = 0>
  13103. ValueType & get_to(ValueType& v) const noexcept(noexcept(
  13104. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
  13105. {
  13106. JSONSerializer<ValueType>::from_json(*this, v);
  13107. return v;
  13108. }
  13109. /*!
  13110. @brief get a pointer value (implicit)
  13111. Implicit pointer access to the internally stored JSON value. No copies are
  13112. made.
  13113. @warning Writing data to the pointee of the result yields an undefined
  13114. state.
  13115. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  13116. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  13117. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  13118. assertion.
  13119. @return pointer to the internally stored JSON value if the requested
  13120. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  13121. @complexity Constant.
  13122. @liveexample{The example below shows how pointers to internal values of a
  13123. JSON value can be requested. Note that no type conversions are made and a
  13124. `nullptr` is returned if the value and the requested pointer type does not
  13125. match.,get_ptr}
  13126. @since version 1.0.0
  13127. */
  13128. template<typename PointerType, typename std::enable_if<
  13129. std::is_pointer<PointerType>::value, int>::type = 0>
  13130. auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  13131. {
  13132. // delegate the call to get_impl_ptr<>()
  13133. return get_impl_ptr(static_cast<PointerType>(nullptr));
  13134. }
  13135. /*!
  13136. @brief get a pointer value (implicit)
  13137. @copydoc get_ptr()
  13138. */
  13139. template<typename PointerType, typename std::enable_if<
  13140. std::is_pointer<PointerType>::value and
  13141. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  13142. constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
  13143. {
  13144. // delegate the call to get_impl_ptr<>() const
  13145. return get_impl_ptr(static_cast<PointerType>(nullptr));
  13146. }
  13147. /*!
  13148. @brief get a pointer value (explicit)
  13149. Explicit pointer access to the internally stored JSON value. No copies are
  13150. made.
  13151. @warning The pointer becomes invalid if the underlying JSON object
  13152. changes.
  13153. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  13154. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  13155. @ref number_unsigned_t, or @ref number_float_t.
  13156. @return pointer to the internally stored JSON value if the requested
  13157. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  13158. @complexity Constant.
  13159. @liveexample{The example below shows how pointers to internal values of a
  13160. JSON value can be requested. Note that no type conversions are made and a
  13161. `nullptr` is returned if the value and the requested pointer type does not
  13162. match.,get__PointerType}
  13163. @sa @ref get_ptr() for explicit pointer-member access
  13164. @since version 1.0.0
  13165. */
  13166. template<typename PointerType, typename std::enable_if<
  13167. std::is_pointer<PointerType>::value, int>::type = 0>
  13168. auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
  13169. {
  13170. // delegate the call to get_ptr
  13171. return get_ptr<PointerType>();
  13172. }
  13173. /*!
  13174. @brief get a pointer value (explicit)
  13175. @copydoc get()
  13176. */
  13177. template<typename PointerType, typename std::enable_if<
  13178. std::is_pointer<PointerType>::value, int>::type = 0>
  13179. constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
  13180. {
  13181. // delegate the call to get_ptr
  13182. return get_ptr<PointerType>();
  13183. }
  13184. /*!
  13185. @brief get a reference value (implicit)
  13186. Implicit reference access to the internally stored JSON value. No copies
  13187. are made.
  13188. @warning Writing data to the referee of the result yields an undefined
  13189. state.
  13190. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  13191. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  13192. @ref number_float_t. Enforced by static assertion.
  13193. @return reference to the internally stored JSON value if the requested
  13194. reference type @a ReferenceType fits to the JSON value; throws
  13195. type_error.303 otherwise
  13196. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  13197. with the stored JSON value; see example below
  13198. @complexity Constant.
  13199. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  13200. @since version 1.1.0
  13201. */
  13202. template<typename ReferenceType, typename std::enable_if<
  13203. std::is_reference<ReferenceType>::value, int>::type = 0>
  13204. ReferenceType get_ref()
  13205. {
  13206. // delegate call to get_ref_impl
  13207. return get_ref_impl<ReferenceType>(*this);
  13208. }
  13209. /*!
  13210. @brief get a reference value (implicit)
  13211. @copydoc get_ref()
  13212. */
  13213. template<typename ReferenceType, typename std::enable_if<
  13214. std::is_reference<ReferenceType>::value and
  13215. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  13216. ReferenceType get_ref() const
  13217. {
  13218. // delegate call to get_ref_impl
  13219. return get_ref_impl<ReferenceType>(*this);
  13220. }
  13221. /*!
  13222. @brief get a value (implicit)
  13223. Implicit type conversion between the JSON value and a compatible value.
  13224. The call is realized by calling @ref get() const.
  13225. @tparam ValueType non-pointer type compatible to the JSON value, for
  13226. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  13227. `std::vector` types for JSON arrays. The character type of @ref string_t
  13228. as well as an initializer list of this type is excluded to avoid
  13229. ambiguities as these types implicitly convert to `std::string`.
  13230. @return copy of the JSON value, converted to type @a ValueType
  13231. @throw type_error.302 in case passed type @a ValueType is incompatible
  13232. to the JSON value type (e.g., the JSON value is of type boolean, but a
  13233. string is requested); see example below
  13234. @complexity Linear in the size of the JSON value.
  13235. @liveexample{The example below shows several conversions from JSON values
  13236. to other types. There a few things to note: (1) Floating-point numbers can
  13237. be converted to integers\, (2) A JSON array can be converted to a standard
  13238. `std::vector<short>`\, (3) A JSON object can be converted to C++
  13239. associative containers such as `std::unordered_map<std::string\,
  13240. json>`.,operator__ValueType}
  13241. @since version 1.0.0
  13242. */
  13243. template < typename ValueType, typename std::enable_if <
  13244. not std::is_pointer<ValueType>::value and
  13245. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  13246. not std::is_same<ValueType, typename string_t::value_type>::value and
  13247. not detail::is_basic_json<ValueType>::value
  13248. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  13249. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  13250. #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
  13251. and not std::is_same<ValueType, typename std::string_view>::value
  13252. #endif
  13253. #endif
  13254. and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
  13255. , int >::type = 0 >
  13256. operator ValueType() const
  13257. {
  13258. // delegate the call to get<>() const
  13259. return get<ValueType>();
  13260. }
  13261. /// @}
  13262. ////////////////////
  13263. // element access //
  13264. ////////////////////
  13265. /// @name element access
  13266. /// Access to the JSON value.
  13267. /// @{
  13268. /*!
  13269. @brief access specified array element with bounds checking
  13270. Returns a reference to the element at specified location @a idx, with
  13271. bounds checking.
  13272. @param[in] idx index of the element to access
  13273. @return reference to the element at index @a idx
  13274. @throw type_error.304 if the JSON value is not an array; in this case,
  13275. calling `at` with an index makes no sense. See example below.
  13276. @throw out_of_range.401 if the index @a idx is out of range of the array;
  13277. that is, `idx >= size()`. See example below.
  13278. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13279. changes in the JSON value.
  13280. @complexity Constant.
  13281. @since version 1.0.0
  13282. @liveexample{The example below shows how array elements can be read and
  13283. written using `at()`. It also demonstrates the different exceptions that
  13284. can be thrown.,at__size_type}
  13285. */
  13286. reference at(size_type idx)
  13287. {
  13288. // at only works for arrays
  13289. if (JSON_LIKELY(is_array()))
  13290. {
  13291. JSON_TRY
  13292. {
  13293. return m_value.array->at(idx);
  13294. }
  13295. JSON_CATCH (std::out_of_range&)
  13296. {
  13297. // create better exception explanation
  13298. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13299. }
  13300. }
  13301. else
  13302. {
  13303. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13304. }
  13305. }
  13306. /*!
  13307. @brief access specified array element with bounds checking
  13308. Returns a const reference to the element at specified location @a idx,
  13309. with bounds checking.
  13310. @param[in] idx index of the element to access
  13311. @return const reference to the element at index @a idx
  13312. @throw type_error.304 if the JSON value is not an array; in this case,
  13313. calling `at` with an index makes no sense. See example below.
  13314. @throw out_of_range.401 if the index @a idx is out of range of the array;
  13315. that is, `idx >= size()`. See example below.
  13316. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13317. changes in the JSON value.
  13318. @complexity Constant.
  13319. @since version 1.0.0
  13320. @liveexample{The example below shows how array elements can be read using
  13321. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13322. at__size_type_const}
  13323. */
  13324. const_reference at(size_type idx) const
  13325. {
  13326. // at only works for arrays
  13327. if (JSON_LIKELY(is_array()))
  13328. {
  13329. JSON_TRY
  13330. {
  13331. return m_value.array->at(idx);
  13332. }
  13333. JSON_CATCH (std::out_of_range&)
  13334. {
  13335. // create better exception explanation
  13336. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  13337. }
  13338. }
  13339. else
  13340. {
  13341. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13342. }
  13343. }
  13344. /*!
  13345. @brief access specified object element with bounds checking
  13346. Returns a reference to the element at with specified key @a key, with
  13347. bounds checking.
  13348. @param[in] key key of the element to access
  13349. @return reference to the element at key @a key
  13350. @throw type_error.304 if the JSON value is not an object; in this case,
  13351. calling `at` with a key makes no sense. See example below.
  13352. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13353. that is, `find(key) == end()`. See example below.
  13354. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13355. changes in the JSON value.
  13356. @complexity Logarithmic in the size of the container.
  13357. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13358. access by reference
  13359. @sa @ref value() for access by value with a default value
  13360. @since version 1.0.0
  13361. @liveexample{The example below shows how object elements can be read and
  13362. written using `at()`. It also demonstrates the different exceptions that
  13363. can be thrown.,at__object_t_key_type}
  13364. */
  13365. reference at(const typename object_t::key_type& key)
  13366. {
  13367. // at only works for objects
  13368. if (JSON_LIKELY(is_object()))
  13369. {
  13370. JSON_TRY
  13371. {
  13372. return m_value.object->at(key);
  13373. }
  13374. JSON_CATCH (std::out_of_range&)
  13375. {
  13376. // create better exception explanation
  13377. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13378. }
  13379. }
  13380. else
  13381. {
  13382. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13383. }
  13384. }
  13385. /*!
  13386. @brief access specified object element with bounds checking
  13387. Returns a const reference to the element at with specified key @a key,
  13388. with bounds checking.
  13389. @param[in] key key of the element to access
  13390. @return const reference to the element at key @a key
  13391. @throw type_error.304 if the JSON value is not an object; in this case,
  13392. calling `at` with a key makes no sense. See example below.
  13393. @throw out_of_range.403 if the key @a key is is not stored in the object;
  13394. that is, `find(key) == end()`. See example below.
  13395. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13396. changes in the JSON value.
  13397. @complexity Logarithmic in the size of the container.
  13398. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13399. access by reference
  13400. @sa @ref value() for access by value with a default value
  13401. @since version 1.0.0
  13402. @liveexample{The example below shows how object elements can be read using
  13403. `at()`. It also demonstrates the different exceptions that can be thrown.,
  13404. at__object_t_key_type_const}
  13405. */
  13406. const_reference at(const typename object_t::key_type& key) const
  13407. {
  13408. // at only works for objects
  13409. if (JSON_LIKELY(is_object()))
  13410. {
  13411. JSON_TRY
  13412. {
  13413. return m_value.object->at(key);
  13414. }
  13415. JSON_CATCH (std::out_of_range&)
  13416. {
  13417. // create better exception explanation
  13418. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  13419. }
  13420. }
  13421. else
  13422. {
  13423. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  13424. }
  13425. }
  13426. /*!
  13427. @brief access specified array element
  13428. Returns a reference to the element at specified location @a idx.
  13429. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  13430. then the array is silently filled up with `null` values to make `idx` a
  13431. valid reference to the last stored element.
  13432. @param[in] idx index of the element to access
  13433. @return reference to the element at index @a idx
  13434. @throw type_error.305 if the JSON value is not an array or null; in that
  13435. cases, using the [] operator with an index makes no sense.
  13436. @complexity Constant if @a idx is in the range of the array. Otherwise
  13437. linear in `idx - size()`.
  13438. @liveexample{The example below shows how array elements can be read and
  13439. written using `[]` operator. Note the addition of `null`
  13440. values.,operatorarray__size_type}
  13441. @since version 1.0.0
  13442. */
  13443. reference operator[](size_type idx)
  13444. {
  13445. // implicitly convert null value to an empty array
  13446. if (is_null())
  13447. {
  13448. m_type = value_t::array;
  13449. m_value.array = create<array_t>();
  13450. assert_invariant();
  13451. }
  13452. // operator[] only works for arrays
  13453. if (JSON_LIKELY(is_array()))
  13454. {
  13455. // fill up array with null values if given idx is outside range
  13456. if (idx >= m_value.array->size())
  13457. {
  13458. m_value.array->insert(m_value.array->end(),
  13459. idx - m_value.array->size() + 1,
  13460. basic_json());
  13461. }
  13462. return m_value.array->operator[](idx);
  13463. }
  13464. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13465. }
  13466. /*!
  13467. @brief access specified array element
  13468. Returns a const reference to the element at specified location @a idx.
  13469. @param[in] idx index of the element to access
  13470. @return const reference to the element at index @a idx
  13471. @throw type_error.305 if the JSON value is not an array; in that case,
  13472. using the [] operator with an index makes no sense.
  13473. @complexity Constant.
  13474. @liveexample{The example below shows how array elements can be read using
  13475. the `[]` operator.,operatorarray__size_type_const}
  13476. @since version 1.0.0
  13477. */
  13478. const_reference operator[](size_type idx) const
  13479. {
  13480. // const operator[] only works for arrays
  13481. if (JSON_LIKELY(is_array()))
  13482. {
  13483. return m_value.array->operator[](idx);
  13484. }
  13485. JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
  13486. }
  13487. /*!
  13488. @brief access specified object element
  13489. Returns a reference to the element at with specified key @a key.
  13490. @note If @a key is not found in the object, then it is silently added to
  13491. the object and filled with a `null` value to make `key` a valid reference.
  13492. In case the value was `null` before, it is converted to an object.
  13493. @param[in] key key of the element to access
  13494. @return reference to the element at key @a key
  13495. @throw type_error.305 if the JSON value is not an object or null; in that
  13496. cases, using the [] operator with a key makes no sense.
  13497. @complexity Logarithmic in the size of the container.
  13498. @liveexample{The example below shows how object elements can be read and
  13499. written using the `[]` operator.,operatorarray__key_type}
  13500. @sa @ref at(const typename object_t::key_type&) for access by reference
  13501. with range checking
  13502. @sa @ref value() for access by value with a default value
  13503. @since version 1.0.0
  13504. */
  13505. reference operator[](const typename object_t::key_type& key)
  13506. {
  13507. // implicitly convert null value to an empty object
  13508. if (is_null())
  13509. {
  13510. m_type = value_t::object;
  13511. m_value.object = create<object_t>();
  13512. assert_invariant();
  13513. }
  13514. // operator[] only works for objects
  13515. if (JSON_LIKELY(is_object()))
  13516. {
  13517. return m_value.object->operator[](key);
  13518. }
  13519. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13520. }
  13521. /*!
  13522. @brief read-only access specified object element
  13523. Returns a const reference to the element at with specified key @a key. No
  13524. bounds checking is performed.
  13525. @warning If the element with key @a key does not exist, the behavior is
  13526. undefined.
  13527. @param[in] key key of the element to access
  13528. @return const reference to the element at key @a key
  13529. @pre The element with key @a key must exist. **This precondition is
  13530. enforced with an assertion.**
  13531. @throw type_error.305 if the JSON value is not an object; in that case,
  13532. using the [] operator with a key makes no sense.
  13533. @complexity Logarithmic in the size of the container.
  13534. @liveexample{The example below shows how object elements can be read using
  13535. the `[]` operator.,operatorarray__key_type_const}
  13536. @sa @ref at(const typename object_t::key_type&) for access by reference
  13537. with range checking
  13538. @sa @ref value() for access by value with a default value
  13539. @since version 1.0.0
  13540. */
  13541. const_reference operator[](const typename object_t::key_type& key) const
  13542. {
  13543. // const operator[] only works for objects
  13544. if (JSON_LIKELY(is_object()))
  13545. {
  13546. assert(m_value.object->find(key) != m_value.object->end());
  13547. return m_value.object->find(key)->second;
  13548. }
  13549. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13550. }
  13551. /*!
  13552. @brief access specified object element
  13553. Returns a reference to the element at with specified key @a key.
  13554. @note If @a key is not found in the object, then it is silently added to
  13555. the object and filled with a `null` value to make `key` a valid reference.
  13556. In case the value was `null` before, it is converted to an object.
  13557. @param[in] key key of the element to access
  13558. @return reference to the element at key @a key
  13559. @throw type_error.305 if the JSON value is not an object or null; in that
  13560. cases, using the [] operator with a key makes no sense.
  13561. @complexity Logarithmic in the size of the container.
  13562. @liveexample{The example below shows how object elements can be read and
  13563. written using the `[]` operator.,operatorarray__key_type}
  13564. @sa @ref at(const typename object_t::key_type&) for access by reference
  13565. with range checking
  13566. @sa @ref value() for access by value with a default value
  13567. @since version 1.1.0
  13568. */
  13569. template<typename T>
  13570. reference operator[](T* key)
  13571. {
  13572. // implicitly convert null to object
  13573. if (is_null())
  13574. {
  13575. m_type = value_t::object;
  13576. m_value = value_t::object;
  13577. assert_invariant();
  13578. }
  13579. // at only works for objects
  13580. if (JSON_LIKELY(is_object()))
  13581. {
  13582. return m_value.object->operator[](key);
  13583. }
  13584. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13585. }
  13586. /*!
  13587. @brief read-only access specified object element
  13588. Returns a const reference to the element at with specified key @a key. No
  13589. bounds checking is performed.
  13590. @warning If the element with key @a key does not exist, the behavior is
  13591. undefined.
  13592. @param[in] key key of the element to access
  13593. @return const reference to the element at key @a key
  13594. @pre The element with key @a key must exist. **This precondition is
  13595. enforced with an assertion.**
  13596. @throw type_error.305 if the JSON value is not an object; in that case,
  13597. using the [] operator with a key makes no sense.
  13598. @complexity Logarithmic in the size of the container.
  13599. @liveexample{The example below shows how object elements can be read using
  13600. the `[]` operator.,operatorarray__key_type_const}
  13601. @sa @ref at(const typename object_t::key_type&) for access by reference
  13602. with range checking
  13603. @sa @ref value() for access by value with a default value
  13604. @since version 1.1.0
  13605. */
  13606. template<typename T>
  13607. const_reference operator[](T* key) const
  13608. {
  13609. // at only works for objects
  13610. if (JSON_LIKELY(is_object()))
  13611. {
  13612. assert(m_value.object->find(key) != m_value.object->end());
  13613. return m_value.object->find(key)->second;
  13614. }
  13615. JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
  13616. }
  13617. /*!
  13618. @brief access specified object element with default value
  13619. Returns either a copy of an object's element at the specified key @a key
  13620. or a given default value if no element with key @a key exists.
  13621. The function is basically equivalent to executing
  13622. @code {.cpp}
  13623. try {
  13624. return at(key);
  13625. } catch(out_of_range) {
  13626. return default_value;
  13627. }
  13628. @endcode
  13629. @note Unlike @ref at(const typename object_t::key_type&), this function
  13630. does not throw if the given key @a key was not found.
  13631. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  13632. function does not implicitly add an element to the position defined by @a
  13633. key. This function is furthermore also applicable to const objects.
  13634. @param[in] key key of the element to access
  13635. @param[in] default_value the value to return if @a key is not found
  13636. @tparam ValueType type compatible to JSON values, for instance `int` for
  13637. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13638. JSON arrays. Note the type of the expected value at @a key and the default
  13639. value @a default_value must be compatible.
  13640. @return copy of the element at key @a key or @a default_value if @a key
  13641. is not found
  13642. @throw type_error.306 if the JSON value is not an object; in that case,
  13643. using `value()` with a key makes no sense.
  13644. @complexity Logarithmic in the size of the container.
  13645. @liveexample{The example below shows how object elements can be queried
  13646. with a default value.,basic_json__value}
  13647. @sa @ref at(const typename object_t::key_type&) for access by reference
  13648. with range checking
  13649. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  13650. access by reference
  13651. @since version 1.0.0
  13652. */
  13653. template<class ValueType, typename std::enable_if<
  13654. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13655. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  13656. {
  13657. // at only works for objects
  13658. if (JSON_LIKELY(is_object()))
  13659. {
  13660. // if key is found, return value and given default value otherwise
  13661. const auto it = find(key);
  13662. if (it != end())
  13663. {
  13664. return *it;
  13665. }
  13666. return default_value;
  13667. }
  13668. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13669. }
  13670. /*!
  13671. @brief overload for a default value of type const char*
  13672. @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
  13673. */
  13674. string_t value(const typename object_t::key_type& key, const char* default_value) const
  13675. {
  13676. return value(key, string_t(default_value));
  13677. }
  13678. /*!
  13679. @brief access specified object element via JSON Pointer with default value
  13680. Returns either a copy of an object's element at the specified key @a key
  13681. or a given default value if no element with key @a key exists.
  13682. The function is basically equivalent to executing
  13683. @code {.cpp}
  13684. try {
  13685. return at(ptr);
  13686. } catch(out_of_range) {
  13687. return default_value;
  13688. }
  13689. @endcode
  13690. @note Unlike @ref at(const json_pointer&), this function does not throw
  13691. if the given key @a key was not found.
  13692. @param[in] ptr a JSON pointer to the element to access
  13693. @param[in] default_value the value to return if @a ptr found no value
  13694. @tparam ValueType type compatible to JSON values, for instance `int` for
  13695. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  13696. JSON arrays. Note the type of the expected value at @a key and the default
  13697. value @a default_value must be compatible.
  13698. @return copy of the element at key @a key or @a default_value if @a key
  13699. is not found
  13700. @throw type_error.306 if the JSON value is not an object; in that case,
  13701. using `value()` with a key makes no sense.
  13702. @complexity Logarithmic in the size of the container.
  13703. @liveexample{The example below shows how object elements can be queried
  13704. with a default value.,basic_json__value_ptr}
  13705. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  13706. @since version 2.0.2
  13707. */
  13708. template<class ValueType, typename std::enable_if<
  13709. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  13710. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  13711. {
  13712. // at only works for objects
  13713. if (JSON_LIKELY(is_object()))
  13714. {
  13715. // if pointer resolves a value, return it or use default value
  13716. JSON_TRY
  13717. {
  13718. return ptr.get_checked(this);
  13719. }
  13720. JSON_INTERNAL_CATCH (out_of_range&)
  13721. {
  13722. return default_value;
  13723. }
  13724. }
  13725. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  13726. }
  13727. /*!
  13728. @brief overload for a default value of type const char*
  13729. @copydoc basic_json::value(const json_pointer&, ValueType) const
  13730. */
  13731. string_t value(const json_pointer& ptr, const char* default_value) const
  13732. {
  13733. return value(ptr, string_t(default_value));
  13734. }
  13735. /*!
  13736. @brief access the first element
  13737. Returns a reference to the first element in the container. For a JSON
  13738. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  13739. @return In case of a structured type (array or object), a reference to the
  13740. first element is returned. In case of number, string, or boolean values, a
  13741. reference to the value is returned.
  13742. @complexity Constant.
  13743. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13744. or an empty array or object (undefined behavior, **guarded by
  13745. assertions**).
  13746. @post The JSON value remains unchanged.
  13747. @throw invalid_iterator.214 when called on `null` value
  13748. @liveexample{The following code shows an example for `front()`.,front}
  13749. @sa @ref back() -- access the last element
  13750. @since version 1.0.0
  13751. */
  13752. reference front()
  13753. {
  13754. return *begin();
  13755. }
  13756. /*!
  13757. @copydoc basic_json::front()
  13758. */
  13759. const_reference front() const
  13760. {
  13761. return *cbegin();
  13762. }
  13763. /*!
  13764. @brief access the last element
  13765. Returns a reference to the last element in the container. For a JSON
  13766. container `c`, the expression `c.back()` is equivalent to
  13767. @code {.cpp}
  13768. auto tmp = c.end();
  13769. --tmp;
  13770. return *tmp;
  13771. @endcode
  13772. @return In case of a structured type (array or object), a reference to the
  13773. last element is returned. In case of number, string, or boolean values, a
  13774. reference to the value is returned.
  13775. @complexity Constant.
  13776. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  13777. or an empty array or object (undefined behavior, **guarded by
  13778. assertions**).
  13779. @post The JSON value remains unchanged.
  13780. @throw invalid_iterator.214 when called on a `null` value. See example
  13781. below.
  13782. @liveexample{The following code shows an example for `back()`.,back}
  13783. @sa @ref front() -- access the first element
  13784. @since version 1.0.0
  13785. */
  13786. reference back()
  13787. {
  13788. auto tmp = end();
  13789. --tmp;
  13790. return *tmp;
  13791. }
  13792. /*!
  13793. @copydoc basic_json::back()
  13794. */
  13795. const_reference back() const
  13796. {
  13797. auto tmp = cend();
  13798. --tmp;
  13799. return *tmp;
  13800. }
  13801. /*!
  13802. @brief remove element given an iterator
  13803. Removes the element specified by iterator @a pos. The iterator @a pos must
  13804. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  13805. but is not dereferenceable) cannot be used as a value for @a pos.
  13806. If called on a primitive type other than `null`, the resulting JSON value
  13807. will be `null`.
  13808. @param[in] pos iterator to the element to remove
  13809. @return Iterator following the last removed element. If the iterator @a
  13810. pos refers to the last element, the `end()` iterator is returned.
  13811. @tparam IteratorType an @ref iterator or @ref const_iterator
  13812. @post Invalidates iterators and references at or after the point of the
  13813. erase, including the `end()` iterator.
  13814. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13815. erase() with null"`
  13816. @throw invalid_iterator.202 if called on an iterator which does not belong
  13817. to the current JSON value; example: `"iterator does not fit current
  13818. value"`
  13819. @throw invalid_iterator.205 if called on a primitive type with invalid
  13820. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  13821. out of range"`
  13822. @complexity The complexity depends on the type:
  13823. - objects: amortized constant
  13824. - arrays: linear in distance between @a pos and the end of the container
  13825. - strings: linear in the length of the string
  13826. - other types: constant
  13827. @liveexample{The example shows the result of `erase()` for different JSON
  13828. types.,erase__IteratorType}
  13829. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13830. the given range
  13831. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13832. from an object at the given key
  13833. @sa @ref erase(const size_type) -- removes the element from an array at
  13834. the given index
  13835. @since version 1.0.0
  13836. */
  13837. template<class IteratorType, typename std::enable_if<
  13838. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13839. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13840. = 0>
  13841. IteratorType erase(IteratorType pos)
  13842. {
  13843. // make sure iterator fits the current value
  13844. if (JSON_UNLIKELY(this != pos.m_object))
  13845. {
  13846. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13847. }
  13848. IteratorType result = end();
  13849. switch (m_type)
  13850. {
  13851. case value_t::boolean:
  13852. case value_t::number_float:
  13853. case value_t::number_integer:
  13854. case value_t::number_unsigned:
  13855. case value_t::string:
  13856. {
  13857. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  13858. {
  13859. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  13860. }
  13861. if (is_string())
  13862. {
  13863. AllocatorType<string_t> alloc;
  13864. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  13865. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  13866. m_value.string = nullptr;
  13867. }
  13868. m_type = value_t::null;
  13869. assert_invariant();
  13870. break;
  13871. }
  13872. case value_t::object:
  13873. {
  13874. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  13875. break;
  13876. }
  13877. case value_t::array:
  13878. {
  13879. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  13880. break;
  13881. }
  13882. default:
  13883. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13884. }
  13885. return result;
  13886. }
  13887. /*!
  13888. @brief remove elements given an iterator range
  13889. Removes the element specified by the range `[first; last)`. The iterator
  13890. @a first does not need to be dereferenceable if `first == last`: erasing
  13891. an empty range is a no-op.
  13892. If called on a primitive type other than `null`, the resulting JSON value
  13893. will be `null`.
  13894. @param[in] first iterator to the beginning of the range to remove
  13895. @param[in] last iterator past the end of the range to remove
  13896. @return Iterator following the last removed element. If the iterator @a
  13897. second refers to the last element, the `end()` iterator is returned.
  13898. @tparam IteratorType an @ref iterator or @ref const_iterator
  13899. @post Invalidates iterators and references at or after the point of the
  13900. erase, including the `end()` iterator.
  13901. @throw type_error.307 if called on a `null` value; example: `"cannot use
  13902. erase() with null"`
  13903. @throw invalid_iterator.203 if called on iterators which does not belong
  13904. to the current JSON value; example: `"iterators do not fit current value"`
  13905. @throw invalid_iterator.204 if called on a primitive type with invalid
  13906. iterators (i.e., if `first != begin()` and `last != end()`); example:
  13907. `"iterators out of range"`
  13908. @complexity The complexity depends on the type:
  13909. - objects: `log(size()) + std::distance(first, last)`
  13910. - arrays: linear in the distance between @a first and @a last, plus linear
  13911. in the distance between @a last and end of the container
  13912. - strings: linear in the length of the string
  13913. - other types: constant
  13914. @liveexample{The example shows the result of `erase()` for different JSON
  13915. types.,erase__IteratorType_IteratorType}
  13916. @sa @ref erase(IteratorType) -- removes the element at a given position
  13917. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  13918. from an object at the given key
  13919. @sa @ref erase(const size_type) -- removes the element from an array at
  13920. the given index
  13921. @since version 1.0.0
  13922. */
  13923. template<class IteratorType, typename std::enable_if<
  13924. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  13925. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  13926. = 0>
  13927. IteratorType erase(IteratorType first, IteratorType last)
  13928. {
  13929. // make sure iterator fits the current value
  13930. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  13931. {
  13932. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  13933. }
  13934. IteratorType result = end();
  13935. switch (m_type)
  13936. {
  13937. case value_t::boolean:
  13938. case value_t::number_float:
  13939. case value_t::number_integer:
  13940. case value_t::number_unsigned:
  13941. case value_t::string:
  13942. {
  13943. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  13944. or not last.m_it.primitive_iterator.is_end()))
  13945. {
  13946. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  13947. }
  13948. if (is_string())
  13949. {
  13950. AllocatorType<string_t> alloc;
  13951. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  13952. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  13953. m_value.string = nullptr;
  13954. }
  13955. m_type = value_t::null;
  13956. assert_invariant();
  13957. break;
  13958. }
  13959. case value_t::object:
  13960. {
  13961. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  13962. last.m_it.object_iterator);
  13963. break;
  13964. }
  13965. case value_t::array:
  13966. {
  13967. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  13968. last.m_it.array_iterator);
  13969. break;
  13970. }
  13971. default:
  13972. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  13973. }
  13974. return result;
  13975. }
  13976. /*!
  13977. @brief remove element from a JSON object given a key
  13978. Removes elements from a JSON object with the key value @a key.
  13979. @param[in] key value of the elements to remove
  13980. @return Number of elements removed. If @a ObjectType is the default
  13981. `std::map` type, the return value will always be `0` (@a key was not
  13982. found) or `1` (@a key was found).
  13983. @post References and iterators to the erased elements are invalidated.
  13984. Other references and iterators are not affected.
  13985. @throw type_error.307 when called on a type other than JSON object;
  13986. example: `"cannot use erase() with null"`
  13987. @complexity `log(size()) + count(key)`
  13988. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  13989. @sa @ref erase(IteratorType) -- removes the element at a given position
  13990. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  13991. the given range
  13992. @sa @ref erase(const size_type) -- removes the element from an array at
  13993. the given index
  13994. @since version 1.0.0
  13995. */
  13996. size_type erase(const typename object_t::key_type& key)
  13997. {
  13998. // this erase only works for objects
  13999. if (JSON_LIKELY(is_object()))
  14000. {
  14001. return m_value.object->erase(key);
  14002. }
  14003. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  14004. }
  14005. /*!
  14006. @brief remove element from a JSON array given an index
  14007. Removes element from a JSON array at the index @a idx.
  14008. @param[in] idx index of the element to remove
  14009. @throw type_error.307 when called on a type other than JSON object;
  14010. example: `"cannot use erase() with null"`
  14011. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  14012. is out of range"`
  14013. @complexity Linear in distance between @a idx and the end of the container.
  14014. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  14015. @sa @ref erase(IteratorType) -- removes the element at a given position
  14016. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  14017. the given range
  14018. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  14019. from an object at the given key
  14020. @since version 1.0.0
  14021. */
  14022. void erase(const size_type idx)
  14023. {
  14024. // this erase only works for arrays
  14025. if (JSON_LIKELY(is_array()))
  14026. {
  14027. if (JSON_UNLIKELY(idx >= size()))
  14028. {
  14029. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  14030. }
  14031. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  14032. }
  14033. else
  14034. {
  14035. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  14036. }
  14037. }
  14038. /// @}
  14039. ////////////
  14040. // lookup //
  14041. ////////////
  14042. /// @name lookup
  14043. /// @{
  14044. /*!
  14045. @brief find an element in a JSON object
  14046. Finds an element in a JSON object with key equivalent to @a key. If the
  14047. element is not found or the JSON value is not an object, end() is
  14048. returned.
  14049. @note This method always returns @ref end() when executed on a JSON type
  14050. that is not an object.
  14051. @param[in] key key value of the element to search for.
  14052. @return Iterator to an element with key equivalent to @a key. If no such
  14053. element is found or the JSON value is not an object, past-the-end (see
  14054. @ref end()) iterator is returned.
  14055. @complexity Logarithmic in the size of the JSON object.
  14056. @liveexample{The example shows how `find()` is used.,find__key_type}
  14057. @sa @ref contains(KeyT&&) const -- checks whether a key exists
  14058. @since version 1.0.0
  14059. */
  14060. template<typename KeyT>
  14061. iterator find(KeyT&& key)
  14062. {
  14063. auto result = end();
  14064. if (is_object())
  14065. {
  14066. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  14067. }
  14068. return result;
  14069. }
  14070. /*!
  14071. @brief find an element in a JSON object
  14072. @copydoc find(KeyT&&)
  14073. */
  14074. template<typename KeyT>
  14075. const_iterator find(KeyT&& key) const
  14076. {
  14077. auto result = cend();
  14078. if (is_object())
  14079. {
  14080. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  14081. }
  14082. return result;
  14083. }
  14084. /*!
  14085. @brief returns the number of occurrences of a key in a JSON object
  14086. Returns the number of elements with key @a key. If ObjectType is the
  14087. default `std::map` type, the return value will always be `0` (@a key was
  14088. not found) or `1` (@a key was found).
  14089. @note This method always returns `0` when executed on a JSON type that is
  14090. not an object.
  14091. @param[in] key key value of the element to count
  14092. @return Number of elements with key @a key. If the JSON value is not an
  14093. object, the return value will be `0`.
  14094. @complexity Logarithmic in the size of the JSON object.
  14095. @liveexample{The example shows how `count()` is used.,count}
  14096. @since version 1.0.0
  14097. */
  14098. template<typename KeyT>
  14099. size_type count(KeyT&& key) const
  14100. {
  14101. // return 0 for all nonobject types
  14102. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  14103. }
  14104. /*!
  14105. @brief check the existence of an element in a JSON object
  14106. Check whether an element exists in a JSON object with key equivalent to
  14107. @a key. If the element is not found or the JSON value is not an object,
  14108. false is returned.
  14109. @note This method always returns false when executed on a JSON type
  14110. that is not an object.
  14111. @param[in] key key value to check its existence.
  14112. @return true if an element with specified @a key exists. If no such
  14113. element with such key is found or the JSON value is not an object,
  14114. false is returned.
  14115. @complexity Logarithmic in the size of the JSON object.
  14116. @liveexample{The following code shows an example for `contains()`.,contains}
  14117. @sa @ref find(KeyT&&) -- returns an iterator to an object element
  14118. @since version 3.6.0
  14119. */
  14120. template<typename KeyT>
  14121. bool contains(KeyT&& key) const
  14122. {
  14123. return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
  14124. }
  14125. /// @}
  14126. ///////////////
  14127. // iterators //
  14128. ///////////////
  14129. /// @name iterators
  14130. /// @{
  14131. /*!
  14132. @brief returns an iterator to the first element
  14133. Returns an iterator to the first element.
  14134. @image html range-begin-end.svg "Illustration from cppreference.com"
  14135. @return iterator to the first element
  14136. @complexity Constant.
  14137. @requirement This function helps `basic_json` satisfying the
  14138. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14139. requirements:
  14140. - The complexity is constant.
  14141. @liveexample{The following code shows an example for `begin()`.,begin}
  14142. @sa @ref cbegin() -- returns a const iterator to the beginning
  14143. @sa @ref end() -- returns an iterator to the end
  14144. @sa @ref cend() -- returns a const iterator to the end
  14145. @since version 1.0.0
  14146. */
  14147. iterator begin() noexcept
  14148. {
  14149. iterator result(this);
  14150. result.set_begin();
  14151. return result;
  14152. }
  14153. /*!
  14154. @copydoc basic_json::cbegin()
  14155. */
  14156. const_iterator begin() const noexcept
  14157. {
  14158. return cbegin();
  14159. }
  14160. /*!
  14161. @brief returns a const iterator to the first element
  14162. Returns a const iterator to the first element.
  14163. @image html range-begin-end.svg "Illustration from cppreference.com"
  14164. @return const iterator to the first element
  14165. @complexity Constant.
  14166. @requirement This function helps `basic_json` satisfying the
  14167. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14168. requirements:
  14169. - The complexity is constant.
  14170. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  14171. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  14172. @sa @ref begin() -- returns an iterator to the beginning
  14173. @sa @ref end() -- returns an iterator to the end
  14174. @sa @ref cend() -- returns a const iterator to the end
  14175. @since version 1.0.0
  14176. */
  14177. const_iterator cbegin() const noexcept
  14178. {
  14179. const_iterator result(this);
  14180. result.set_begin();
  14181. return result;
  14182. }
  14183. /*!
  14184. @brief returns an iterator to one past the last element
  14185. Returns an iterator to one past the last element.
  14186. @image html range-begin-end.svg "Illustration from cppreference.com"
  14187. @return iterator one past the last element
  14188. @complexity Constant.
  14189. @requirement This function helps `basic_json` satisfying the
  14190. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14191. requirements:
  14192. - The complexity is constant.
  14193. @liveexample{The following code shows an example for `end()`.,end}
  14194. @sa @ref cend() -- returns a const iterator to the end
  14195. @sa @ref begin() -- returns an iterator to the beginning
  14196. @sa @ref cbegin() -- returns a const iterator to the beginning
  14197. @since version 1.0.0
  14198. */
  14199. iterator end() noexcept
  14200. {
  14201. iterator result(this);
  14202. result.set_end();
  14203. return result;
  14204. }
  14205. /*!
  14206. @copydoc basic_json::cend()
  14207. */
  14208. const_iterator end() const noexcept
  14209. {
  14210. return cend();
  14211. }
  14212. /*!
  14213. @brief returns a const iterator to one past the last element
  14214. Returns a const iterator to one past the last element.
  14215. @image html range-begin-end.svg "Illustration from cppreference.com"
  14216. @return const iterator one past the last element
  14217. @complexity Constant.
  14218. @requirement This function helps `basic_json` satisfying the
  14219. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14220. requirements:
  14221. - The complexity is constant.
  14222. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  14223. @liveexample{The following code shows an example for `cend()`.,cend}
  14224. @sa @ref end() -- returns an iterator to the end
  14225. @sa @ref begin() -- returns an iterator to the beginning
  14226. @sa @ref cbegin() -- returns a const iterator to the beginning
  14227. @since version 1.0.0
  14228. */
  14229. const_iterator cend() const noexcept
  14230. {
  14231. const_iterator result(this);
  14232. result.set_end();
  14233. return result;
  14234. }
  14235. /*!
  14236. @brief returns an iterator to the reverse-beginning
  14237. Returns an iterator to the reverse-beginning; that is, the last element.
  14238. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14239. @complexity Constant.
  14240. @requirement This function helps `basic_json` satisfying the
  14241. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14242. requirements:
  14243. - The complexity is constant.
  14244. - Has the semantics of `reverse_iterator(end())`.
  14245. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  14246. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14247. @sa @ref rend() -- returns a reverse iterator to the end
  14248. @sa @ref crend() -- returns a const reverse iterator to the end
  14249. @since version 1.0.0
  14250. */
  14251. reverse_iterator rbegin() noexcept
  14252. {
  14253. return reverse_iterator(end());
  14254. }
  14255. /*!
  14256. @copydoc basic_json::crbegin()
  14257. */
  14258. const_reverse_iterator rbegin() const noexcept
  14259. {
  14260. return crbegin();
  14261. }
  14262. /*!
  14263. @brief returns an iterator to the reverse-end
  14264. Returns an iterator to the reverse-end; that is, one before the first
  14265. element.
  14266. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14267. @complexity Constant.
  14268. @requirement This function helps `basic_json` satisfying the
  14269. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14270. requirements:
  14271. - The complexity is constant.
  14272. - Has the semantics of `reverse_iterator(begin())`.
  14273. @liveexample{The following code shows an example for `rend()`.,rend}
  14274. @sa @ref crend() -- returns a const reverse iterator to the end
  14275. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14276. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14277. @since version 1.0.0
  14278. */
  14279. reverse_iterator rend() noexcept
  14280. {
  14281. return reverse_iterator(begin());
  14282. }
  14283. /*!
  14284. @copydoc basic_json::crend()
  14285. */
  14286. const_reverse_iterator rend() const noexcept
  14287. {
  14288. return crend();
  14289. }
  14290. /*!
  14291. @brief returns a const reverse iterator to the last element
  14292. Returns a const iterator to the reverse-beginning; that is, the last
  14293. element.
  14294. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14295. @complexity Constant.
  14296. @requirement This function helps `basic_json` satisfying the
  14297. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14298. requirements:
  14299. - The complexity is constant.
  14300. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  14301. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  14302. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14303. @sa @ref rend() -- returns a reverse iterator to the end
  14304. @sa @ref crend() -- returns a const reverse iterator to the end
  14305. @since version 1.0.0
  14306. */
  14307. const_reverse_iterator crbegin() const noexcept
  14308. {
  14309. return const_reverse_iterator(cend());
  14310. }
  14311. /*!
  14312. @brief returns a const reverse iterator to one before the first
  14313. Returns a const reverse iterator to the reverse-end; that is, one before
  14314. the first element.
  14315. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  14316. @complexity Constant.
  14317. @requirement This function helps `basic_json` satisfying the
  14318. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  14319. requirements:
  14320. - The complexity is constant.
  14321. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  14322. @liveexample{The following code shows an example for `crend()`.,crend}
  14323. @sa @ref rend() -- returns a reverse iterator to the end
  14324. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  14325. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  14326. @since version 1.0.0
  14327. */
  14328. const_reverse_iterator crend() const noexcept
  14329. {
  14330. return const_reverse_iterator(cbegin());
  14331. }
  14332. public:
  14333. /*!
  14334. @brief wrapper to access iterator member functions in range-based for
  14335. This function allows to access @ref iterator::key() and @ref
  14336. iterator::value() during range-based for loops. In these loops, a
  14337. reference to the JSON values is returned, so there is no access to the
  14338. underlying iterator.
  14339. For loop without iterator_wrapper:
  14340. @code{cpp}
  14341. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14342. {
  14343. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14344. }
  14345. @endcode
  14346. Range-based for loop without iterator proxy:
  14347. @code{cpp}
  14348. for (auto it : j_object)
  14349. {
  14350. // "it" is of type json::reference and has no key() member
  14351. std::cout << "value: " << it << '\n';
  14352. }
  14353. @endcode
  14354. Range-based for loop with iterator proxy:
  14355. @code{cpp}
  14356. for (auto it : json::iterator_wrapper(j_object))
  14357. {
  14358. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14359. }
  14360. @endcode
  14361. @note When iterating over an array, `key()` will return the index of the
  14362. element as string (see example).
  14363. @param[in] ref reference to a JSON value
  14364. @return iteration proxy object wrapping @a ref with an interface to use in
  14365. range-based for loops
  14366. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  14367. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14368. changes in the JSON value.
  14369. @complexity Constant.
  14370. @note The name of this function is not yet final and may change in the
  14371. future.
  14372. @deprecated This stream operator is deprecated and will be removed in
  14373. future 4.0.0 of the library. Please use @ref items() instead;
  14374. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  14375. */
  14376. JSON_DEPRECATED
  14377. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  14378. {
  14379. return ref.items();
  14380. }
  14381. /*!
  14382. @copydoc iterator_wrapper(reference)
  14383. */
  14384. JSON_DEPRECATED
  14385. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  14386. {
  14387. return ref.items();
  14388. }
  14389. /*!
  14390. @brief helper to access iterator member functions in range-based for
  14391. This function allows to access @ref iterator::key() and @ref
  14392. iterator::value() during range-based for loops. In these loops, a
  14393. reference to the JSON values is returned, so there is no access to the
  14394. underlying iterator.
  14395. For loop without `items()` function:
  14396. @code{cpp}
  14397. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  14398. {
  14399. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  14400. }
  14401. @endcode
  14402. Range-based for loop without `items()` function:
  14403. @code{cpp}
  14404. for (auto it : j_object)
  14405. {
  14406. // "it" is of type json::reference and has no key() member
  14407. std::cout << "value: " << it << '\n';
  14408. }
  14409. @endcode
  14410. Range-based for loop with `items()` function:
  14411. @code{cpp}
  14412. for (auto& el : j_object.items())
  14413. {
  14414. std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
  14415. }
  14416. @endcode
  14417. The `items()` function also allows to use
  14418. [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
  14419. (C++17):
  14420. @code{cpp}
  14421. for (auto& [key, val] : j_object.items())
  14422. {
  14423. std::cout << "key: " << key << ", value:" << val << '\n';
  14424. }
  14425. @endcode
  14426. @note When iterating over an array, `key()` will return the index of the
  14427. element as string (see example). For primitive types (e.g., numbers),
  14428. `key()` returns an empty string.
  14429. @return iteration proxy object wrapping @a ref with an interface to use in
  14430. range-based for loops
  14431. @liveexample{The following code shows how the function is used.,items}
  14432. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  14433. changes in the JSON value.
  14434. @complexity Constant.
  14435. @since version 3.1.0, structured bindings support since 3.5.0.
  14436. */
  14437. iteration_proxy<iterator> items() noexcept
  14438. {
  14439. return iteration_proxy<iterator>(*this);
  14440. }
  14441. /*!
  14442. @copydoc items()
  14443. */
  14444. iteration_proxy<const_iterator> items() const noexcept
  14445. {
  14446. return iteration_proxy<const_iterator>(*this);
  14447. }
  14448. /// @}
  14449. //////////////
  14450. // capacity //
  14451. //////////////
  14452. /// @name capacity
  14453. /// @{
  14454. /*!
  14455. @brief checks whether the container is empty.
  14456. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  14457. @return The return value depends on the different types and is
  14458. defined as follows:
  14459. Value type | return value
  14460. ----------- | -------------
  14461. null | `true`
  14462. boolean | `false`
  14463. string | `false`
  14464. number | `false`
  14465. object | result of function `object_t::empty()`
  14466. array | result of function `array_t::empty()`
  14467. @liveexample{The following code uses `empty()` to check if a JSON
  14468. object contains any elements.,empty}
  14469. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14470. the Container concept; that is, their `empty()` functions have constant
  14471. complexity.
  14472. @iterators No changes.
  14473. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14474. @note This function does not return whether a string stored as JSON value
  14475. is empty - it returns whether the JSON container itself is empty which is
  14476. false in the case of a string.
  14477. @requirement This function helps `basic_json` satisfying the
  14478. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14479. requirements:
  14480. - The complexity is constant.
  14481. - Has the semantics of `begin() == end()`.
  14482. @sa @ref size() -- returns the number of elements
  14483. @since version 1.0.0
  14484. */
  14485. bool empty() const noexcept
  14486. {
  14487. switch (m_type)
  14488. {
  14489. case value_t::null:
  14490. {
  14491. // null values are empty
  14492. return true;
  14493. }
  14494. case value_t::array:
  14495. {
  14496. // delegate call to array_t::empty()
  14497. return m_value.array->empty();
  14498. }
  14499. case value_t::object:
  14500. {
  14501. // delegate call to object_t::empty()
  14502. return m_value.object->empty();
  14503. }
  14504. default:
  14505. {
  14506. // all other types are nonempty
  14507. return false;
  14508. }
  14509. }
  14510. }
  14511. /*!
  14512. @brief returns the number of elements
  14513. Returns the number of elements in a JSON value.
  14514. @return The return value depends on the different types and is
  14515. defined as follows:
  14516. Value type | return value
  14517. ----------- | -------------
  14518. null | `0`
  14519. boolean | `1`
  14520. string | `1`
  14521. number | `1`
  14522. object | result of function object_t::size()
  14523. array | result of function array_t::size()
  14524. @liveexample{The following code calls `size()` on the different value
  14525. types.,size}
  14526. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14527. the Container concept; that is, their size() functions have constant
  14528. complexity.
  14529. @iterators No changes.
  14530. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14531. @note This function does not return the length of a string stored as JSON
  14532. value - it returns the number of elements in the JSON value which is 1 in
  14533. the case of a string.
  14534. @requirement This function helps `basic_json` satisfying the
  14535. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14536. requirements:
  14537. - The complexity is constant.
  14538. - Has the semantics of `std::distance(begin(), end())`.
  14539. @sa @ref empty() -- checks whether the container is empty
  14540. @sa @ref max_size() -- returns the maximal number of elements
  14541. @since version 1.0.0
  14542. */
  14543. size_type size() const noexcept
  14544. {
  14545. switch (m_type)
  14546. {
  14547. case value_t::null:
  14548. {
  14549. // null values are empty
  14550. return 0;
  14551. }
  14552. case value_t::array:
  14553. {
  14554. // delegate call to array_t::size()
  14555. return m_value.array->size();
  14556. }
  14557. case value_t::object:
  14558. {
  14559. // delegate call to object_t::size()
  14560. return m_value.object->size();
  14561. }
  14562. default:
  14563. {
  14564. // all other types have size 1
  14565. return 1;
  14566. }
  14567. }
  14568. }
  14569. /*!
  14570. @brief returns the maximum possible number of elements
  14571. Returns the maximum number of elements a JSON value is able to hold due to
  14572. system or library implementation limitations, i.e. `std::distance(begin(),
  14573. end())` for the JSON value.
  14574. @return The return value depends on the different types and is
  14575. defined as follows:
  14576. Value type | return value
  14577. ----------- | -------------
  14578. null | `0` (same as `size()`)
  14579. boolean | `1` (same as `size()`)
  14580. string | `1` (same as `size()`)
  14581. number | `1` (same as `size()`)
  14582. object | result of function `object_t::max_size()`
  14583. array | result of function `array_t::max_size()`
  14584. @liveexample{The following code calls `max_size()` on the different value
  14585. types. Note the output is implementation specific.,max_size}
  14586. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  14587. the Container concept; that is, their `max_size()` functions have constant
  14588. complexity.
  14589. @iterators No changes.
  14590. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14591. @requirement This function helps `basic_json` satisfying the
  14592. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  14593. requirements:
  14594. - The complexity is constant.
  14595. - Has the semantics of returning `b.size()` where `b` is the largest
  14596. possible JSON value.
  14597. @sa @ref size() -- returns the number of elements
  14598. @since version 1.0.0
  14599. */
  14600. size_type max_size() const noexcept
  14601. {
  14602. switch (m_type)
  14603. {
  14604. case value_t::array:
  14605. {
  14606. // delegate call to array_t::max_size()
  14607. return m_value.array->max_size();
  14608. }
  14609. case value_t::object:
  14610. {
  14611. // delegate call to object_t::max_size()
  14612. return m_value.object->max_size();
  14613. }
  14614. default:
  14615. {
  14616. // all other types have max_size() == size()
  14617. return size();
  14618. }
  14619. }
  14620. }
  14621. /// @}
  14622. ///////////////
  14623. // modifiers //
  14624. ///////////////
  14625. /// @name modifiers
  14626. /// @{
  14627. /*!
  14628. @brief clears the contents
  14629. Clears the content of a JSON value and resets it to the default value as
  14630. if @ref basic_json(value_t) would have been called with the current value
  14631. type from @ref type():
  14632. Value type | initial value
  14633. ----------- | -------------
  14634. null | `null`
  14635. boolean | `false`
  14636. string | `""`
  14637. number | `0`
  14638. object | `{}`
  14639. array | `[]`
  14640. @post Has the same effect as calling
  14641. @code {.cpp}
  14642. *this = basic_json(type());
  14643. @endcode
  14644. @liveexample{The example below shows the effect of `clear()` to different
  14645. JSON types.,clear}
  14646. @complexity Linear in the size of the JSON value.
  14647. @iterators All iterators, pointers and references related to this container
  14648. are invalidated.
  14649. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14650. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  14651. same value than calling `clear()`
  14652. @since version 1.0.0
  14653. */
  14654. void clear() noexcept
  14655. {
  14656. switch (m_type)
  14657. {
  14658. case value_t::number_integer:
  14659. {
  14660. m_value.number_integer = 0;
  14661. break;
  14662. }
  14663. case value_t::number_unsigned:
  14664. {
  14665. m_value.number_unsigned = 0;
  14666. break;
  14667. }
  14668. case value_t::number_float:
  14669. {
  14670. m_value.number_float = 0.0;
  14671. break;
  14672. }
  14673. case value_t::boolean:
  14674. {
  14675. m_value.boolean = false;
  14676. break;
  14677. }
  14678. case value_t::string:
  14679. {
  14680. m_value.string->clear();
  14681. break;
  14682. }
  14683. case value_t::array:
  14684. {
  14685. m_value.array->clear();
  14686. break;
  14687. }
  14688. case value_t::object:
  14689. {
  14690. m_value.object->clear();
  14691. break;
  14692. }
  14693. default:
  14694. break;
  14695. }
  14696. }
  14697. /*!
  14698. @brief add an object to an array
  14699. Appends the given element @a val to the end of the JSON value. If the
  14700. function is called on a JSON null value, an empty array is created before
  14701. appending @a val.
  14702. @param[in] val the value to add to the JSON array
  14703. @throw type_error.308 when called on a type other than JSON array or
  14704. null; example: `"cannot use push_back() with number"`
  14705. @complexity Amortized constant.
  14706. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14707. add elements to a JSON array. Note how the `null` value was silently
  14708. converted to a JSON array.,push_back}
  14709. @since version 1.0.0
  14710. */
  14711. void push_back(basic_json&& val)
  14712. {
  14713. // push_back only works for null objects or arrays
  14714. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14715. {
  14716. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14717. }
  14718. // transform null object into an array
  14719. if (is_null())
  14720. {
  14721. m_type = value_t::array;
  14722. m_value = value_t::array;
  14723. assert_invariant();
  14724. }
  14725. // add element to array (move semantics)
  14726. m_value.array->push_back(std::move(val));
  14727. // invalidate object: mark it null so we do not call the destructor
  14728. // cppcheck-suppress accessMoved
  14729. val.m_type = value_t::null;
  14730. }
  14731. /*!
  14732. @brief add an object to an array
  14733. @copydoc push_back(basic_json&&)
  14734. */
  14735. reference operator+=(basic_json&& val)
  14736. {
  14737. push_back(std::move(val));
  14738. return *this;
  14739. }
  14740. /*!
  14741. @brief add an object to an array
  14742. @copydoc push_back(basic_json&&)
  14743. */
  14744. void push_back(const basic_json& val)
  14745. {
  14746. // push_back only works for null objects or arrays
  14747. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14748. {
  14749. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14750. }
  14751. // transform null object into an array
  14752. if (is_null())
  14753. {
  14754. m_type = value_t::array;
  14755. m_value = value_t::array;
  14756. assert_invariant();
  14757. }
  14758. // add element to array
  14759. m_value.array->push_back(val);
  14760. }
  14761. /*!
  14762. @brief add an object to an array
  14763. @copydoc push_back(basic_json&&)
  14764. */
  14765. reference operator+=(const basic_json& val)
  14766. {
  14767. push_back(val);
  14768. return *this;
  14769. }
  14770. /*!
  14771. @brief add an object to an object
  14772. Inserts the given element @a val to the JSON object. If the function is
  14773. called on a JSON null value, an empty object is created before inserting
  14774. @a val.
  14775. @param[in] val the value to add to the JSON object
  14776. @throw type_error.308 when called on a type other than JSON object or
  14777. null; example: `"cannot use push_back() with number"`
  14778. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14779. @liveexample{The example shows how `push_back()` and `+=` can be used to
  14780. add elements to a JSON object. Note how the `null` value was silently
  14781. converted to a JSON object.,push_back__object_t__value}
  14782. @since version 1.0.0
  14783. */
  14784. void push_back(const typename object_t::value_type& val)
  14785. {
  14786. // push_back only works for null objects or objects
  14787. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14788. {
  14789. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  14790. }
  14791. // transform null object into an object
  14792. if (is_null())
  14793. {
  14794. m_type = value_t::object;
  14795. m_value = value_t::object;
  14796. assert_invariant();
  14797. }
  14798. // add element to array
  14799. m_value.object->insert(val);
  14800. }
  14801. /*!
  14802. @brief add an object to an object
  14803. @copydoc push_back(const typename object_t::value_type&)
  14804. */
  14805. reference operator+=(const typename object_t::value_type& val)
  14806. {
  14807. push_back(val);
  14808. return *this;
  14809. }
  14810. /*!
  14811. @brief add an object to an object
  14812. This function allows to use `push_back` with an initializer list. In case
  14813. 1. the current value is an object,
  14814. 2. the initializer list @a init contains only two elements, and
  14815. 3. the first element of @a init is a string,
  14816. @a init is converted into an object element and added using
  14817. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  14818. is converted to a JSON value and added using @ref push_back(basic_json&&).
  14819. @param[in] init an initializer list
  14820. @complexity Linear in the size of the initializer list @a init.
  14821. @note This function is required to resolve an ambiguous overload error,
  14822. because pairs like `{"key", "value"}` can be both interpreted as
  14823. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  14824. https://github.com/nlohmann/json/issues/235 for more information.
  14825. @liveexample{The example shows how initializer lists are treated as
  14826. objects when possible.,push_back__initializer_list}
  14827. */
  14828. void push_back(initializer_list_t init)
  14829. {
  14830. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  14831. {
  14832. basic_json&& key = init.begin()->moved_or_copied();
  14833. push_back(typename object_t::value_type(
  14834. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  14835. }
  14836. else
  14837. {
  14838. push_back(basic_json(init));
  14839. }
  14840. }
  14841. /*!
  14842. @brief add an object to an object
  14843. @copydoc push_back(initializer_list_t)
  14844. */
  14845. reference operator+=(initializer_list_t init)
  14846. {
  14847. push_back(init);
  14848. return *this;
  14849. }
  14850. /*!
  14851. @brief add an object to an array
  14852. Creates a JSON value from the passed parameters @a args to the end of the
  14853. JSON value. If the function is called on a JSON null value, an empty array
  14854. is created before appending the value created from @a args.
  14855. @param[in] args arguments to forward to a constructor of @ref basic_json
  14856. @tparam Args compatible types to create a @ref basic_json object
  14857. @throw type_error.311 when called on a type other than JSON array or
  14858. null; example: `"cannot use emplace_back() with number"`
  14859. @complexity Amortized constant.
  14860. @liveexample{The example shows how `push_back()` can be used to add
  14861. elements to a JSON array. Note how the `null` value was silently converted
  14862. to a JSON array.,emplace_back}
  14863. @since version 2.0.8
  14864. */
  14865. template<class... Args>
  14866. void emplace_back(Args&& ... args)
  14867. {
  14868. // emplace_back only works for null objects or arrays
  14869. if (JSON_UNLIKELY(not(is_null() or is_array())))
  14870. {
  14871. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  14872. }
  14873. // transform null object into an array
  14874. if (is_null())
  14875. {
  14876. m_type = value_t::array;
  14877. m_value = value_t::array;
  14878. assert_invariant();
  14879. }
  14880. // add element to array (perfect forwarding)
  14881. m_value.array->emplace_back(std::forward<Args>(args)...);
  14882. }
  14883. /*!
  14884. @brief add an object to an object if key does not exist
  14885. Inserts a new element into a JSON object constructed in-place with the
  14886. given @a args if there is no element with the key in the container. If the
  14887. function is called on a JSON null value, an empty object is created before
  14888. appending the value created from @a args.
  14889. @param[in] args arguments to forward to a constructor of @ref basic_json
  14890. @tparam Args compatible types to create a @ref basic_json object
  14891. @return a pair consisting of an iterator to the inserted element, or the
  14892. already-existing element if no insertion happened, and a bool
  14893. denoting whether the insertion took place.
  14894. @throw type_error.311 when called on a type other than JSON object or
  14895. null; example: `"cannot use emplace() with number"`
  14896. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  14897. @liveexample{The example shows how `emplace()` can be used to add elements
  14898. to a JSON object. Note how the `null` value was silently converted to a
  14899. JSON object. Further note how no value is added if there was already one
  14900. value stored with the same key.,emplace}
  14901. @since version 2.0.8
  14902. */
  14903. template<class... Args>
  14904. std::pair<iterator, bool> emplace(Args&& ... args)
  14905. {
  14906. // emplace only works for null objects or arrays
  14907. if (JSON_UNLIKELY(not(is_null() or is_object())))
  14908. {
  14909. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  14910. }
  14911. // transform null object into an object
  14912. if (is_null())
  14913. {
  14914. m_type = value_t::object;
  14915. m_value = value_t::object;
  14916. assert_invariant();
  14917. }
  14918. // add element to array (perfect forwarding)
  14919. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  14920. // create result iterator and set iterator to the result of emplace
  14921. auto it = begin();
  14922. it.m_it.object_iterator = res.first;
  14923. // return pair of iterator and boolean
  14924. return {it, res.second};
  14925. }
  14926. /// Helper for insertion of an iterator
  14927. /// @note: This uses std::distance to support GCC 4.8,
  14928. /// see https://github.com/nlohmann/json/pull/1257
  14929. template<typename... Args>
  14930. iterator insert_iterator(const_iterator pos, Args&& ... args)
  14931. {
  14932. iterator result(this);
  14933. assert(m_value.array != nullptr);
  14934. auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
  14935. m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
  14936. result.m_it.array_iterator = m_value.array->begin() + insert_pos;
  14937. // This could have been written as:
  14938. // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  14939. // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
  14940. return result;
  14941. }
  14942. /*!
  14943. @brief inserts element
  14944. Inserts element @a val before iterator @a pos.
  14945. @param[in] pos iterator before which the content will be inserted; may be
  14946. the end() iterator
  14947. @param[in] val element to insert
  14948. @return iterator pointing to the inserted @a val.
  14949. @throw type_error.309 if called on JSON values other than arrays;
  14950. example: `"cannot use insert() with string"`
  14951. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14952. example: `"iterator does not fit current value"`
  14953. @complexity Constant plus linear in the distance between @a pos and end of
  14954. the container.
  14955. @liveexample{The example shows how `insert()` is used.,insert}
  14956. @since version 1.0.0
  14957. */
  14958. iterator insert(const_iterator pos, const basic_json& val)
  14959. {
  14960. // insert only works for arrays
  14961. if (JSON_LIKELY(is_array()))
  14962. {
  14963. // check if iterator pos fits to this JSON value
  14964. if (JSON_UNLIKELY(pos.m_object != this))
  14965. {
  14966. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  14967. }
  14968. // insert to array and return iterator
  14969. return insert_iterator(pos, val);
  14970. }
  14971. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  14972. }
  14973. /*!
  14974. @brief inserts element
  14975. @copydoc insert(const_iterator, const basic_json&)
  14976. */
  14977. iterator insert(const_iterator pos, basic_json&& val)
  14978. {
  14979. return insert(pos, val);
  14980. }
  14981. /*!
  14982. @brief inserts elements
  14983. Inserts @a cnt copies of @a val before iterator @a pos.
  14984. @param[in] pos iterator before which the content will be inserted; may be
  14985. the end() iterator
  14986. @param[in] cnt number of copies of @a val to insert
  14987. @param[in] val element to insert
  14988. @return iterator pointing to the first element inserted, or @a pos if
  14989. `cnt==0`
  14990. @throw type_error.309 if called on JSON values other than arrays; example:
  14991. `"cannot use insert() with string"`
  14992. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  14993. example: `"iterator does not fit current value"`
  14994. @complexity Linear in @a cnt plus linear in the distance between @a pos
  14995. and end of the container.
  14996. @liveexample{The example shows how `insert()` is used.,insert__count}
  14997. @since version 1.0.0
  14998. */
  14999. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  15000. {
  15001. // insert only works for arrays
  15002. if (JSON_LIKELY(is_array()))
  15003. {
  15004. // check if iterator pos fits to this JSON value
  15005. if (JSON_UNLIKELY(pos.m_object != this))
  15006. {
  15007. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15008. }
  15009. // insert to array and return iterator
  15010. return insert_iterator(pos, cnt, val);
  15011. }
  15012. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15013. }
  15014. /*!
  15015. @brief inserts elements
  15016. Inserts elements from range `[first, last)` before iterator @a pos.
  15017. @param[in] pos iterator before which the content will be inserted; may be
  15018. the end() iterator
  15019. @param[in] first begin of the range of elements to insert
  15020. @param[in] last end of the range of elements to insert
  15021. @throw type_error.309 if called on JSON values other than arrays; example:
  15022. `"cannot use insert() with string"`
  15023. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15024. example: `"iterator does not fit current value"`
  15025. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15026. same JSON value; example: `"iterators do not fit"`
  15027. @throw invalid_iterator.211 if @a first or @a last are iterators into
  15028. container for which insert is called; example: `"passed iterators may not
  15029. belong to container"`
  15030. @return iterator pointing to the first element inserted, or @a pos if
  15031. `first==last`
  15032. @complexity Linear in `std::distance(first, last)` plus linear in the
  15033. distance between @a pos and end of the container.
  15034. @liveexample{The example shows how `insert()` is used.,insert__range}
  15035. @since version 1.0.0
  15036. */
  15037. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  15038. {
  15039. // insert only works for arrays
  15040. if (JSON_UNLIKELY(not is_array()))
  15041. {
  15042. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15043. }
  15044. // check if iterator pos fits to this JSON value
  15045. if (JSON_UNLIKELY(pos.m_object != this))
  15046. {
  15047. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15048. }
  15049. // check if range iterators belong to the same JSON object
  15050. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15051. {
  15052. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15053. }
  15054. if (JSON_UNLIKELY(first.m_object == this))
  15055. {
  15056. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  15057. }
  15058. // insert to array and return iterator
  15059. return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
  15060. }
  15061. /*!
  15062. @brief inserts elements
  15063. Inserts elements from initializer list @a ilist before iterator @a pos.
  15064. @param[in] pos iterator before which the content will be inserted; may be
  15065. the end() iterator
  15066. @param[in] ilist initializer list to insert the values from
  15067. @throw type_error.309 if called on JSON values other than arrays; example:
  15068. `"cannot use insert() with string"`
  15069. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  15070. example: `"iterator does not fit current value"`
  15071. @return iterator pointing to the first element inserted, or @a pos if
  15072. `ilist` is empty
  15073. @complexity Linear in `ilist.size()` plus linear in the distance between
  15074. @a pos and end of the container.
  15075. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  15076. @since version 1.0.0
  15077. */
  15078. iterator insert(const_iterator pos, initializer_list_t ilist)
  15079. {
  15080. // insert only works for arrays
  15081. if (JSON_UNLIKELY(not is_array()))
  15082. {
  15083. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15084. }
  15085. // check if iterator pos fits to this JSON value
  15086. if (JSON_UNLIKELY(pos.m_object != this))
  15087. {
  15088. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  15089. }
  15090. // insert to array and return iterator
  15091. return insert_iterator(pos, ilist.begin(), ilist.end());
  15092. }
  15093. /*!
  15094. @brief inserts elements
  15095. Inserts elements from range `[first, last)`.
  15096. @param[in] first begin of the range of elements to insert
  15097. @param[in] last end of the range of elements to insert
  15098. @throw type_error.309 if called on JSON values other than objects; example:
  15099. `"cannot use insert() with string"`
  15100. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  15101. point to an object; example: `"iterators first and last must point to
  15102. objects"`
  15103. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15104. same JSON value; example: `"iterators do not fit"`
  15105. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  15106. of elements to insert.
  15107. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  15108. @since version 3.0.0
  15109. */
  15110. void insert(const_iterator first, const_iterator last)
  15111. {
  15112. // insert only works for objects
  15113. if (JSON_UNLIKELY(not is_object()))
  15114. {
  15115. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  15116. }
  15117. // check if range iterators belong to the same JSON object
  15118. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15119. {
  15120. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15121. }
  15122. // passed iterators must belong to objects
  15123. if (JSON_UNLIKELY(not first.m_object->is_object()))
  15124. {
  15125. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  15126. }
  15127. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  15128. }
  15129. /*!
  15130. @brief updates a JSON object from another object, overwriting existing keys
  15131. Inserts all values from JSON object @a j and overwrites existing keys.
  15132. @param[in] j JSON object to read values from
  15133. @throw type_error.312 if called on JSON values other than objects; example:
  15134. `"cannot use update() with string"`
  15135. @complexity O(N*log(size() + N)), where N is the number of elements to
  15136. insert.
  15137. @liveexample{The example shows how `update()` is used.,update}
  15138. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  15139. @since version 3.0.0
  15140. */
  15141. void update(const_reference j)
  15142. {
  15143. // implicitly convert null value to an empty object
  15144. if (is_null())
  15145. {
  15146. m_type = value_t::object;
  15147. m_value.object = create<object_t>();
  15148. assert_invariant();
  15149. }
  15150. if (JSON_UNLIKELY(not is_object()))
  15151. {
  15152. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  15153. }
  15154. if (JSON_UNLIKELY(not j.is_object()))
  15155. {
  15156. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  15157. }
  15158. for (auto it = j.cbegin(); it != j.cend(); ++it)
  15159. {
  15160. m_value.object->operator[](it.key()) = it.value();
  15161. }
  15162. }
  15163. /*!
  15164. @brief updates a JSON object from another object, overwriting existing keys
  15165. Inserts all values from from range `[first, last)` and overwrites existing
  15166. keys.
  15167. @param[in] first begin of the range of elements to insert
  15168. @param[in] last end of the range of elements to insert
  15169. @throw type_error.312 if called on JSON values other than objects; example:
  15170. `"cannot use update() with string"`
  15171. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  15172. point to an object; example: `"iterators first and last must point to
  15173. objects"`
  15174. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  15175. same JSON value; example: `"iterators do not fit"`
  15176. @complexity O(N*log(size() + N)), where N is the number of elements to
  15177. insert.
  15178. @liveexample{The example shows how `update()` is used__range.,update}
  15179. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  15180. @since version 3.0.0
  15181. */
  15182. void update(const_iterator first, const_iterator last)
  15183. {
  15184. // implicitly convert null value to an empty object
  15185. if (is_null())
  15186. {
  15187. m_type = value_t::object;
  15188. m_value.object = create<object_t>();
  15189. assert_invariant();
  15190. }
  15191. if (JSON_UNLIKELY(not is_object()))
  15192. {
  15193. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  15194. }
  15195. // check if range iterators belong to the same JSON object
  15196. if (JSON_UNLIKELY(first.m_object != last.m_object))
  15197. {
  15198. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  15199. }
  15200. // passed iterators must belong to objects
  15201. if (JSON_UNLIKELY(not first.m_object->is_object()
  15202. or not last.m_object->is_object()))
  15203. {
  15204. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  15205. }
  15206. for (auto it = first; it != last; ++it)
  15207. {
  15208. m_value.object->operator[](it.key()) = it.value();
  15209. }
  15210. }
  15211. /*!
  15212. @brief exchanges the values
  15213. Exchanges the contents of the JSON value with those of @a other. Does not
  15214. invoke any move, copy, or swap operations on individual elements. All
  15215. iterators and references remain valid. The past-the-end iterator is
  15216. invalidated.
  15217. @param[in,out] other JSON value to exchange the contents with
  15218. @complexity Constant.
  15219. @liveexample{The example below shows how JSON values can be swapped with
  15220. `swap()`.,swap__reference}
  15221. @since version 1.0.0
  15222. */
  15223. void swap(reference other) noexcept (
  15224. std::is_nothrow_move_constructible<value_t>::value and
  15225. std::is_nothrow_move_assignable<value_t>::value and
  15226. std::is_nothrow_move_constructible<json_value>::value and
  15227. std::is_nothrow_move_assignable<json_value>::value
  15228. )
  15229. {
  15230. std::swap(m_type, other.m_type);
  15231. std::swap(m_value, other.m_value);
  15232. assert_invariant();
  15233. }
  15234. /*!
  15235. @brief exchanges the values
  15236. Exchanges the contents of a JSON array with those of @a other. Does not
  15237. invoke any move, copy, or swap operations on individual elements. All
  15238. iterators and references remain valid. The past-the-end iterator is
  15239. invalidated.
  15240. @param[in,out] other array to exchange the contents with
  15241. @throw type_error.310 when JSON value is not an array; example: `"cannot
  15242. use swap() with string"`
  15243. @complexity Constant.
  15244. @liveexample{The example below shows how arrays can be swapped with
  15245. `swap()`.,swap__array_t}
  15246. @since version 1.0.0
  15247. */
  15248. void swap(array_t& other)
  15249. {
  15250. // swap only works for arrays
  15251. if (JSON_LIKELY(is_array()))
  15252. {
  15253. std::swap(*(m_value.array), other);
  15254. }
  15255. else
  15256. {
  15257. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15258. }
  15259. }
  15260. /*!
  15261. @brief exchanges the values
  15262. Exchanges the contents of a JSON object with those of @a other. Does not
  15263. invoke any move, copy, or swap operations on individual elements. All
  15264. iterators and references remain valid. The past-the-end iterator is
  15265. invalidated.
  15266. @param[in,out] other object to exchange the contents with
  15267. @throw type_error.310 when JSON value is not an object; example:
  15268. `"cannot use swap() with string"`
  15269. @complexity Constant.
  15270. @liveexample{The example below shows how objects can be swapped with
  15271. `swap()`.,swap__object_t}
  15272. @since version 1.0.0
  15273. */
  15274. void swap(object_t& other)
  15275. {
  15276. // swap only works for objects
  15277. if (JSON_LIKELY(is_object()))
  15278. {
  15279. std::swap(*(m_value.object), other);
  15280. }
  15281. else
  15282. {
  15283. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15284. }
  15285. }
  15286. /*!
  15287. @brief exchanges the values
  15288. Exchanges the contents of a JSON string with those of @a other. Does not
  15289. invoke any move, copy, or swap operations on individual elements. All
  15290. iterators and references remain valid. The past-the-end iterator is
  15291. invalidated.
  15292. @param[in,out] other string to exchange the contents with
  15293. @throw type_error.310 when JSON value is not a string; example: `"cannot
  15294. use swap() with boolean"`
  15295. @complexity Constant.
  15296. @liveexample{The example below shows how strings can be swapped with
  15297. `swap()`.,swap__string_t}
  15298. @since version 1.0.0
  15299. */
  15300. void swap(string_t& other)
  15301. {
  15302. // swap only works for strings
  15303. if (JSON_LIKELY(is_string()))
  15304. {
  15305. std::swap(*(m_value.string), other);
  15306. }
  15307. else
  15308. {
  15309. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  15310. }
  15311. }
  15312. /// @}
  15313. public:
  15314. //////////////////////////////////////////
  15315. // lexicographical comparison operators //
  15316. //////////////////////////////////////////
  15317. /// @name lexicographical comparison operators
  15318. /// @{
  15319. /*!
  15320. @brief comparison: equal
  15321. Compares two JSON values for equality according to the following rules:
  15322. - Two JSON values are equal if (1) they are from the same type and (2)
  15323. their stored values are the same according to their respective
  15324. `operator==`.
  15325. - Integer and floating-point numbers are automatically converted before
  15326. comparison. Note than two NaN values are always treated as unequal.
  15327. - Two JSON null values are equal.
  15328. @note Floating-point inside JSON values numbers are compared with
  15329. `json::number_float_t::operator==` which is `double::operator==` by
  15330. default. To compare floating-point while respecting an epsilon, an alternative
  15331. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  15332. could be used, for instance
  15333. @code {.cpp}
  15334. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  15335. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  15336. {
  15337. return std::abs(a - b) <= epsilon;
  15338. }
  15339. @endcode
  15340. @note NaN values never compare equal to themselves or to other NaN values.
  15341. @param[in] lhs first JSON value to consider
  15342. @param[in] rhs second JSON value to consider
  15343. @return whether the values @a lhs and @a rhs are equal
  15344. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15345. @complexity Linear.
  15346. @liveexample{The example demonstrates comparing several JSON
  15347. types.,operator__equal}
  15348. @since version 1.0.0
  15349. */
  15350. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  15351. {
  15352. const auto lhs_type = lhs.type();
  15353. const auto rhs_type = rhs.type();
  15354. if (lhs_type == rhs_type)
  15355. {
  15356. switch (lhs_type)
  15357. {
  15358. case value_t::array:
  15359. return *lhs.m_value.array == *rhs.m_value.array;
  15360. case value_t::object:
  15361. return *lhs.m_value.object == *rhs.m_value.object;
  15362. case value_t::null:
  15363. return true;
  15364. case value_t::string:
  15365. return *lhs.m_value.string == *rhs.m_value.string;
  15366. case value_t::boolean:
  15367. return lhs.m_value.boolean == rhs.m_value.boolean;
  15368. case value_t::number_integer:
  15369. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  15370. case value_t::number_unsigned:
  15371. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  15372. case value_t::number_float:
  15373. return lhs.m_value.number_float == rhs.m_value.number_float;
  15374. default:
  15375. return false;
  15376. }
  15377. }
  15378. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15379. {
  15380. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  15381. }
  15382. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15383. {
  15384. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  15385. }
  15386. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15387. {
  15388. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  15389. }
  15390. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15391. {
  15392. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  15393. }
  15394. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15395. {
  15396. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  15397. }
  15398. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15399. {
  15400. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  15401. }
  15402. return false;
  15403. }
  15404. /*!
  15405. @brief comparison: equal
  15406. @copydoc operator==(const_reference, const_reference)
  15407. */
  15408. template<typename ScalarType, typename std::enable_if<
  15409. std::is_scalar<ScalarType>::value, int>::type = 0>
  15410. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  15411. {
  15412. return lhs == basic_json(rhs);
  15413. }
  15414. /*!
  15415. @brief comparison: equal
  15416. @copydoc operator==(const_reference, const_reference)
  15417. */
  15418. template<typename ScalarType, typename std::enable_if<
  15419. std::is_scalar<ScalarType>::value, int>::type = 0>
  15420. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  15421. {
  15422. return basic_json(lhs) == rhs;
  15423. }
  15424. /*!
  15425. @brief comparison: not equal
  15426. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  15427. @param[in] lhs first JSON value to consider
  15428. @param[in] rhs second JSON value to consider
  15429. @return whether the values @a lhs and @a rhs are not equal
  15430. @complexity Linear.
  15431. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15432. @liveexample{The example demonstrates comparing several JSON
  15433. types.,operator__notequal}
  15434. @since version 1.0.0
  15435. */
  15436. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  15437. {
  15438. return not (lhs == rhs);
  15439. }
  15440. /*!
  15441. @brief comparison: not equal
  15442. @copydoc operator!=(const_reference, const_reference)
  15443. */
  15444. template<typename ScalarType, typename std::enable_if<
  15445. std::is_scalar<ScalarType>::value, int>::type = 0>
  15446. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  15447. {
  15448. return lhs != basic_json(rhs);
  15449. }
  15450. /*!
  15451. @brief comparison: not equal
  15452. @copydoc operator!=(const_reference, const_reference)
  15453. */
  15454. template<typename ScalarType, typename std::enable_if<
  15455. std::is_scalar<ScalarType>::value, int>::type = 0>
  15456. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  15457. {
  15458. return basic_json(lhs) != rhs;
  15459. }
  15460. /*!
  15461. @brief comparison: less than
  15462. Compares whether one JSON value @a lhs is less than another JSON value @a
  15463. rhs according to the following rules:
  15464. - If @a lhs and @a rhs have the same type, the values are compared using
  15465. the default `<` operator.
  15466. - Integer and floating-point numbers are automatically converted before
  15467. comparison
  15468. - In case @a lhs and @a rhs have different types, the values are ignored
  15469. and the order of the types is considered, see
  15470. @ref operator<(const value_t, const value_t).
  15471. @param[in] lhs first JSON value to consider
  15472. @param[in] rhs second JSON value to consider
  15473. @return whether @a lhs is less than @a rhs
  15474. @complexity Linear.
  15475. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15476. @liveexample{The example demonstrates comparing several JSON
  15477. types.,operator__less}
  15478. @since version 1.0.0
  15479. */
  15480. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  15481. {
  15482. const auto lhs_type = lhs.type();
  15483. const auto rhs_type = rhs.type();
  15484. if (lhs_type == rhs_type)
  15485. {
  15486. switch (lhs_type)
  15487. {
  15488. case value_t::array:
  15489. // note parentheses are necessary, see
  15490. // https://github.com/nlohmann/json/issues/1530
  15491. return (*lhs.m_value.array) < (*rhs.m_value.array);
  15492. case value_t::object:
  15493. return *lhs.m_value.object < *rhs.m_value.object;
  15494. case value_t::null:
  15495. return false;
  15496. case value_t::string:
  15497. return *lhs.m_value.string < *rhs.m_value.string;
  15498. case value_t::boolean:
  15499. return lhs.m_value.boolean < rhs.m_value.boolean;
  15500. case value_t::number_integer:
  15501. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  15502. case value_t::number_unsigned:
  15503. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  15504. case value_t::number_float:
  15505. return lhs.m_value.number_float < rhs.m_value.number_float;
  15506. default:
  15507. return false;
  15508. }
  15509. }
  15510. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  15511. {
  15512. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  15513. }
  15514. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  15515. {
  15516. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  15517. }
  15518. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  15519. {
  15520. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  15521. }
  15522. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  15523. {
  15524. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  15525. }
  15526. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  15527. {
  15528. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  15529. }
  15530. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  15531. {
  15532. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  15533. }
  15534. // We only reach this line if we cannot compare values. In that case,
  15535. // we compare types. Note we have to call the operator explicitly,
  15536. // because MSVC has problems otherwise.
  15537. return operator<(lhs_type, rhs_type);
  15538. }
  15539. /*!
  15540. @brief comparison: less than
  15541. @copydoc operator<(const_reference, const_reference)
  15542. */
  15543. template<typename ScalarType, typename std::enable_if<
  15544. std::is_scalar<ScalarType>::value, int>::type = 0>
  15545. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  15546. {
  15547. return lhs < basic_json(rhs);
  15548. }
  15549. /*!
  15550. @brief comparison: less than
  15551. @copydoc operator<(const_reference, const_reference)
  15552. */
  15553. template<typename ScalarType, typename std::enable_if<
  15554. std::is_scalar<ScalarType>::value, int>::type = 0>
  15555. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  15556. {
  15557. return basic_json(lhs) < rhs;
  15558. }
  15559. /*!
  15560. @brief comparison: less than or equal
  15561. Compares whether one JSON value @a lhs is less than or equal to another
  15562. JSON value by calculating `not (rhs < lhs)`.
  15563. @param[in] lhs first JSON value to consider
  15564. @param[in] rhs second JSON value to consider
  15565. @return whether @a lhs is less than or equal to @a rhs
  15566. @complexity Linear.
  15567. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15568. @liveexample{The example demonstrates comparing several JSON
  15569. types.,operator__greater}
  15570. @since version 1.0.0
  15571. */
  15572. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  15573. {
  15574. return not (rhs < lhs);
  15575. }
  15576. /*!
  15577. @brief comparison: less than or equal
  15578. @copydoc operator<=(const_reference, const_reference)
  15579. */
  15580. template<typename ScalarType, typename std::enable_if<
  15581. std::is_scalar<ScalarType>::value, int>::type = 0>
  15582. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  15583. {
  15584. return lhs <= basic_json(rhs);
  15585. }
  15586. /*!
  15587. @brief comparison: less than or equal
  15588. @copydoc operator<=(const_reference, const_reference)
  15589. */
  15590. template<typename ScalarType, typename std::enable_if<
  15591. std::is_scalar<ScalarType>::value, int>::type = 0>
  15592. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  15593. {
  15594. return basic_json(lhs) <= rhs;
  15595. }
  15596. /*!
  15597. @brief comparison: greater than
  15598. Compares whether one JSON value @a lhs is greater than another
  15599. JSON value by calculating `not (lhs <= rhs)`.
  15600. @param[in] lhs first JSON value to consider
  15601. @param[in] rhs second JSON value to consider
  15602. @return whether @a lhs is greater than to @a rhs
  15603. @complexity Linear.
  15604. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15605. @liveexample{The example demonstrates comparing several JSON
  15606. types.,operator__lessequal}
  15607. @since version 1.0.0
  15608. */
  15609. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  15610. {
  15611. return not (lhs <= rhs);
  15612. }
  15613. /*!
  15614. @brief comparison: greater than
  15615. @copydoc operator>(const_reference, const_reference)
  15616. */
  15617. template<typename ScalarType, typename std::enable_if<
  15618. std::is_scalar<ScalarType>::value, int>::type = 0>
  15619. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  15620. {
  15621. return lhs > basic_json(rhs);
  15622. }
  15623. /*!
  15624. @brief comparison: greater than
  15625. @copydoc operator>(const_reference, const_reference)
  15626. */
  15627. template<typename ScalarType, typename std::enable_if<
  15628. std::is_scalar<ScalarType>::value, int>::type = 0>
  15629. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  15630. {
  15631. return basic_json(lhs) > rhs;
  15632. }
  15633. /*!
  15634. @brief comparison: greater than or equal
  15635. Compares whether one JSON value @a lhs is greater than or equal to another
  15636. JSON value by calculating `not (lhs < rhs)`.
  15637. @param[in] lhs first JSON value to consider
  15638. @param[in] rhs second JSON value to consider
  15639. @return whether @a lhs is greater than or equal to @a rhs
  15640. @complexity Linear.
  15641. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15642. @liveexample{The example demonstrates comparing several JSON
  15643. types.,operator__greaterequal}
  15644. @since version 1.0.0
  15645. */
  15646. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  15647. {
  15648. return not (lhs < rhs);
  15649. }
  15650. /*!
  15651. @brief comparison: greater than or equal
  15652. @copydoc operator>=(const_reference, const_reference)
  15653. */
  15654. template<typename ScalarType, typename std::enable_if<
  15655. std::is_scalar<ScalarType>::value, int>::type = 0>
  15656. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  15657. {
  15658. return lhs >= basic_json(rhs);
  15659. }
  15660. /*!
  15661. @brief comparison: greater than or equal
  15662. @copydoc operator>=(const_reference, const_reference)
  15663. */
  15664. template<typename ScalarType, typename std::enable_if<
  15665. std::is_scalar<ScalarType>::value, int>::type = 0>
  15666. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  15667. {
  15668. return basic_json(lhs) >= rhs;
  15669. }
  15670. /// @}
  15671. ///////////////////
  15672. // serialization //
  15673. ///////////////////
  15674. /// @name serialization
  15675. /// @{
  15676. /*!
  15677. @brief serialize to stream
  15678. Serialize the given JSON value @a j to the output stream @a o. The JSON
  15679. value will be serialized using the @ref dump member function.
  15680. - The indentation of the output can be controlled with the member variable
  15681. `width` of the output stream @a o. For instance, using the manipulator
  15682. `std::setw(4)` on @a o sets the indentation level to `4` and the
  15683. serialization result is the same as calling `dump(4)`.
  15684. - The indentation character can be controlled with the member variable
  15685. `fill` of the output stream @a o. For instance, the manipulator
  15686. `std::setfill('\\t')` sets indentation to use a tab character rather than
  15687. the default space character.
  15688. @param[in,out] o stream to serialize to
  15689. @param[in] j JSON value to serialize
  15690. @return the stream @a o
  15691. @throw type_error.316 if a string stored inside the JSON value is not
  15692. UTF-8 encoded
  15693. @complexity Linear.
  15694. @liveexample{The example below shows the serialization with different
  15695. parameters to `width` to adjust the indentation level.,operator_serialize}
  15696. @since version 1.0.0; indentation character added in version 3.0.0
  15697. */
  15698. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  15699. {
  15700. // read width member and use it as indentation parameter if nonzero
  15701. const bool pretty_print = o.width() > 0;
  15702. const auto indentation = pretty_print ? o.width() : 0;
  15703. // reset width to 0 for subsequent calls to this stream
  15704. o.width(0);
  15705. // do the actual serialization
  15706. serializer s(detail::output_adapter<char>(o), o.fill());
  15707. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  15708. return o;
  15709. }
  15710. /*!
  15711. @brief serialize to stream
  15712. @deprecated This stream operator is deprecated and will be removed in
  15713. future 4.0.0 of the library. Please use
  15714. @ref operator<<(std::ostream&, const basic_json&)
  15715. instead; that is, replace calls like `j >> o;` with `o << j;`.
  15716. @since version 1.0.0; deprecated since version 3.0.0
  15717. */
  15718. JSON_DEPRECATED
  15719. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  15720. {
  15721. return o << j;
  15722. }
  15723. /// @}
  15724. /////////////////////
  15725. // deserialization //
  15726. /////////////////////
  15727. /// @name deserialization
  15728. /// @{
  15729. /*!
  15730. @brief deserialize from a compatible input
  15731. This function reads from a compatible input. Examples are:
  15732. - an array of 1-byte values
  15733. - strings with character/literal type with size of 1 byte
  15734. - input streams
  15735. - container with contiguous storage of 1-byte values. Compatible container
  15736. types include `std::vector`, `std::string`, `std::array`,
  15737. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15738. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15739. containers can be used as long as they implement random-access iterators
  15740. and a contiguous storage.
  15741. @pre Each element of the container has a size of 1 byte. Violating this
  15742. precondition yields undefined behavior. **This precondition is enforced
  15743. with a static assertion.**
  15744. @pre The container storage is contiguous. Violating this precondition
  15745. yields undefined behavior. **This precondition is enforced with an
  15746. assertion.**
  15747. @warning There is no way to enforce all preconditions at compile-time. If
  15748. the function is called with a noncompliant container and with
  15749. assertions switched off, the behavior is undefined and will most
  15750. likely yield segmentation violation.
  15751. @param[in] i input to read from
  15752. @param[in] cb a parser callback function of type @ref parser_callback_t
  15753. which is used to control the deserialization by filtering unwanted values
  15754. (optional)
  15755. @param[in] allow_exceptions whether to throw exceptions in case of a
  15756. parse error (optional, true by default)
  15757. @return deserialized JSON value; in case of a parse error and
  15758. @a allow_exceptions set to `false`, the return value will be
  15759. value_t::discarded.
  15760. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15761. of input; expected string literal""`
  15762. @throw parse_error.102 if to_unicode fails or surrogate error
  15763. @throw parse_error.103 if to_unicode fails
  15764. @complexity Linear in the length of the input. The parser is a predictive
  15765. LL(1) parser. The complexity can be higher if the parser callback function
  15766. @a cb has a super-linear complexity.
  15767. @note A UTF-8 byte order mark is silently ignored.
  15768. @liveexample{The example below demonstrates the `parse()` function reading
  15769. from an array.,parse__array__parser_callback_t}
  15770. @liveexample{The example below demonstrates the `parse()` function with
  15771. and without callback function.,parse__string__parser_callback_t}
  15772. @liveexample{The example below demonstrates the `parse()` function with
  15773. and without callback function.,parse__istream__parser_callback_t}
  15774. @liveexample{The example below demonstrates the `parse()` function reading
  15775. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  15776. @since version 2.0.3 (contiguous containers)
  15777. */
  15778. JSON_NODISCARD
  15779. static basic_json parse(detail::input_adapter&& i,
  15780. const parser_callback_t cb = nullptr,
  15781. const bool allow_exceptions = true)
  15782. {
  15783. basic_json result;
  15784. parser(i, cb, allow_exceptions).parse(true, result);
  15785. return result;
  15786. }
  15787. static bool accept(detail::input_adapter&& i)
  15788. {
  15789. return parser(i).accept(true);
  15790. }
  15791. /*!
  15792. @brief generate SAX events
  15793. The SAX event lister must follow the interface of @ref json_sax.
  15794. This function reads from a compatible input. Examples are:
  15795. - an array of 1-byte values
  15796. - strings with character/literal type with size of 1 byte
  15797. - input streams
  15798. - container with contiguous storage of 1-byte values. Compatible container
  15799. types include `std::vector`, `std::string`, `std::array`,
  15800. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  15801. arrays can be used with `std::begin()`/`std::end()`. User-defined
  15802. containers can be used as long as they implement random-access iterators
  15803. and a contiguous storage.
  15804. @pre Each element of the container has a size of 1 byte. Violating this
  15805. precondition yields undefined behavior. **This precondition is enforced
  15806. with a static assertion.**
  15807. @pre The container storage is contiguous. Violating this precondition
  15808. yields undefined behavior. **This precondition is enforced with an
  15809. assertion.**
  15810. @warning There is no way to enforce all preconditions at compile-time. If
  15811. the function is called with a noncompliant container and with
  15812. assertions switched off, the behavior is undefined and will most
  15813. likely yield segmentation violation.
  15814. @param[in] i input to read from
  15815. @param[in,out] sax SAX event listener
  15816. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  15817. @param[in] strict whether the input has to be consumed completely
  15818. @return return value of the last processed SAX event
  15819. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  15820. of input; expected string literal""`
  15821. @throw parse_error.102 if to_unicode fails or surrogate error
  15822. @throw parse_error.103 if to_unicode fails
  15823. @complexity Linear in the length of the input. The parser is a predictive
  15824. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  15825. a super-linear complexity.
  15826. @note A UTF-8 byte order mark is silently ignored.
  15827. @liveexample{The example below demonstrates the `sax_parse()` function
  15828. reading from string and processing the events with a user-defined SAX
  15829. event consumer.,sax_parse}
  15830. @since version 3.2.0
  15831. */
  15832. template <typename SAX>
  15833. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  15834. input_format_t format = input_format_t::json,
  15835. const bool strict = true)
  15836. {
  15837. assert(sax);
  15838. return format == input_format_t::json
  15839. ? parser(std::move(i)).sax_parse(sax, strict)
  15840. : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  15841. }
  15842. /*!
  15843. @brief deserialize from an iterator range with contiguous storage
  15844. This function reads from an iterator range of a container with contiguous
  15845. storage of 1-byte values. Compatible container types include
  15846. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  15847. `std::initializer_list`. Furthermore, C-style arrays can be used with
  15848. `std::begin()`/`std::end()`. User-defined containers can be used as long
  15849. as they implement random-access iterators and a contiguous storage.
  15850. @pre The iterator range is contiguous. Violating this precondition yields
  15851. undefined behavior. **This precondition is enforced with an assertion.**
  15852. @pre Each element in the range has a size of 1 byte. Violating this
  15853. precondition yields undefined behavior. **This precondition is enforced
  15854. with a static assertion.**
  15855. @warning There is no way to enforce all preconditions at compile-time. If
  15856. the function is called with noncompliant iterators and with
  15857. assertions switched off, the behavior is undefined and will most
  15858. likely yield segmentation violation.
  15859. @tparam IteratorType iterator of container with contiguous storage
  15860. @param[in] first begin of the range to parse (included)
  15861. @param[in] last end of the range to parse (excluded)
  15862. @param[in] cb a parser callback function of type @ref parser_callback_t
  15863. which is used to control the deserialization by filtering unwanted values
  15864. (optional)
  15865. @param[in] allow_exceptions whether to throw exceptions in case of a
  15866. parse error (optional, true by default)
  15867. @return deserialized JSON value; in case of a parse error and
  15868. @a allow_exceptions set to `false`, the return value will be
  15869. value_t::discarded.
  15870. @throw parse_error.101 in case of an unexpected token
  15871. @throw parse_error.102 if to_unicode fails or surrogate error
  15872. @throw parse_error.103 if to_unicode fails
  15873. @complexity Linear in the length of the input. The parser is a predictive
  15874. LL(1) parser. The complexity can be higher if the parser callback function
  15875. @a cb has a super-linear complexity.
  15876. @note A UTF-8 byte order mark is silently ignored.
  15877. @liveexample{The example below demonstrates the `parse()` function reading
  15878. from an iterator range.,parse__iteratortype__parser_callback_t}
  15879. @since version 2.0.3
  15880. */
  15881. template<class IteratorType, typename std::enable_if<
  15882. std::is_base_of<
  15883. std::random_access_iterator_tag,
  15884. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15885. static basic_json parse(IteratorType first, IteratorType last,
  15886. const parser_callback_t cb = nullptr,
  15887. const bool allow_exceptions = true)
  15888. {
  15889. basic_json result;
  15890. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  15891. return result;
  15892. }
  15893. template<class IteratorType, typename std::enable_if<
  15894. std::is_base_of<
  15895. std::random_access_iterator_tag,
  15896. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15897. static bool accept(IteratorType first, IteratorType last)
  15898. {
  15899. return parser(detail::input_adapter(first, last)).accept(true);
  15900. }
  15901. template<class IteratorType, class SAX, typename std::enable_if<
  15902. std::is_base_of<
  15903. std::random_access_iterator_tag,
  15904. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  15905. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  15906. {
  15907. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  15908. }
  15909. /*!
  15910. @brief deserialize from stream
  15911. @deprecated This stream operator is deprecated and will be removed in
  15912. version 4.0.0 of the library. Please use
  15913. @ref operator>>(std::istream&, basic_json&)
  15914. instead; that is, replace calls like `j << i;` with `i >> j;`.
  15915. @since version 1.0.0; deprecated since version 3.0.0
  15916. */
  15917. JSON_DEPRECATED
  15918. friend std::istream& operator<<(basic_json& j, std::istream& i)
  15919. {
  15920. return operator>>(i, j);
  15921. }
  15922. /*!
  15923. @brief deserialize from stream
  15924. Deserializes an input stream to a JSON value.
  15925. @param[in,out] i input stream to read a serialized JSON value from
  15926. @param[in,out] j JSON value to write the deserialized input to
  15927. @throw parse_error.101 in case of an unexpected token
  15928. @throw parse_error.102 if to_unicode fails or surrogate error
  15929. @throw parse_error.103 if to_unicode fails
  15930. @complexity Linear in the length of the input. The parser is a predictive
  15931. LL(1) parser.
  15932. @note A UTF-8 byte order mark is silently ignored.
  15933. @liveexample{The example below shows how a JSON value is constructed by
  15934. reading a serialization from a stream.,operator_deserialize}
  15935. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  15936. parser callback function to filter values while parsing
  15937. @since version 1.0.0
  15938. */
  15939. friend std::istream& operator>>(std::istream& i, basic_json& j)
  15940. {
  15941. parser(detail::input_adapter(i)).parse(false, j);
  15942. return i;
  15943. }
  15944. /// @}
  15945. ///////////////////////////
  15946. // convenience functions //
  15947. ///////////////////////////
  15948. /*!
  15949. @brief return the type as string
  15950. Returns the type name as string to be used in error messages - usually to
  15951. indicate that a function was called on a wrong JSON type.
  15952. @return a string representation of a the @a m_type member:
  15953. Value type | return value
  15954. ----------- | -------------
  15955. null | `"null"`
  15956. boolean | `"boolean"`
  15957. string | `"string"`
  15958. number | `"number"` (for all number types)
  15959. object | `"object"`
  15960. array | `"array"`
  15961. discarded | `"discarded"`
  15962. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  15963. @complexity Constant.
  15964. @liveexample{The following code exemplifies `type_name()` for all JSON
  15965. types.,type_name}
  15966. @sa @ref type() -- return the type of the JSON value
  15967. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  15968. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  15969. since 3.0.0
  15970. */
  15971. const char* type_name() const noexcept
  15972. {
  15973. {
  15974. switch (m_type)
  15975. {
  15976. case value_t::null:
  15977. return "null";
  15978. case value_t::object:
  15979. return "object";
  15980. case value_t::array:
  15981. return "array";
  15982. case value_t::string:
  15983. return "string";
  15984. case value_t::boolean:
  15985. return "boolean";
  15986. case value_t::discarded:
  15987. return "discarded";
  15988. default:
  15989. return "number";
  15990. }
  15991. }
  15992. }
  15993. private:
  15994. //////////////////////
  15995. // member variables //
  15996. //////////////////////
  15997. /// the type of the current element
  15998. value_t m_type = value_t::null;
  15999. /// the value of the current element
  16000. json_value m_value = {};
  16001. //////////////////////////////////////////
  16002. // binary serialization/deserialization //
  16003. //////////////////////////////////////////
  16004. /// @name binary serialization/deserialization support
  16005. /// @{
  16006. public:
  16007. /*!
  16008. @brief create a CBOR serialization of a given JSON value
  16009. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  16010. Binary Object Representation) serialization format. CBOR is a binary
  16011. serialization format which aims to be more compact than JSON itself, yet
  16012. more efficient to parse.
  16013. The library uses the following mapping from JSON values types to
  16014. CBOR types according to the CBOR specification (RFC 7049):
  16015. JSON value type | value/range | CBOR type | first byte
  16016. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  16017. null | `null` | Null | 0xF6
  16018. boolean | `true` | True | 0xF5
  16019. boolean | `false` | False | 0xF4
  16020. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  16021. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  16022. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  16023. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  16024. number_integer | -24..-1 | Negative integer | 0x20..0x37
  16025. number_integer | 0..23 | Integer | 0x00..0x17
  16026. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  16027. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  16028. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  16029. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  16030. number_unsigned | 0..23 | Integer | 0x00..0x17
  16031. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  16032. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  16033. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  16034. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  16035. number_float | *any value* | Double-Precision Float | 0xFB
  16036. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  16037. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  16038. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  16039. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  16040. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  16041. array | *size*: 0..23 | array | 0x80..0x97
  16042. array | *size*: 23..255 | array (1 byte follow) | 0x98
  16043. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  16044. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  16045. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  16046. object | *size*: 0..23 | map | 0xA0..0xB7
  16047. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  16048. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  16049. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  16050. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  16051. @note The mapping is **complete** in the sense that any JSON value type
  16052. can be converted to a CBOR value.
  16053. @note If NaN or Infinity are stored inside a JSON number, they are
  16054. serialized properly. This behavior differs from the @ref dump()
  16055. function which serializes NaN or Infinity to `null`.
  16056. @note The following CBOR types are not used in the conversion:
  16057. - byte strings (0x40..0x5F)
  16058. - UTF-8 strings terminated by "break" (0x7F)
  16059. - arrays terminated by "break" (0x9F)
  16060. - maps terminated by "break" (0xBF)
  16061. - date/time (0xC0..0xC1)
  16062. - bignum (0xC2..0xC3)
  16063. - decimal fraction (0xC4)
  16064. - bigfloat (0xC5)
  16065. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  16066. - expected conversions (0xD5..0xD7)
  16067. - simple values (0xE0..0xF3, 0xF8)
  16068. - undefined (0xF7)
  16069. - half and single-precision floats (0xF9-0xFA)
  16070. - break (0xFF)
  16071. @param[in] j JSON value to serialize
  16072. @return MessagePack serialization as byte vector
  16073. @complexity Linear in the size of the JSON value @a j.
  16074. @liveexample{The example shows the serialization of a JSON value to a byte
  16075. vector in CBOR format.,to_cbor}
  16076. @sa http://cbor.io
  16077. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16078. analogous deserialization
  16079. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16080. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16081. related UBJSON format
  16082. @since version 2.0.9
  16083. */
  16084. static std::vector<uint8_t> to_cbor(const basic_json& j)
  16085. {
  16086. std::vector<uint8_t> result;
  16087. to_cbor(j, result);
  16088. return result;
  16089. }
  16090. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  16091. {
  16092. binary_writer<uint8_t>(o).write_cbor(j);
  16093. }
  16094. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  16095. {
  16096. binary_writer<char>(o).write_cbor(j);
  16097. }
  16098. /*!
  16099. @brief create a MessagePack serialization of a given JSON value
  16100. Serializes a given JSON value @a j to a byte vector using the MessagePack
  16101. serialization format. MessagePack is a binary serialization format which
  16102. aims to be more compact than JSON itself, yet more efficient to parse.
  16103. The library uses the following mapping from JSON values types to
  16104. MessagePack types according to the MessagePack specification:
  16105. JSON value type | value/range | MessagePack type | first byte
  16106. --------------- | --------------------------------- | ---------------- | ----------
  16107. null | `null` | nil | 0xC0
  16108. boolean | `true` | true | 0xC3
  16109. boolean | `false` | false | 0xC2
  16110. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  16111. number_integer | -2147483648..-32769 | int32 | 0xD2
  16112. number_integer | -32768..-129 | int16 | 0xD1
  16113. number_integer | -128..-33 | int8 | 0xD0
  16114. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  16115. number_integer | 0..127 | positive fixint | 0x00..0x7F
  16116. number_integer | 128..255 | uint 8 | 0xCC
  16117. number_integer | 256..65535 | uint 16 | 0xCD
  16118. number_integer | 65536..4294967295 | uint 32 | 0xCE
  16119. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  16120. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  16121. number_unsigned | 128..255 | uint 8 | 0xCC
  16122. number_unsigned | 256..65535 | uint 16 | 0xCD
  16123. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  16124. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  16125. number_float | *any value* | float 64 | 0xCB
  16126. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  16127. string | *length*: 32..255 | str 8 | 0xD9
  16128. string | *length*: 256..65535 | str 16 | 0xDA
  16129. string | *length*: 65536..4294967295 | str 32 | 0xDB
  16130. array | *size*: 0..15 | fixarray | 0x90..0x9F
  16131. array | *size*: 16..65535 | array 16 | 0xDC
  16132. array | *size*: 65536..4294967295 | array 32 | 0xDD
  16133. object | *size*: 0..15 | fix map | 0x80..0x8F
  16134. object | *size*: 16..65535 | map 16 | 0xDE
  16135. object | *size*: 65536..4294967295 | map 32 | 0xDF
  16136. @note The mapping is **complete** in the sense that any JSON value type
  16137. can be converted to a MessagePack value.
  16138. @note The following values can **not** be converted to a MessagePack value:
  16139. - strings with more than 4294967295 bytes
  16140. - arrays with more than 4294967295 elements
  16141. - objects with more than 4294967295 elements
  16142. @note The following MessagePack types are not used in the conversion:
  16143. - bin 8 - bin 32 (0xC4..0xC6)
  16144. - ext 8 - ext 32 (0xC7..0xC9)
  16145. - float 32 (0xCA)
  16146. - fixext 1 - fixext 16 (0xD4..0xD8)
  16147. @note Any MessagePack output created @ref to_msgpack can be successfully
  16148. parsed by @ref from_msgpack.
  16149. @note If NaN or Infinity are stored inside a JSON number, they are
  16150. serialized properly. This behavior differs from the @ref dump()
  16151. function which serializes NaN or Infinity to `null`.
  16152. @param[in] j JSON value to serialize
  16153. @return MessagePack serialization as byte vector
  16154. @complexity Linear in the size of the JSON value @a j.
  16155. @liveexample{The example shows the serialization of a JSON value to a byte
  16156. vector in MessagePack format.,to_msgpack}
  16157. @sa http://msgpack.org
  16158. @sa @ref from_msgpack for the analogous deserialization
  16159. @sa @ref to_cbor(const basic_json& for the related CBOR format
  16160. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16161. related UBJSON format
  16162. @since version 2.0.9
  16163. */
  16164. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  16165. {
  16166. std::vector<uint8_t> result;
  16167. to_msgpack(j, result);
  16168. return result;
  16169. }
  16170. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  16171. {
  16172. binary_writer<uint8_t>(o).write_msgpack(j);
  16173. }
  16174. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  16175. {
  16176. binary_writer<char>(o).write_msgpack(j);
  16177. }
  16178. /*!
  16179. @brief create a UBJSON serialization of a given JSON value
  16180. Serializes a given JSON value @a j to a byte vector using the UBJSON
  16181. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  16182. than JSON itself, yet more efficient to parse.
  16183. The library uses the following mapping from JSON values types to
  16184. UBJSON types according to the UBJSON specification:
  16185. JSON value type | value/range | UBJSON type | marker
  16186. --------------- | --------------------------------- | ----------- | ------
  16187. null | `null` | null | `Z`
  16188. boolean | `true` | true | `T`
  16189. boolean | `false` | false | `F`
  16190. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  16191. number_integer | -2147483648..-32769 | int32 | `l`
  16192. number_integer | -32768..-129 | int16 | `I`
  16193. number_integer | -128..127 | int8 | `i`
  16194. number_integer | 128..255 | uint8 | `U`
  16195. number_integer | 256..32767 | int16 | `I`
  16196. number_integer | 32768..2147483647 | int32 | `l`
  16197. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  16198. number_unsigned | 0..127 | int8 | `i`
  16199. number_unsigned | 128..255 | uint8 | `U`
  16200. number_unsigned | 256..32767 | int16 | `I`
  16201. number_unsigned | 32768..2147483647 | int32 | `l`
  16202. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  16203. number_float | *any value* | float64 | `D`
  16204. string | *with shortest length indicator* | string | `S`
  16205. array | *see notes on optimized format* | array | `[`
  16206. object | *see notes on optimized format* | map | `{`
  16207. @note The mapping is **complete** in the sense that any JSON value type
  16208. can be converted to a UBJSON value.
  16209. @note The following values can **not** be converted to a UBJSON value:
  16210. - strings with more than 9223372036854775807 bytes (theoretical)
  16211. - unsigned integer numbers above 9223372036854775807
  16212. @note The following markers are not used in the conversion:
  16213. - `Z`: no-op values are not created.
  16214. - `C`: single-byte strings are serialized with `S` markers.
  16215. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  16216. by @ref from_ubjson.
  16217. @note If NaN or Infinity are stored inside a JSON number, they are
  16218. serialized properly. This behavior differs from the @ref dump()
  16219. function which serializes NaN or Infinity to `null`.
  16220. @note The optimized formats for containers are supported: Parameter
  16221. @a use_size adds size information to the beginning of a container and
  16222. removes the closing marker. Parameter @a use_type further checks
  16223. whether all elements of a container have the same type and adds the
  16224. type marker to the beginning of the container. The @a use_type
  16225. parameter must only be used together with @a use_size = true. Note
  16226. that @a use_size = true alone may result in larger representations -
  16227. the benefit of this parameter is that the receiving side is
  16228. immediately informed on the number of elements of the container.
  16229. @param[in] j JSON value to serialize
  16230. @param[in] use_size whether to add size annotations to container types
  16231. @param[in] use_type whether to add type annotations to container types
  16232. (must be combined with @a use_size = true)
  16233. @return UBJSON serialization as byte vector
  16234. @complexity Linear in the size of the JSON value @a j.
  16235. @liveexample{The example shows the serialization of a JSON value to a byte
  16236. vector in UBJSON format.,to_ubjson}
  16237. @sa http://ubjson.org
  16238. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16239. analogous deserialization
  16240. @sa @ref to_cbor(const basic_json& for the related CBOR format
  16241. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16242. @since version 3.1.0
  16243. */
  16244. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  16245. const bool use_size = false,
  16246. const bool use_type = false)
  16247. {
  16248. std::vector<uint8_t> result;
  16249. to_ubjson(j, result, use_size, use_type);
  16250. return result;
  16251. }
  16252. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  16253. const bool use_size = false, const bool use_type = false)
  16254. {
  16255. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  16256. }
  16257. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  16258. const bool use_size = false, const bool use_type = false)
  16259. {
  16260. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  16261. }
  16262. /*!
  16263. @brief Serializes the given JSON object `j` to BSON and returns a vector
  16264. containing the corresponding BSON-representation.
  16265. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
  16266. stored as a single entity (a so-called document).
  16267. The library uses the following mapping from JSON values types to BSON types:
  16268. JSON value type | value/range | BSON type | marker
  16269. --------------- | --------------------------------- | ----------- | ------
  16270. null | `null` | null | 0x0A
  16271. boolean | `true`, `false` | boolean | 0x08
  16272. number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
  16273. number_integer | -2147483648..2147483647 | int32 | 0x10
  16274. number_integer | 2147483648..9223372036854775807 | int64 | 0x12
  16275. number_unsigned | 0..2147483647 | int32 | 0x10
  16276. number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
  16277. number_unsigned | 9223372036854775808..18446744073709551615| -- | --
  16278. number_float | *any value* | double | 0x01
  16279. string | *any value* | string | 0x02
  16280. array | *any value* | document | 0x04
  16281. object | *any value* | document | 0x03
  16282. @warning The mapping is **incomplete**, since only JSON-objects (and things
  16283. contained therein) can be serialized to BSON.
  16284. Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
  16285. and the keys may not contain U+0000, since they are serialized a
  16286. zero-terminated c-strings.
  16287. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
  16288. @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
  16289. @throw type_error.317 if `!j.is_object()`
  16290. @pre The input `j` is required to be an object: `j.is_object() == true`.
  16291. @note Any BSON output created via @ref to_bson can be successfully parsed
  16292. by @ref from_bson.
  16293. @param[in] j JSON value to serialize
  16294. @return BSON serialization as byte vector
  16295. @complexity Linear in the size of the JSON value @a j.
  16296. @liveexample{The example shows the serialization of a JSON value to a byte
  16297. vector in BSON format.,to_bson}
  16298. @sa http://bsonspec.org/spec.html
  16299. @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
  16300. analogous deserialization
  16301. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16302. related UBJSON format
  16303. @sa @ref to_cbor(const basic_json&) for the related CBOR format
  16304. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  16305. */
  16306. static std::vector<uint8_t> to_bson(const basic_json& j)
  16307. {
  16308. std::vector<uint8_t> result;
  16309. to_bson(j, result);
  16310. return result;
  16311. }
  16312. /*!
  16313. @brief Serializes the given JSON object `j` to BSON and forwards the
  16314. corresponding BSON-representation to the given output_adapter `o`.
  16315. @param j The JSON object to convert to BSON.
  16316. @param o The output adapter that receives the binary BSON representation.
  16317. @pre The input `j` shall be an object: `j.is_object() == true`
  16318. @sa @ref to_bson(const basic_json&)
  16319. */
  16320. static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
  16321. {
  16322. binary_writer<uint8_t>(o).write_bson(j);
  16323. }
  16324. /*!
  16325. @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
  16326. */
  16327. static void to_bson(const basic_json& j, detail::output_adapter<char> o)
  16328. {
  16329. binary_writer<char>(o).write_bson(j);
  16330. }
  16331. /*!
  16332. @brief create a JSON value from an input in CBOR format
  16333. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  16334. Binary Object Representation) serialization format.
  16335. The library maps CBOR types to JSON value types as follows:
  16336. CBOR type | JSON value type | first byte
  16337. ---------------------- | --------------- | ----------
  16338. Integer | number_unsigned | 0x00..0x17
  16339. Unsigned integer | number_unsigned | 0x18
  16340. Unsigned integer | number_unsigned | 0x19
  16341. Unsigned integer | number_unsigned | 0x1A
  16342. Unsigned integer | number_unsigned | 0x1B
  16343. Negative integer | number_integer | 0x20..0x37
  16344. Negative integer | number_integer | 0x38
  16345. Negative integer | number_integer | 0x39
  16346. Negative integer | number_integer | 0x3A
  16347. Negative integer | number_integer | 0x3B
  16348. Negative integer | number_integer | 0x40..0x57
  16349. UTF-8 string | string | 0x60..0x77
  16350. UTF-8 string | string | 0x78
  16351. UTF-8 string | string | 0x79
  16352. UTF-8 string | string | 0x7A
  16353. UTF-8 string | string | 0x7B
  16354. UTF-8 string | string | 0x7F
  16355. array | array | 0x80..0x97
  16356. array | array | 0x98
  16357. array | array | 0x99
  16358. array | array | 0x9A
  16359. array | array | 0x9B
  16360. array | array | 0x9F
  16361. map | object | 0xA0..0xB7
  16362. map | object | 0xB8
  16363. map | object | 0xB9
  16364. map | object | 0xBA
  16365. map | object | 0xBB
  16366. map | object | 0xBF
  16367. False | `false` | 0xF4
  16368. True | `true` | 0xF5
  16369. Null | `null` | 0xF6
  16370. Half-Precision Float | number_float | 0xF9
  16371. Single-Precision Float | number_float | 0xFA
  16372. Double-Precision Float | number_float | 0xFB
  16373. @warning The mapping is **incomplete** in the sense that not all CBOR
  16374. types can be converted to a JSON value. The following CBOR types
  16375. are not supported and will yield parse errors (parse_error.112):
  16376. - byte strings (0x40..0x5F)
  16377. - date/time (0xC0..0xC1)
  16378. - bignum (0xC2..0xC3)
  16379. - decimal fraction (0xC4)
  16380. - bigfloat (0xC5)
  16381. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  16382. - expected conversions (0xD5..0xD7)
  16383. - simple values (0xE0..0xF3, 0xF8)
  16384. - undefined (0xF7)
  16385. @warning CBOR allows map keys of any type, whereas JSON only allows
  16386. strings as keys in object values. Therefore, CBOR maps with keys
  16387. other than UTF-8 strings are rejected (parse_error.113).
  16388. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  16389. @ref from_cbor.
  16390. @param[in] i an input in CBOR format convertible to an input adapter
  16391. @param[in] strict whether to expect the input to be consumed until EOF
  16392. (true by default)
  16393. @param[in] allow_exceptions whether to throw exceptions in case of a
  16394. parse error (optional, true by default)
  16395. @return deserialized JSON value; in case of a parse error and
  16396. @a allow_exceptions set to `false`, the return value will be
  16397. value_t::discarded.
  16398. @throw parse_error.110 if the given input ends prematurely or the end of
  16399. file was not reached when @a strict was set to true
  16400. @throw parse_error.112 if unsupported features from CBOR were
  16401. used in the given input @a v or if the input is not valid CBOR
  16402. @throw parse_error.113 if a string was expected as map key, but not found
  16403. @complexity Linear in the size of the input @a i.
  16404. @liveexample{The example shows the deserialization of a byte vector in CBOR
  16405. format to a JSON value.,from_cbor}
  16406. @sa http://cbor.io
  16407. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  16408. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
  16409. related MessagePack format
  16410. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16411. related UBJSON format
  16412. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16413. consume input adapters, removed start_index parameter, and added
  16414. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16415. since 3.2.0
  16416. */
  16417. JSON_NODISCARD
  16418. static basic_json from_cbor(detail::input_adapter&& i,
  16419. const bool strict = true,
  16420. const bool allow_exceptions = true)
  16421. {
  16422. basic_json result;
  16423. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16424. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  16425. return res ? result : basic_json(value_t::discarded);
  16426. }
  16427. /*!
  16428. @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
  16429. */
  16430. template<typename A1, typename A2,
  16431. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16432. JSON_NODISCARD
  16433. static basic_json from_cbor(A1 && a1, A2 && a2,
  16434. const bool strict = true,
  16435. const bool allow_exceptions = true)
  16436. {
  16437. basic_json result;
  16438. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16439. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  16440. return res ? result : basic_json(value_t::discarded);
  16441. }
  16442. /*!
  16443. @brief create a JSON value from an input in MessagePack format
  16444. Deserializes a given input @a i to a JSON value using the MessagePack
  16445. serialization format.
  16446. The library maps MessagePack types to JSON value types as follows:
  16447. MessagePack type | JSON value type | first byte
  16448. ---------------- | --------------- | ----------
  16449. positive fixint | number_unsigned | 0x00..0x7F
  16450. fixmap | object | 0x80..0x8F
  16451. fixarray | array | 0x90..0x9F
  16452. fixstr | string | 0xA0..0xBF
  16453. nil | `null` | 0xC0
  16454. false | `false` | 0xC2
  16455. true | `true` | 0xC3
  16456. float 32 | number_float | 0xCA
  16457. float 64 | number_float | 0xCB
  16458. uint 8 | number_unsigned | 0xCC
  16459. uint 16 | number_unsigned | 0xCD
  16460. uint 32 | number_unsigned | 0xCE
  16461. uint 64 | number_unsigned | 0xCF
  16462. int 8 | number_integer | 0xD0
  16463. int 16 | number_integer | 0xD1
  16464. int 32 | number_integer | 0xD2
  16465. int 64 | number_integer | 0xD3
  16466. str 8 | string | 0xD9
  16467. str 16 | string | 0xDA
  16468. str 32 | string | 0xDB
  16469. array 16 | array | 0xDC
  16470. array 32 | array | 0xDD
  16471. map 16 | object | 0xDE
  16472. map 32 | object | 0xDF
  16473. negative fixint | number_integer | 0xE0-0xFF
  16474. @warning The mapping is **incomplete** in the sense that not all
  16475. MessagePack types can be converted to a JSON value. The following
  16476. MessagePack types are not supported and will yield parse errors:
  16477. - bin 8 - bin 32 (0xC4..0xC6)
  16478. - ext 8 - ext 32 (0xC7..0xC9)
  16479. - fixext 1 - fixext 16 (0xD4..0xD8)
  16480. @note Any MessagePack output created @ref to_msgpack can be successfully
  16481. parsed by @ref from_msgpack.
  16482. @param[in] i an input in MessagePack format convertible to an input
  16483. adapter
  16484. @param[in] strict whether to expect the input to be consumed until EOF
  16485. (true by default)
  16486. @param[in] allow_exceptions whether to throw exceptions in case of a
  16487. parse error (optional, true by default)
  16488. @return deserialized JSON value; in case of a parse error and
  16489. @a allow_exceptions set to `false`, the return value will be
  16490. value_t::discarded.
  16491. @throw parse_error.110 if the given input ends prematurely or the end of
  16492. file was not reached when @a strict was set to true
  16493. @throw parse_error.112 if unsupported features from MessagePack were
  16494. used in the given input @a i or if the input is not valid MessagePack
  16495. @throw parse_error.113 if a string was expected as map key, but not found
  16496. @complexity Linear in the size of the input @a i.
  16497. @liveexample{The example shows the deserialization of a byte vector in
  16498. MessagePack format to a JSON value.,from_msgpack}
  16499. @sa http://msgpack.org
  16500. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  16501. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16502. related CBOR format
  16503. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
  16504. the related UBJSON format
  16505. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16506. the related BSON format
  16507. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  16508. consume input adapters, removed start_index parameter, and added
  16509. @a strict parameter since 3.0.0; added @a allow_exceptions parameter
  16510. since 3.2.0
  16511. */
  16512. JSON_NODISCARD
  16513. static basic_json from_msgpack(detail::input_adapter&& i,
  16514. const bool strict = true,
  16515. const bool allow_exceptions = true)
  16516. {
  16517. basic_json result;
  16518. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16519. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  16520. return res ? result : basic_json(value_t::discarded);
  16521. }
  16522. /*!
  16523. @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
  16524. */
  16525. template<typename A1, typename A2,
  16526. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16527. JSON_NODISCARD
  16528. static basic_json from_msgpack(A1 && a1, A2 && a2,
  16529. const bool strict = true,
  16530. const bool allow_exceptions = true)
  16531. {
  16532. basic_json result;
  16533. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16534. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  16535. return res ? result : basic_json(value_t::discarded);
  16536. }
  16537. /*!
  16538. @brief create a JSON value from an input in UBJSON format
  16539. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  16540. Binary JSON) serialization format.
  16541. The library maps UBJSON types to JSON value types as follows:
  16542. UBJSON type | JSON value type | marker
  16543. ----------- | --------------------------------------- | ------
  16544. no-op | *no value, next value is read* | `N`
  16545. null | `null` | `Z`
  16546. false | `false` | `F`
  16547. true | `true` | `T`
  16548. float32 | number_float | `d`
  16549. float64 | number_float | `D`
  16550. uint8 | number_unsigned | `U`
  16551. int8 | number_integer | `i`
  16552. int16 | number_integer | `I`
  16553. int32 | number_integer | `l`
  16554. int64 | number_integer | `L`
  16555. string | string | `S`
  16556. char | string | `C`
  16557. array | array (optimized values are supported) | `[`
  16558. object | object (optimized values are supported) | `{`
  16559. @note The mapping is **complete** in the sense that any UBJSON value can
  16560. be converted to a JSON value.
  16561. @param[in] i an input in UBJSON format convertible to an input adapter
  16562. @param[in] strict whether to expect the input to be consumed until EOF
  16563. (true by default)
  16564. @param[in] allow_exceptions whether to throw exceptions in case of a
  16565. parse error (optional, true by default)
  16566. @return deserialized JSON value; in case of a parse error and
  16567. @a allow_exceptions set to `false`, the return value will be
  16568. value_t::discarded.
  16569. @throw parse_error.110 if the given input ends prematurely or the end of
  16570. file was not reached when @a strict was set to true
  16571. @throw parse_error.112 if a parse error occurs
  16572. @throw parse_error.113 if a string could not be parsed successfully
  16573. @complexity Linear in the size of the input @a i.
  16574. @liveexample{The example shows the deserialization of a byte vector in
  16575. UBJSON format to a JSON value.,from_ubjson}
  16576. @sa http://ubjson.org
  16577. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  16578. analogous serialization
  16579. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16580. related CBOR format
  16581. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16582. the related MessagePack format
  16583. @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
  16584. the related BSON format
  16585. @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
  16586. */
  16587. JSON_NODISCARD
  16588. static basic_json from_ubjson(detail::input_adapter&& i,
  16589. const bool strict = true,
  16590. const bool allow_exceptions = true)
  16591. {
  16592. basic_json result;
  16593. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16594. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  16595. return res ? result : basic_json(value_t::discarded);
  16596. }
  16597. /*!
  16598. @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
  16599. */
  16600. template<typename A1, typename A2,
  16601. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16602. JSON_NODISCARD
  16603. static basic_json from_ubjson(A1 && a1, A2 && a2,
  16604. const bool strict = true,
  16605. const bool allow_exceptions = true)
  16606. {
  16607. basic_json result;
  16608. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16609. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  16610. return res ? result : basic_json(value_t::discarded);
  16611. }
  16612. /*!
  16613. @brief Create a JSON value from an input in BSON format
  16614. Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
  16615. serialization format.
  16616. The library maps BSON record types to JSON value types as follows:
  16617. BSON type | BSON marker byte | JSON value type
  16618. --------------- | ---------------- | ---------------------------
  16619. double | 0x01 | number_float
  16620. string | 0x02 | string
  16621. document | 0x03 | object
  16622. array | 0x04 | array
  16623. binary | 0x05 | still unsupported
  16624. undefined | 0x06 | still unsupported
  16625. ObjectId | 0x07 | still unsupported
  16626. boolean | 0x08 | boolean
  16627. UTC Date-Time | 0x09 | still unsupported
  16628. null | 0x0A | null
  16629. Regular Expr. | 0x0B | still unsupported
  16630. DB Pointer | 0x0C | still unsupported
  16631. JavaScript Code | 0x0D | still unsupported
  16632. Symbol | 0x0E | still unsupported
  16633. JavaScript Code | 0x0F | still unsupported
  16634. int32 | 0x10 | number_integer
  16635. Timestamp | 0x11 | still unsupported
  16636. 128-bit decimal float | 0x13 | still unsupported
  16637. Max Key | 0x7F | still unsupported
  16638. Min Key | 0xFF | still unsupported
  16639. @warning The mapping is **incomplete**. The unsupported mappings
  16640. are indicated in the table above.
  16641. @param[in] i an input in BSON format convertible to an input adapter
  16642. @param[in] strict whether to expect the input to be consumed until EOF
  16643. (true by default)
  16644. @param[in] allow_exceptions whether to throw exceptions in case of a
  16645. parse error (optional, true by default)
  16646. @return deserialized JSON value; in case of a parse error and
  16647. @a allow_exceptions set to `false`, the return value will be
  16648. value_t::discarded.
  16649. @throw parse_error.114 if an unsupported BSON record type is encountered
  16650. @complexity Linear in the size of the input @a i.
  16651. @liveexample{The example shows the deserialization of a byte vector in
  16652. BSON format to a JSON value.,from_bson}
  16653. @sa http://bsonspec.org/spec.html
  16654. @sa @ref to_bson(const basic_json&) for the analogous serialization
  16655. @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
  16656. related CBOR format
  16657. @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
  16658. the related MessagePack format
  16659. @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
  16660. related UBJSON format
  16661. */
  16662. JSON_NODISCARD
  16663. static basic_json from_bson(detail::input_adapter&& i,
  16664. const bool strict = true,
  16665. const bool allow_exceptions = true)
  16666. {
  16667. basic_json result;
  16668. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16669. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
  16670. return res ? result : basic_json(value_t::discarded);
  16671. }
  16672. /*!
  16673. @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
  16674. */
  16675. template<typename A1, typename A2,
  16676. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  16677. JSON_NODISCARD
  16678. static basic_json from_bson(A1 && a1, A2 && a2,
  16679. const bool strict = true,
  16680. const bool allow_exceptions = true)
  16681. {
  16682. basic_json result;
  16683. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  16684. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
  16685. return res ? result : basic_json(value_t::discarded);
  16686. }
  16687. /// @}
  16688. //////////////////////////
  16689. // JSON Pointer support //
  16690. //////////////////////////
  16691. /// @name JSON Pointer functions
  16692. /// @{
  16693. /*!
  16694. @brief access specified element via JSON Pointer
  16695. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16696. No bound checking is performed. Similar to @ref operator[](const typename
  16697. object_t::key_type&), `null` values are created in arrays and objects if
  16698. necessary.
  16699. In particular:
  16700. - If the JSON pointer points to an object key that does not exist, it
  16701. is created an filled with a `null` value before a reference to it
  16702. is returned.
  16703. - If the JSON pointer points to an array index that does not exist, it
  16704. is created an filled with a `null` value before a reference to it
  16705. is returned. All indices between the current maximum and the given
  16706. index are also filled with `null`.
  16707. - The special value `-` is treated as a synonym for the index past the
  16708. end.
  16709. @param[in] ptr a JSON pointer
  16710. @return reference to the element pointed to by @a ptr
  16711. @complexity Constant.
  16712. @throw parse_error.106 if an array index begins with '0'
  16713. @throw parse_error.109 if an array index was not a number
  16714. @throw out_of_range.404 if the JSON pointer can not be resolved
  16715. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  16716. @since version 2.0.0
  16717. */
  16718. reference operator[](const json_pointer& ptr)
  16719. {
  16720. return ptr.get_unchecked(this);
  16721. }
  16722. /*!
  16723. @brief access specified element via JSON Pointer
  16724. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  16725. No bound checking is performed. The function does not change the JSON
  16726. value; no `null` values are created. In particular, the the special value
  16727. `-` yields an exception.
  16728. @param[in] ptr JSON pointer to the desired element
  16729. @return const reference to the element pointed to by @a ptr
  16730. @complexity Constant.
  16731. @throw parse_error.106 if an array index begins with '0'
  16732. @throw parse_error.109 if an array index was not a number
  16733. @throw out_of_range.402 if the array index '-' is used
  16734. @throw out_of_range.404 if the JSON pointer can not be resolved
  16735. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  16736. @since version 2.0.0
  16737. */
  16738. const_reference operator[](const json_pointer& ptr) const
  16739. {
  16740. return ptr.get_unchecked(this);
  16741. }
  16742. /*!
  16743. @brief access specified element via JSON Pointer
  16744. Returns a reference to the element at with specified JSON pointer @a ptr,
  16745. with bounds checking.
  16746. @param[in] ptr JSON pointer to the desired element
  16747. @return reference to the element pointed to by @a ptr
  16748. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16749. begins with '0'. See example below.
  16750. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16751. is not a number. See example below.
  16752. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16753. is out of range. See example below.
  16754. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16755. pointer @a ptr. As `at` provides checked access (and no elements are
  16756. implicitly inserted), the index '-' is always invalid. See example below.
  16757. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16758. which cannot be found. See example below.
  16759. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16760. See example below.
  16761. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16762. changes in the JSON value.
  16763. @complexity Constant.
  16764. @since version 2.0.0
  16765. @liveexample{The behavior is shown in the example.,at_json_pointer}
  16766. */
  16767. reference at(const json_pointer& ptr)
  16768. {
  16769. return ptr.get_checked(this);
  16770. }
  16771. /*!
  16772. @brief access specified element via JSON Pointer
  16773. Returns a const reference to the element at with specified JSON pointer @a
  16774. ptr, with bounds checking.
  16775. @param[in] ptr JSON pointer to the desired element
  16776. @return reference to the element pointed to by @a ptr
  16777. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  16778. begins with '0'. See example below.
  16779. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  16780. is not a number. See example below.
  16781. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  16782. is out of range. See example below.
  16783. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  16784. pointer @a ptr. As `at` provides checked access (and no elements are
  16785. implicitly inserted), the index '-' is always invalid. See example below.
  16786. @throw out_of_range.403 if the JSON pointer describes a key of an object
  16787. which cannot be found. See example below.
  16788. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  16789. See example below.
  16790. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  16791. changes in the JSON value.
  16792. @complexity Constant.
  16793. @since version 2.0.0
  16794. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  16795. */
  16796. const_reference at(const json_pointer& ptr) const
  16797. {
  16798. return ptr.get_checked(this);
  16799. }
  16800. /*!
  16801. @brief return flattened JSON value
  16802. The function creates a JSON object whose keys are JSON pointers (see [RFC
  16803. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  16804. primitive. The original JSON value can be restored using the @ref
  16805. unflatten() function.
  16806. @return an object that maps JSON pointers to primitive values
  16807. @note Empty objects and arrays are flattened to `null` and will not be
  16808. reconstructed correctly by the @ref unflatten() function.
  16809. @complexity Linear in the size the JSON value.
  16810. @liveexample{The following code shows how a JSON object is flattened to an
  16811. object whose keys consist of JSON pointers.,flatten}
  16812. @sa @ref unflatten() for the reverse function
  16813. @since version 2.0.0
  16814. */
  16815. basic_json flatten() const
  16816. {
  16817. basic_json result(value_t::object);
  16818. json_pointer::flatten("", *this, result);
  16819. return result;
  16820. }
  16821. /*!
  16822. @brief unflatten a previously flattened JSON value
  16823. The function restores the arbitrary nesting of a JSON value that has been
  16824. flattened before using the @ref flatten() function. The JSON value must
  16825. meet certain constraints:
  16826. 1. The value must be an object.
  16827. 2. The keys must be JSON pointers (see
  16828. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  16829. 3. The mapped values must be primitive JSON types.
  16830. @return the original JSON from a flattened version
  16831. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  16832. values and can not unflattened to their original type. Apart from
  16833. this example, for a JSON value `j`, the following is always true:
  16834. `j == j.flatten().unflatten()`.
  16835. @complexity Linear in the size the JSON value.
  16836. @throw type_error.314 if value is not an object
  16837. @throw type_error.315 if object values are not primitive
  16838. @liveexample{The following code shows how a flattened JSON object is
  16839. unflattened into the original nested JSON object.,unflatten}
  16840. @sa @ref flatten() for the reverse function
  16841. @since version 2.0.0
  16842. */
  16843. basic_json unflatten() const
  16844. {
  16845. return json_pointer::unflatten(*this);
  16846. }
  16847. /// @}
  16848. //////////////////////////
  16849. // JSON Patch functions //
  16850. //////////////////////////
  16851. /// @name JSON Patch functions
  16852. /// @{
  16853. /*!
  16854. @brief applies a JSON patch
  16855. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  16856. expressing a sequence of operations to apply to a JSON) document. With
  16857. this function, a JSON Patch is applied to the current JSON value by
  16858. executing all operations from the patch.
  16859. @param[in] json_patch JSON patch document
  16860. @return patched document
  16861. @note The application of a patch is atomic: Either all operations succeed
  16862. and the patched document is returned or an exception is thrown. In
  16863. any case, the original value is not changed: the patch is applied
  16864. to a copy of the value.
  16865. @throw parse_error.104 if the JSON patch does not consist of an array of
  16866. objects
  16867. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  16868. attributes are missing); example: `"operation add must have member path"`
  16869. @throw out_of_range.401 if an array index is out of range.
  16870. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  16871. resolved successfully in the current JSON value; example: `"key baz not
  16872. found"`
  16873. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  16874. "move")
  16875. @throw other_error.501 if "test" operation was unsuccessful
  16876. @complexity Linear in the size of the JSON value and the length of the
  16877. JSON patch. As usually only a fraction of the JSON value is affected by
  16878. the patch, the complexity can usually be neglected.
  16879. @liveexample{The following code shows how a JSON patch is applied to a
  16880. value.,patch}
  16881. @sa @ref diff -- create a JSON patch by comparing two JSON values
  16882. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  16883. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  16884. @since version 2.0.0
  16885. */
  16886. basic_json patch(const basic_json& json_patch) const
  16887. {
  16888. // make a working copy to apply the patch to
  16889. basic_json result = *this;
  16890. // the valid JSON Patch operations
  16891. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  16892. const auto get_op = [](const std::string & op)
  16893. {
  16894. if (op == "add")
  16895. {
  16896. return patch_operations::add;
  16897. }
  16898. if (op == "remove")
  16899. {
  16900. return patch_operations::remove;
  16901. }
  16902. if (op == "replace")
  16903. {
  16904. return patch_operations::replace;
  16905. }
  16906. if (op == "move")
  16907. {
  16908. return patch_operations::move;
  16909. }
  16910. if (op == "copy")
  16911. {
  16912. return patch_operations::copy;
  16913. }
  16914. if (op == "test")
  16915. {
  16916. return patch_operations::test;
  16917. }
  16918. return patch_operations::invalid;
  16919. };
  16920. // wrapper for "add" operation; add value at ptr
  16921. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  16922. {
  16923. // adding to the root of the target document means replacing it
  16924. if (ptr.empty())
  16925. {
  16926. result = val;
  16927. return;
  16928. }
  16929. // make sure the top element of the pointer exists
  16930. json_pointer top_pointer = ptr.top();
  16931. if (top_pointer != ptr)
  16932. {
  16933. result.at(top_pointer);
  16934. }
  16935. // get reference to parent of JSON pointer ptr
  16936. const auto last_path = ptr.back();
  16937. ptr.pop_back();
  16938. basic_json& parent = result[ptr];
  16939. switch (parent.m_type)
  16940. {
  16941. case value_t::null:
  16942. case value_t::object:
  16943. {
  16944. // use operator[] to add value
  16945. parent[last_path] = val;
  16946. break;
  16947. }
  16948. case value_t::array:
  16949. {
  16950. if (last_path == "-")
  16951. {
  16952. // special case: append to back
  16953. parent.push_back(val);
  16954. }
  16955. else
  16956. {
  16957. const auto idx = json_pointer::array_index(last_path);
  16958. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  16959. {
  16960. // avoid undefined behavior
  16961. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  16962. }
  16963. // default case: insert add offset
  16964. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  16965. }
  16966. break;
  16967. }
  16968. // if there exists a parent it cannot be primitive
  16969. default: // LCOV_EXCL_LINE
  16970. assert(false); // LCOV_EXCL_LINE
  16971. }
  16972. };
  16973. // wrapper for "remove" operation; remove value at ptr
  16974. const auto operation_remove = [&result](json_pointer & ptr)
  16975. {
  16976. // get reference to parent of JSON pointer ptr
  16977. const auto last_path = ptr.back();
  16978. ptr.pop_back();
  16979. basic_json& parent = result.at(ptr);
  16980. // remove child
  16981. if (parent.is_object())
  16982. {
  16983. // perform range check
  16984. auto it = parent.find(last_path);
  16985. if (JSON_LIKELY(it != parent.end()))
  16986. {
  16987. parent.erase(it);
  16988. }
  16989. else
  16990. {
  16991. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  16992. }
  16993. }
  16994. else if (parent.is_array())
  16995. {
  16996. // note erase performs range check
  16997. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  16998. }
  16999. };
  17000. // type check: top level value must be an array
  17001. if (JSON_UNLIKELY(not json_patch.is_array()))
  17002. {
  17003. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  17004. }
  17005. // iterate and apply the operations
  17006. for (const auto& val : json_patch)
  17007. {
  17008. // wrapper to get a value for an operation
  17009. const auto get_value = [&val](const std::string & op,
  17010. const std::string & member,
  17011. bool string_type) -> basic_json &
  17012. {
  17013. // find value
  17014. auto it = val.m_value.object->find(member);
  17015. // context-sensitive error message
  17016. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  17017. // check if desired value is present
  17018. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  17019. {
  17020. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  17021. }
  17022. // check if result is of type string
  17023. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  17024. {
  17025. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  17026. }
  17027. // no error: return value
  17028. return it->second;
  17029. };
  17030. // type check: every element of the array must be an object
  17031. if (JSON_UNLIKELY(not val.is_object()))
  17032. {
  17033. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  17034. }
  17035. // collect mandatory members
  17036. const std::string op = get_value("op", "op", true);
  17037. const std::string path = get_value(op, "path", true);
  17038. json_pointer ptr(path);
  17039. switch (get_op(op))
  17040. {
  17041. case patch_operations::add:
  17042. {
  17043. operation_add(ptr, get_value("add", "value", false));
  17044. break;
  17045. }
  17046. case patch_operations::remove:
  17047. {
  17048. operation_remove(ptr);
  17049. break;
  17050. }
  17051. case patch_operations::replace:
  17052. {
  17053. // the "path" location must exist - use at()
  17054. result.at(ptr) = get_value("replace", "value", false);
  17055. break;
  17056. }
  17057. case patch_operations::move:
  17058. {
  17059. const std::string from_path = get_value("move", "from", true);
  17060. json_pointer from_ptr(from_path);
  17061. // the "from" location must exist - use at()
  17062. basic_json v = result.at(from_ptr);
  17063. // The move operation is functionally identical to a
  17064. // "remove" operation on the "from" location, followed
  17065. // immediately by an "add" operation at the target
  17066. // location with the value that was just removed.
  17067. operation_remove(from_ptr);
  17068. operation_add(ptr, v);
  17069. break;
  17070. }
  17071. case patch_operations::copy:
  17072. {
  17073. const std::string from_path = get_value("copy", "from", true);
  17074. const json_pointer from_ptr(from_path);
  17075. // the "from" location must exist - use at()
  17076. basic_json v = result.at(from_ptr);
  17077. // The copy is functionally identical to an "add"
  17078. // operation at the target location using the value
  17079. // specified in the "from" member.
  17080. operation_add(ptr, v);
  17081. break;
  17082. }
  17083. case patch_operations::test:
  17084. {
  17085. bool success = false;
  17086. JSON_TRY
  17087. {
  17088. // check if "value" matches the one at "path"
  17089. // the "path" location must exist - use at()
  17090. success = (result.at(ptr) == get_value("test", "value", false));
  17091. }
  17092. JSON_INTERNAL_CATCH (out_of_range&)
  17093. {
  17094. // ignore out of range errors: success remains false
  17095. }
  17096. // throw an exception if test fails
  17097. if (JSON_UNLIKELY(not success))
  17098. {
  17099. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  17100. }
  17101. break;
  17102. }
  17103. default:
  17104. {
  17105. // op must be "add", "remove", "replace", "move", "copy", or
  17106. // "test"
  17107. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  17108. }
  17109. }
  17110. }
  17111. return result;
  17112. }
  17113. /*!
  17114. @brief creates a diff as a JSON patch
  17115. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  17116. be changed into the value @a target by calling @ref patch function.
  17117. @invariant For two JSON values @a source and @a target, the following code
  17118. yields always `true`:
  17119. @code {.cpp}
  17120. source.patch(diff(source, target)) == target;
  17121. @endcode
  17122. @note Currently, only `remove`, `add`, and `replace` operations are
  17123. generated.
  17124. @param[in] source JSON value to compare from
  17125. @param[in] target JSON value to compare against
  17126. @param[in] path helper value to create JSON pointers
  17127. @return a JSON patch to convert the @a source to @a target
  17128. @complexity Linear in the lengths of @a source and @a target.
  17129. @liveexample{The following code shows how a JSON patch is created as a
  17130. diff for two JSON values.,diff}
  17131. @sa @ref patch -- apply a JSON patch
  17132. @sa @ref merge_patch -- apply a JSON Merge Patch
  17133. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  17134. @since version 2.0.0
  17135. */
  17136. JSON_NODISCARD
  17137. static basic_json diff(const basic_json& source, const basic_json& target,
  17138. const std::string& path = "")
  17139. {
  17140. // the patch
  17141. basic_json result(value_t::array);
  17142. // if the values are the same, return empty patch
  17143. if (source == target)
  17144. {
  17145. return result;
  17146. }
  17147. if (source.type() != target.type())
  17148. {
  17149. // different types: replace value
  17150. result.push_back(
  17151. {
  17152. {"op", "replace"}, {"path", path}, {"value", target}
  17153. });
  17154. return result;
  17155. }
  17156. switch (source.type())
  17157. {
  17158. case value_t::array:
  17159. {
  17160. // first pass: traverse common elements
  17161. std::size_t i = 0;
  17162. while (i < source.size() and i < target.size())
  17163. {
  17164. // recursive call to compare array values at index i
  17165. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  17166. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  17167. ++i;
  17168. }
  17169. // i now reached the end of at least one array
  17170. // in a second pass, traverse the remaining elements
  17171. // remove my remaining elements
  17172. const auto end_index = static_cast<difference_type>(result.size());
  17173. while (i < source.size())
  17174. {
  17175. // add operations in reverse order to avoid invalid
  17176. // indices
  17177. result.insert(result.begin() + end_index, object(
  17178. {
  17179. {"op", "remove"},
  17180. {"path", path + "/" + std::to_string(i)}
  17181. }));
  17182. ++i;
  17183. }
  17184. // add other remaining elements
  17185. while (i < target.size())
  17186. {
  17187. result.push_back(
  17188. {
  17189. {"op", "add"},
  17190. {"path", path + "/" + std::to_string(i)},
  17191. {"value", target[i]}
  17192. });
  17193. ++i;
  17194. }
  17195. break;
  17196. }
  17197. case value_t::object:
  17198. {
  17199. // first pass: traverse this object's elements
  17200. for (auto it = source.cbegin(); it != source.cend(); ++it)
  17201. {
  17202. // escape the key name to be used in a JSON patch
  17203. const auto key = json_pointer::escape(it.key());
  17204. if (target.find(it.key()) != target.end())
  17205. {
  17206. // recursive call to compare object values at key it
  17207. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  17208. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  17209. }
  17210. else
  17211. {
  17212. // found a key that is not in o -> remove it
  17213. result.push_back(object(
  17214. {
  17215. {"op", "remove"}, {"path", path + "/" + key}
  17216. }));
  17217. }
  17218. }
  17219. // second pass: traverse other object's elements
  17220. for (auto it = target.cbegin(); it != target.cend(); ++it)
  17221. {
  17222. if (source.find(it.key()) == source.end())
  17223. {
  17224. // found a key that is not in this -> add it
  17225. const auto key = json_pointer::escape(it.key());
  17226. result.push_back(
  17227. {
  17228. {"op", "add"}, {"path", path + "/" + key},
  17229. {"value", it.value()}
  17230. });
  17231. }
  17232. }
  17233. break;
  17234. }
  17235. default:
  17236. {
  17237. // both primitive type: replace value
  17238. result.push_back(
  17239. {
  17240. {"op", "replace"}, {"path", path}, {"value", target}
  17241. });
  17242. break;
  17243. }
  17244. }
  17245. return result;
  17246. }
  17247. /// @}
  17248. ////////////////////////////////
  17249. // JSON Merge Patch functions //
  17250. ////////////////////////////////
  17251. /// @name JSON Merge Patch functions
  17252. /// @{
  17253. /*!
  17254. @brief applies a JSON Merge Patch
  17255. The merge patch format is primarily intended for use with the HTTP PATCH
  17256. method as a means of describing a set of modifications to a target
  17257. resource's content. This function applies a merge patch to the current
  17258. JSON value.
  17259. The function implements the following algorithm from Section 2 of
  17260. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  17261. ```
  17262. define MergePatch(Target, Patch):
  17263. if Patch is an Object:
  17264. if Target is not an Object:
  17265. Target = {} // Ignore the contents and set it to an empty Object
  17266. for each Name/Value pair in Patch:
  17267. if Value is null:
  17268. if Name exists in Target:
  17269. remove the Name/Value pair from Target
  17270. else:
  17271. Target[Name] = MergePatch(Target[Name], Value)
  17272. return Target
  17273. else:
  17274. return Patch
  17275. ```
  17276. Thereby, `Target` is the current object; that is, the patch is applied to
  17277. the current value.
  17278. @param[in] apply_patch the patch to apply
  17279. @complexity Linear in the lengths of @a patch.
  17280. @liveexample{The following code shows how a JSON Merge Patch is applied to
  17281. a JSON document.,merge_patch}
  17282. @sa @ref patch -- apply a JSON patch
  17283. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  17284. @since version 3.0.0
  17285. */
  17286. void merge_patch(const basic_json& apply_patch)
  17287. {
  17288. if (apply_patch.is_object())
  17289. {
  17290. if (not is_object())
  17291. {
  17292. *this = object();
  17293. }
  17294. for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
  17295. {
  17296. if (it.value().is_null())
  17297. {
  17298. erase(it.key());
  17299. }
  17300. else
  17301. {
  17302. operator[](it.key()).merge_patch(it.value());
  17303. }
  17304. }
  17305. }
  17306. else
  17307. {
  17308. *this = apply_patch;
  17309. }
  17310. }
  17311. /// @}
  17312. };
  17313. } // namespace nlohmann
  17314. ///////////////////////
  17315. // nonmember support //
  17316. ///////////////////////
  17317. // specialization of std::swap, and std::hash
  17318. namespace std
  17319. {
  17320. /// hash value for JSON objects
  17321. template<>
  17322. struct hash<nlohmann::json>
  17323. {
  17324. /*!
  17325. @brief return a hash value for a JSON object
  17326. @since version 1.0.0
  17327. */
  17328. std::size_t operator()(const nlohmann::json& j) const
  17329. {
  17330. // a naive hashing via the string representation
  17331. const auto& h = hash<nlohmann::json::string_t>();
  17332. return h(j.dump());
  17333. }
  17334. };
  17335. /// specialization for std::less<value_t>
  17336. /// @note: do not remove the space after '<',
  17337. /// see https://github.com/nlohmann/json/pull/679
  17338. template<>
  17339. struct less< ::nlohmann::detail::value_t>
  17340. {
  17341. /*!
  17342. @brief compare two value_t enum values
  17343. @since version 3.0.0
  17344. */
  17345. bool operator()(nlohmann::detail::value_t lhs,
  17346. nlohmann::detail::value_t rhs) const noexcept
  17347. {
  17348. return nlohmann::detail::operator<(lhs, rhs);
  17349. }
  17350. };
  17351. /*!
  17352. @brief exchanges the values of two JSON objects
  17353. @since version 1.0.0
  17354. */
  17355. template<>
  17356. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  17357. is_nothrow_move_constructible<nlohmann::json>::value and
  17358. is_nothrow_move_assignable<nlohmann::json>::value
  17359. )
  17360. {
  17361. j1.swap(j2);
  17362. }
  17363. } // namespace std
  17364. /*!
  17365. @brief user-defined string literal for JSON values
  17366. This operator implements a user-defined string literal for JSON objects. It
  17367. can be used by adding `"_json"` to a string literal and returns a JSON object
  17368. if no parse error occurred.
  17369. @param[in] s a string representation of a JSON object
  17370. @param[in] n the length of string @a s
  17371. @return a JSON object
  17372. @since version 1.0.0
  17373. */
  17374. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  17375. {
  17376. return nlohmann::json::parse(s, s + n);
  17377. }
  17378. /*!
  17379. @brief user-defined string literal for JSON pointer
  17380. This operator implements a user-defined string literal for JSON Pointers. It
  17381. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  17382. object if no parse error occurred.
  17383. @param[in] s a string representation of a JSON Pointer
  17384. @param[in] n the length of string @a s
  17385. @return a JSON pointer object
  17386. @since version 2.0.0
  17387. */
  17388. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  17389. {
  17390. return nlohmann::json::json_pointer(std::string(s, n));
  17391. }
  17392. // #include <nlohmann/detail/macro_unscope.hpp>
  17393. // restore GCC/clang diagnostic settings
  17394. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  17395. #pragma GCC diagnostic pop
  17396. #endif
  17397. #if defined(__clang__)
  17398. #pragma GCC diagnostic pop
  17399. #endif
  17400. // clean up
  17401. #undef JSON_INTERNAL_CATCH
  17402. #undef JSON_CATCH
  17403. #undef JSON_THROW
  17404. #undef JSON_TRY
  17405. #undef JSON_LIKELY
  17406. #undef JSON_UNLIKELY
  17407. #undef JSON_DEPRECATED
  17408. #undef JSON_NODISCARD
  17409. #undef JSON_HAS_CPP_14
  17410. #undef JSON_HAS_CPP_17
  17411. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  17412. #undef NLOHMANN_BASIC_JSON_TPL
  17413. #endif // INCLUDE_NLOHMANN_JSON_HPP_