json.hpp 490 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 2.1.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. SOFTWARE.
  23. */
  24. #ifndef NLOHMANN_JSON_HPP
  25. #define NLOHMANN_JSON_HPP
  26. #include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <ciso646> // and, not, or
  30. #include <clocale> // lconv, localeconv
  31. #include <cmath> // isfinite, labs, ldexp, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
  35. #include <cstring> // strlen
  36. #include <forward_list> // forward_list
  37. #include <functional> // function, hash, less
  38. #include <initializer_list> // initializer_list
  39. #include <iostream> // istream, ostream
  40. #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
  41. #include <limits> // numeric_limits
  42. #include <locale> // locale
  43. #include <map> // map
  44. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  45. #include <numeric> // accumulate
  46. #include <sstream> // stringstream
  47. #include <string> // getline, stoi, string, to_string
  48. #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
  49. #include <utility> // declval, forward, make_pair, move, pair, swap
  50. #include <vector> // vector
  51. // exclude unsupported compilers
  52. #if defined(__clang__)
  53. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  54. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  55. #endif
  56. #elif defined(__GNUC__)
  57. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  58. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  59. #endif
  60. #endif
  61. // disable float-equal warnings on GCC/clang
  62. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  63. #pragma GCC diagnostic push
  64. #pragma GCC diagnostic ignored "-Wfloat-equal"
  65. #endif
  66. // disable documentation warnings on clang
  67. #if defined(__clang__)
  68. #pragma GCC diagnostic push
  69. #pragma GCC diagnostic ignored "-Wdocumentation"
  70. #endif
  71. // allow for portable deprecation warnings
  72. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  73. #define JSON_DEPRECATED __attribute__((deprecated))
  74. #elif defined(_MSC_VER)
  75. #define JSON_DEPRECATED __declspec(deprecated)
  76. #else
  77. #define JSON_DEPRECATED
  78. #endif
  79. // allow to disable exceptions
  80. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
  81. #define JSON_THROW(exception) throw exception
  82. #define JSON_TRY try
  83. #define JSON_CATCH(exception) catch(exception)
  84. #else
  85. #define JSON_THROW(exception) std::abort()
  86. #define JSON_TRY if(true)
  87. #define JSON_CATCH(exception) if(false)
  88. #endif
  89. /*!
  90. @brief namespace for Niels Lohmann
  91. @see https://github.com/nlohmann
  92. @since version 1.0.0
  93. */
  94. namespace nlohmann
  95. {
  96. /*!
  97. @brief unnamed namespace with internal helper functions
  98. This namespace collects some functions that could not be defined inside the
  99. @ref basic_json class.
  100. @since version 2.1.0
  101. */
  102. namespace detail
  103. {
  104. ////////////////
  105. // exceptions //
  106. ////////////////
  107. /*!
  108. @brief general exception of the @ref basic_json class
  109. Extension of std::exception objects with a member @a id for exception ids.
  110. @note To have nothrow-copy-constructible exceptions, we internally use
  111. std::runtime_error which can cope with arbitrary-length error messages.
  112. Intermediate strings are built with static functions and then passed to
  113. the actual constructor.
  114. @since version 3.0.0
  115. */
  116. class exception : public std::exception
  117. {
  118. public:
  119. /// returns the explanatory string
  120. virtual const char* what() const noexcept override
  121. {
  122. return m.what();
  123. }
  124. /// the id of the exception
  125. const int id;
  126. protected:
  127. exception(int id_, const char* what_arg)
  128. : id(id_), m(what_arg)
  129. {}
  130. static std::string name(const std::string& ename, int id)
  131. {
  132. return "[json.exception." + ename + "." + std::to_string(id) + "] ";
  133. }
  134. private:
  135. /// an exception object as storage for error messages
  136. std::runtime_error m;
  137. };
  138. /*!
  139. @brief exception indicating a parse error
  140. This excpetion is thrown by the library when a parse error occurs. Parse
  141. errors can occur during the deserialization of JSON text as well as when
  142. using JSON Patch.
  143. Member @a byte holds the byte index of the last read character in the input
  144. file.
  145. @note For an input with n bytes, 1 is the index of the first character
  146. and n+1 is the index of the terminating null byte or the end of
  147. file. This also holds true when reading a byte vector (CBOR or
  148. MessagePack).
  149. Exceptions have ids 1xx.
  150. name / id | example massage | description
  151. ------------------------------ | --------------- | -------------------------
  152. 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.
  153. 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.
  154. 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.
  155. 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.
  156. 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.
  157. 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 wihtout a leading `0`.
  158. 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.
  159. 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.
  160. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  161. 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.
  162. json.exception.parse_error.111 | parse error: bad input stream | Parsing CBOR or MessagePack from an input stream where the [`badbit` or `failbit`](http://en.cppreference.com/w/cpp/io/ios_base/iostate) is set.
  163. 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.
  164. 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.
  165. @since version 3.0.0
  166. */
  167. class parse_error : public exception
  168. {
  169. public:
  170. /*!
  171. @brief create a parse error exception
  172. @param[in] id the id of the exception
  173. @param[in] byte_ the byte index where the error occured (or 0 if
  174. the position cannot be determined)
  175. @param[in] what_arg the explanatory string
  176. @return parse_error object
  177. */
  178. static parse_error create(int id, size_t byte_, const std::string& what_arg)
  179. {
  180. std::string w = exception::name("parse_error", id) + "parse error" +
  181. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  182. ": " + what_arg;
  183. return parse_error(id, byte_, w.c_str());
  184. }
  185. /*!
  186. @brief byte index of the parse error
  187. The byte index of the last read character in the input file.
  188. @note For an input with n bytes, 1 is the index of the first character
  189. and n+1 is the index of the terminating null byte or the end of
  190. file. This also holds true when reading a byte vector (CBOR or
  191. MessagePack).
  192. */
  193. const size_t byte;
  194. private:
  195. parse_error(int id_, size_t byte_, const char* what_arg)
  196. : exception(id_, what_arg), byte(byte_)
  197. {}
  198. };
  199. /*!
  200. @brief exception indicating errors with iterators
  201. Exceptions have ids 2xx.
  202. name / id | example massage | description
  203. ----------------------------------- | --------------- | -------------------------
  204. 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.
  205. 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.
  206. 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.
  207. 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.
  208. 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.
  209. 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.
  210. 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.
  211. 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.
  212. 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.
  213. 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.
  214. 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.
  215. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  216. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compated, because JSON objects are unordered.
  217. 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().
  218. @since version 3.0.0
  219. */
  220. class invalid_iterator : public exception
  221. {
  222. public:
  223. static invalid_iterator create(int id, const std::string& what_arg)
  224. {
  225. std::string w = exception::name("invalid_iterator", id) + what_arg;
  226. return invalid_iterator(id, w.c_str());
  227. }
  228. private:
  229. invalid_iterator(int id_, const char* what_arg)
  230. : exception(id_, what_arg)
  231. {}
  232. };
  233. /*!
  234. @brief exception indicating executing a member function with a wrong type
  235. Exceptions have ids 3xx.
  236. name / id | example massage | description
  237. ----------------------------- | --------------- | -------------------------
  238. 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.
  239. 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.
  240. 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&.
  241. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  242. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  243. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  244. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  245. 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.
  246. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  247. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  248. 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.
  249. 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.
  250. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  251. 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.
  252. @since version 3.0.0
  253. */
  254. class type_error : public exception
  255. {
  256. public:
  257. static type_error create(int id, const std::string& what_arg)
  258. {
  259. std::string w = exception::name("type_error", id) + what_arg;
  260. return type_error(id, w.c_str());
  261. }
  262. private:
  263. type_error(int id_, const char* what_arg)
  264. : exception(id_, what_arg)
  265. {}
  266. };
  267. /*!
  268. @brief exception indicating access out of the defined range
  269. Exceptions have ids 4xx.
  270. name / id | example massage | description
  271. ------------------------------- | --------------- | -------------------------
  272. 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.
  273. 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.
  274. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  275. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  276. 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.
  277. 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.
  278. @since version 3.0.0
  279. */
  280. class out_of_range : public exception
  281. {
  282. public:
  283. static out_of_range create(int id, const std::string& what_arg)
  284. {
  285. std::string w = exception::name("out_of_range", id) + what_arg;
  286. return out_of_range(id, w.c_str());
  287. }
  288. private:
  289. out_of_range(int id_, const char* what_arg)
  290. : exception(id_, what_arg)
  291. {}
  292. };
  293. /*!
  294. @brief exception indicating other errors
  295. Exceptions have ids 5xx.
  296. name / id | example massage | description
  297. ------------------------------ | --------------- | -------------------------
  298. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  299. @since version 3.0.0
  300. */
  301. class other_error : public exception
  302. {
  303. public:
  304. static other_error create(int id, const std::string& what_arg)
  305. {
  306. std::string w = exception::name("other_error", id) + what_arg;
  307. return other_error(id, w.c_str());
  308. }
  309. private:
  310. other_error(int id_, const char* what_arg)
  311. : exception(id_, what_arg)
  312. {}
  313. };
  314. ///////////////////////////
  315. // JSON type enumeration //
  316. ///////////////////////////
  317. /*!
  318. @brief the JSON type enumeration
  319. This enumeration collects the different JSON types. It is internally used to
  320. distinguish the stored values, and the functions @ref basic_json::is_null(),
  321. @ref basic_json::is_object(), @ref basic_json::is_array(),
  322. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  323. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  324. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  325. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  326. @ref basic_json::is_structured() rely on it.
  327. @note There are three enumeration entries (number_integer, number_unsigned, and
  328. number_float), because the library distinguishes these three types for numbers:
  329. @ref basic_json::number_unsigned_t is used for unsigned integers,
  330. @ref basic_json::number_integer_t is used for signed integers, and
  331. @ref basic_json::number_float_t is used for floating-point numbers or to
  332. approximate integers which do not fit in the limits of their respective type.
  333. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  334. value with the default value for a given type
  335. @since version 1.0.0
  336. */
  337. enum class value_t : uint8_t
  338. {
  339. null, ///< null value
  340. object, ///< object (unordered set of name/value pairs)
  341. array, ///< array (ordered collection of values)
  342. string, ///< string value
  343. boolean, ///< boolean value
  344. number_integer, ///< number value (signed integer)
  345. number_unsigned, ///< number value (unsigned integer)
  346. number_float, ///< number value (floating-point)
  347. discarded ///< discarded by the the parser callback function
  348. };
  349. /*!
  350. @brief comparison operator for JSON types
  351. Returns an ordering that is similar to Python:
  352. - order: null < boolean < number < object < array < string
  353. - furthermore, each type is not smaller than itself
  354. @since version 1.0.0
  355. */
  356. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  357. {
  358. static constexpr std::array<uint8_t, 8> order = {{
  359. 0, // null
  360. 3, // object
  361. 4, // array
  362. 5, // string
  363. 1, // boolean
  364. 2, // integer
  365. 2, // unsigned
  366. 2, // float
  367. }
  368. };
  369. // discarded values are not comparable
  370. if (lhs == value_t::discarded or rhs == value_t::discarded)
  371. {
  372. return false;
  373. }
  374. return order[static_cast<std::size_t>(lhs)] <
  375. order[static_cast<std::size_t>(rhs)];
  376. }
  377. /////////////
  378. // helpers //
  379. /////////////
  380. // alias templates to reduce boilerplate
  381. template<bool B, typename T = void>
  382. using enable_if_t = typename std::enable_if<B, T>::type;
  383. template<typename T>
  384. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  385. /*
  386. Implementation of two C++17 constructs: conjunction, negation. This is needed
  387. to avoid evaluating all the traits in a condition
  388. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  389. will not compile when T = void (on MSVC at least). Whereas
  390. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  391. stop evaluating if negation<...>::value == false
  392. Please note that those constructs must be used with caution, since symbols can
  393. become very long quickly (which can slow down compilation and cause MSVC
  394. internal compiler errors). Only use it when you have to (see example ahead).
  395. */
  396. template<class...> struct conjunction : std::true_type {};
  397. template<class B1> struct conjunction<B1> : B1 {};
  398. template<class B1, class... Bn>
  399. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  400. template<class B> struct negation : std::integral_constant < bool, !B::value > {};
  401. // dispatch utility (taken from ranges-v3)
  402. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  403. template<> struct priority_tag<0> {};
  404. //////////////////
  405. // constructors //
  406. //////////////////
  407. template<value_t> struct external_constructor;
  408. template<>
  409. struct external_constructor<value_t::boolean>
  410. {
  411. template<typename BasicJsonType>
  412. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  413. {
  414. j.m_type = value_t::boolean;
  415. j.m_value = b;
  416. j.assert_invariant();
  417. }
  418. };
  419. template<>
  420. struct external_constructor<value_t::string>
  421. {
  422. template<typename BasicJsonType>
  423. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  424. {
  425. j.m_type = value_t::string;
  426. j.m_value = s;
  427. j.assert_invariant();
  428. }
  429. };
  430. template<>
  431. struct external_constructor<value_t::number_float>
  432. {
  433. template<typename BasicJsonType>
  434. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  435. {
  436. j.m_type = value_t::number_float;
  437. j.m_value = val;
  438. j.assert_invariant();
  439. }
  440. };
  441. template<>
  442. struct external_constructor<value_t::number_unsigned>
  443. {
  444. template<typename BasicJsonType>
  445. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  446. {
  447. j.m_type = value_t::number_unsigned;
  448. j.m_value = val;
  449. j.assert_invariant();
  450. }
  451. };
  452. template<>
  453. struct external_constructor<value_t::number_integer>
  454. {
  455. template<typename BasicJsonType>
  456. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  457. {
  458. j.m_type = value_t::number_integer;
  459. j.m_value = val;
  460. j.assert_invariant();
  461. }
  462. };
  463. template<>
  464. struct external_constructor<value_t::array>
  465. {
  466. template<typename BasicJsonType>
  467. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  468. {
  469. j.m_type = value_t::array;
  470. j.m_value = arr;
  471. j.assert_invariant();
  472. }
  473. template<typename BasicJsonType, typename CompatibleArrayType,
  474. enable_if_t<not std::is_same<CompatibleArrayType,
  475. typename BasicJsonType::array_t>::value,
  476. int> = 0>
  477. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  478. {
  479. using std::begin;
  480. using std::end;
  481. j.m_type = value_t::array;
  482. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  483. j.assert_invariant();
  484. }
  485. template<typename BasicJsonType>
  486. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  487. {
  488. j.m_type = value_t::array;
  489. j.m_value = value_t::array;
  490. j.m_value.array->reserve(arr.size());
  491. for (bool x : arr)
  492. {
  493. j.m_value.array->push_back(x);
  494. }
  495. j.assert_invariant();
  496. }
  497. };
  498. template<>
  499. struct external_constructor<value_t::object>
  500. {
  501. template<typename BasicJsonType>
  502. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  503. {
  504. j.m_type = value_t::object;
  505. j.m_value = obj;
  506. j.assert_invariant();
  507. }
  508. template<typename BasicJsonType, typename CompatibleObjectType,
  509. enable_if_t<not std::is_same<CompatibleObjectType,
  510. typename BasicJsonType::object_t>::value,
  511. int> = 0>
  512. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  513. {
  514. using std::begin;
  515. using std::end;
  516. j.m_type = value_t::object;
  517. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  518. j.assert_invariant();
  519. }
  520. };
  521. ////////////////////////
  522. // has_/is_ functions //
  523. ////////////////////////
  524. /*!
  525. @brief Helper to determine whether there's a key_type for T.
  526. This helper is used to tell associative containers apart from other containers
  527. such as sequence containers. For instance, `std::map` passes the test as it
  528. contains a `mapped_type`, whereas `std::vector` fails the test.
  529. @sa http://stackoverflow.com/a/7728728/266378
  530. @since version 1.0.0, overworked in version 2.0.6
  531. */
  532. #define NLOHMANN_JSON_HAS_HELPER(type) \
  533. template<typename T> struct has_##type { \
  534. private: \
  535. template<typename U, typename = typename U::type> \
  536. static int detect(U &&); \
  537. static void detect(...); \
  538. public: \
  539. static constexpr bool value = \
  540. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  541. }
  542. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  543. NLOHMANN_JSON_HAS_HELPER(key_type);
  544. NLOHMANN_JSON_HAS_HELPER(value_type);
  545. NLOHMANN_JSON_HAS_HELPER(iterator);
  546. #undef NLOHMANN_JSON_HAS_HELPER
  547. template<bool B, class RealType, class CompatibleObjectType>
  548. struct is_compatible_object_type_impl : std::false_type {};
  549. template<class RealType, class CompatibleObjectType>
  550. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  551. {
  552. static constexpr auto value =
  553. std::is_constructible<typename RealType::key_type,
  554. typename CompatibleObjectType::key_type>::value and
  555. std::is_constructible<typename RealType::mapped_type,
  556. typename CompatibleObjectType::mapped_type>::value;
  557. };
  558. template<class BasicJsonType, class CompatibleObjectType>
  559. struct is_compatible_object_type
  560. {
  561. static auto constexpr value = is_compatible_object_type_impl <
  562. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  563. has_mapped_type<CompatibleObjectType>,
  564. has_key_type<CompatibleObjectType>>::value,
  565. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  566. };
  567. template<typename BasicJsonType, typename T>
  568. struct is_basic_json_nested_type
  569. {
  570. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  571. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  572. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  573. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or
  574. std::is_same<T, typename BasicJsonType::json_pointer>::value;
  575. };
  576. template<class BasicJsonType, class CompatibleArrayType>
  577. struct is_compatible_array_type
  578. {
  579. static auto constexpr value =
  580. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  581. negation<is_compatible_object_type<
  582. BasicJsonType, CompatibleArrayType>>,
  583. negation<std::is_constructible<typename BasicJsonType::string_t,
  584. CompatibleArrayType>>,
  585. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  586. has_value_type<CompatibleArrayType>,
  587. has_iterator<CompatibleArrayType>>::value;
  588. };
  589. template<bool, typename, typename>
  590. struct is_compatible_integer_type_impl : std::false_type {};
  591. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  592. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  593. {
  594. // is there an assert somewhere on overflows?
  595. using RealLimits = std::numeric_limits<RealIntegerType>;
  596. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  597. static constexpr auto value =
  598. std::is_constructible<RealIntegerType,
  599. CompatibleNumberIntegerType>::value and
  600. CompatibleLimits::is_integer and
  601. RealLimits::is_signed == CompatibleLimits::is_signed;
  602. };
  603. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  604. struct is_compatible_integer_type
  605. {
  606. static constexpr auto value =
  607. is_compatible_integer_type_impl <
  608. std::is_integral<CompatibleNumberIntegerType>::value and
  609. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  610. RealIntegerType, CompatibleNumberIntegerType > ::value;
  611. };
  612. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  613. template<typename BasicJsonType, typename T>
  614. struct has_from_json
  615. {
  616. private:
  617. // also check the return type of from_json
  618. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  619. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  620. static int detect(U&&);
  621. static void detect(...);
  622. public:
  623. static constexpr bool value = std::is_integral<decltype(
  624. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  625. };
  626. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  627. // this overload is used for non-default-constructible user-defined-types
  628. template<typename BasicJsonType, typename T>
  629. struct has_non_default_from_json
  630. {
  631. private:
  632. template <
  633. typename U,
  634. typename = enable_if_t<std::is_same<
  635. T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
  636. static int detect(U&&);
  637. static void detect(...);
  638. public:
  639. static constexpr bool value = std::is_integral<decltype(detect(
  640. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  641. };
  642. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  643. template<typename BasicJsonType, typename T>
  644. struct has_to_json
  645. {
  646. private:
  647. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  648. std::declval<BasicJsonType&>(), std::declval<T>()))>
  649. static int detect(U&&);
  650. static void detect(...);
  651. public:
  652. static constexpr bool value = std::is_integral<decltype(detect(
  653. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  654. };
  655. /////////////
  656. // to_json //
  657. /////////////
  658. template<typename BasicJsonType, typename T, enable_if_t<
  659. std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  660. void to_json(BasicJsonType& j, T b) noexcept
  661. {
  662. external_constructor<value_t::boolean>::construct(j, b);
  663. }
  664. template<typename BasicJsonType, typename CompatibleString,
  665. enable_if_t<std::is_constructible<typename BasicJsonType::string_t,
  666. CompatibleString>::value, int> = 0>
  667. void to_json(BasicJsonType& j, const CompatibleString& s)
  668. {
  669. external_constructor<value_t::string>::construct(j, s);
  670. }
  671. template<typename BasicJsonType, typename FloatType,
  672. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  673. void to_json(BasicJsonType& j, FloatType val) noexcept
  674. {
  675. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  676. }
  677. template <
  678. typename BasicJsonType, typename CompatibleNumberUnsignedType,
  679. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
  680. CompatibleNumberUnsignedType>::value, int> = 0 >
  681. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  682. {
  683. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  684. }
  685. template <
  686. typename BasicJsonType, typename CompatibleNumberIntegerType,
  687. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t,
  688. CompatibleNumberIntegerType>::value, int> = 0 >
  689. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  690. {
  691. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  692. }
  693. template<typename BasicJsonType, typename EnumType,
  694. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  695. void to_json(BasicJsonType& j, EnumType e) noexcept
  696. {
  697. using underlying_type = typename std::underlying_type<EnumType>::type;
  698. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  699. }
  700. template<typename BasicJsonType>
  701. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  702. {
  703. external_constructor<value_t::array>::construct(j, e);
  704. }
  705. template <
  706. typename BasicJsonType, typename CompatibleArrayType,
  707. enable_if_t <
  708. is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  709. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  710. int > = 0 >
  711. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  712. {
  713. external_constructor<value_t::array>::construct(j, arr);
  714. }
  715. template <
  716. typename BasicJsonType, typename CompatibleObjectType,
  717. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value,
  718. int> = 0 >
  719. void to_json(BasicJsonType& j, const CompatibleObjectType& arr)
  720. {
  721. external_constructor<value_t::object>::construct(j, arr);
  722. }
  723. template <typename BasicJsonType, typename T, std::size_t N,
  724. enable_if_t<not std::is_constructible<
  725. typename BasicJsonType::string_t, T (&)[N]>::value,
  726. int> = 0>
  727. void to_json(BasicJsonType& j, T (&arr)[N])
  728. {
  729. external_constructor<value_t::array>::construct(j, arr);
  730. }
  731. ///////////////
  732. // from_json //
  733. ///////////////
  734. // overloads for basic_json template parameters
  735. template<typename BasicJsonType, typename ArithmeticType,
  736. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  737. not std::is_same<ArithmeticType,
  738. typename BasicJsonType::boolean_t>::value,
  739. int> = 0>
  740. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  741. {
  742. switch (static_cast<value_t>(j))
  743. {
  744. case value_t::number_unsigned:
  745. {
  746. val = static_cast<ArithmeticType>(
  747. *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  748. break;
  749. }
  750. case value_t::number_integer:
  751. {
  752. val = static_cast<ArithmeticType>(
  753. *j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  754. break;
  755. }
  756. case value_t::number_float:
  757. {
  758. val = static_cast<ArithmeticType>(
  759. *j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  760. break;
  761. }
  762. default:
  763. {
  764. JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name()));
  765. }
  766. }
  767. }
  768. template<typename BasicJsonType>
  769. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  770. {
  771. if (not j.is_boolean())
  772. {
  773. JSON_THROW(type_error::create(302, "type must be boolean, but is " + j.type_name()));
  774. }
  775. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  776. }
  777. template<typename BasicJsonType>
  778. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  779. {
  780. if (not j.is_string())
  781. {
  782. JSON_THROW(type_error::create(302, "type must be string, but is " + j.type_name()));
  783. }
  784. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  785. }
  786. template<typename BasicJsonType>
  787. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  788. {
  789. get_arithmetic_value(j, val);
  790. }
  791. template<typename BasicJsonType>
  792. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  793. {
  794. get_arithmetic_value(j, val);
  795. }
  796. template<typename BasicJsonType>
  797. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  798. {
  799. get_arithmetic_value(j, val);
  800. }
  801. template<typename BasicJsonType, typename EnumType,
  802. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  803. void from_json(const BasicJsonType& j, EnumType& e)
  804. {
  805. typename std::underlying_type<EnumType>::type val;
  806. get_arithmetic_value(j, val);
  807. e = static_cast<EnumType>(val);
  808. }
  809. template<typename BasicJsonType>
  810. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  811. {
  812. if (not j.is_array())
  813. {
  814. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  815. }
  816. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  817. }
  818. // forward_list doesn't have an insert method
  819. template<typename BasicJsonType, typename T, typename Allocator,
  820. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  821. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  822. {
  823. if (not j.is_array())
  824. {
  825. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  826. }
  827. for (auto it = j.rbegin(), end = j.rend(); it != end; ++it)
  828. {
  829. l.push_front(it->template get<T>());
  830. }
  831. }
  832. template<typename BasicJsonType, typename CompatibleArrayType>
  833. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>)
  834. {
  835. using std::begin;
  836. using std::end;
  837. std::transform(j.begin(), j.end(),
  838. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  839. {
  840. // get<BasicJsonType>() returns *this, this won't call a from_json
  841. // method when value_type is BasicJsonType
  842. return i.template get<typename CompatibleArrayType::value_type>();
  843. });
  844. }
  845. template<typename BasicJsonType, typename CompatibleArrayType>
  846. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>)
  847. -> decltype(
  848. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  849. void())
  850. {
  851. using std::begin;
  852. using std::end;
  853. arr.reserve(j.size());
  854. std::transform(j.begin(), j.end(),
  855. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  856. {
  857. // get<BasicJsonType>() returns *this, this won't call a from_json
  858. // method when value_type is BasicJsonType
  859. return i.template get<typename CompatibleArrayType::value_type>();
  860. });
  861. }
  862. template<typename BasicJsonType, typename CompatibleArrayType,
  863. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  864. std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
  865. not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
  866. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  867. {
  868. if (not j.is_array())
  869. {
  870. JSON_THROW(type_error::create(302, "type must be array, but is " + j.type_name()));
  871. }
  872. from_json_array_impl(j, arr, priority_tag<1> {});
  873. }
  874. template<typename BasicJsonType, typename CompatibleObjectType,
  875. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  876. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  877. {
  878. if (not j.is_object())
  879. {
  880. JSON_THROW(type_error::create(302, "type must be object, but is " + j.type_name()));
  881. }
  882. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  883. using std::begin;
  884. using std::end;
  885. // we could avoid the assignment, but this might require a for loop, which
  886. // might be less efficient than the container constructor for some
  887. // containers (would it?)
  888. obj = CompatibleObjectType(begin(*inner_object), end(*inner_object));
  889. }
  890. // overload for arithmetic types, not chosen for basic_json template arguments
  891. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  892. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  893. // an arithmetic type?
  894. template<typename BasicJsonType, typename ArithmeticType,
  895. enable_if_t <
  896. std::is_arithmetic<ArithmeticType>::value and
  897. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  898. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  899. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  900. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  901. int> = 0>
  902. void from_json(const BasicJsonType& j, ArithmeticType& val)
  903. {
  904. switch (static_cast<value_t>(j))
  905. {
  906. case value_t::number_unsigned:
  907. {
  908. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  909. break;
  910. }
  911. case value_t::number_integer:
  912. {
  913. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  914. break;
  915. }
  916. case value_t::number_float:
  917. {
  918. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  919. break;
  920. }
  921. case value_t::boolean:
  922. {
  923. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  924. break;
  925. }
  926. default:
  927. {
  928. JSON_THROW(type_error::create(302, "type must be number, but is " + j.type_name()));
  929. }
  930. }
  931. }
  932. struct to_json_fn
  933. {
  934. private:
  935. template<typename BasicJsonType, typename T>
  936. auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  937. -> decltype(to_json(j, std::forward<T>(val)), void())
  938. {
  939. return to_json(j, std::forward<T>(val));
  940. }
  941. template<typename BasicJsonType, typename T>
  942. void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept
  943. {
  944. static_assert(sizeof(BasicJsonType) == 0,
  945. "could not find to_json() method in T's namespace");
  946. }
  947. public:
  948. template<typename BasicJsonType, typename T>
  949. void operator()(BasicJsonType& j, T&& val) const
  950. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  951. {
  952. return call(j, std::forward<T>(val), priority_tag<1> {});
  953. }
  954. };
  955. struct from_json_fn
  956. {
  957. private:
  958. template<typename BasicJsonType, typename T>
  959. auto call(const BasicJsonType& j, T& val, priority_tag<1>) const
  960. noexcept(noexcept(from_json(j, val)))
  961. -> decltype(from_json(j, val), void())
  962. {
  963. return from_json(j, val);
  964. }
  965. template<typename BasicJsonType, typename T>
  966. void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept
  967. {
  968. static_assert(sizeof(BasicJsonType) == 0,
  969. "could not find from_json() method in T's namespace");
  970. }
  971. public:
  972. template<typename BasicJsonType, typename T>
  973. void operator()(const BasicJsonType& j, T& val) const
  974. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  975. {
  976. return call(j, val, priority_tag<1> {});
  977. }
  978. };
  979. // taken from ranges-v3
  980. template<typename T>
  981. struct static_const
  982. {
  983. static constexpr T value{};
  984. };
  985. template<typename T>
  986. constexpr T static_const<T>::value;
  987. } // namespace detail
  988. /// namespace to hold default `to_json` / `from_json` functions
  989. namespace
  990. {
  991. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  992. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  993. }
  994. /*!
  995. @brief default JSONSerializer template argument
  996. This serializer ignores the template arguments and uses ADL
  997. ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
  998. for serialization.
  999. */
  1000. template<typename = void, typename = void>
  1001. struct adl_serializer
  1002. {
  1003. /*!
  1004. @brief convert a JSON value to any value type
  1005. This function is usually called by the `get()` function of the
  1006. @ref basic_json class (either explicit or via conversion operators).
  1007. @param[in] j JSON value to read from
  1008. @param[in,out] val value to write to
  1009. */
  1010. template<typename BasicJsonType, typename ValueType>
  1011. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  1012. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  1013. {
  1014. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  1015. }
  1016. /*!
  1017. @brief convert any value type to a JSON value
  1018. This function is usually called by the constructors of the @ref basic_json
  1019. class.
  1020. @param[in,out] j JSON value to write to
  1021. @param[in] val value to read from
  1022. */
  1023. template<typename BasicJsonType, typename ValueType>
  1024. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  1025. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  1026. {
  1027. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  1028. }
  1029. };
  1030. /*!
  1031. @brief a class to store JSON values
  1032. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  1033. in @ref object_t)
  1034. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  1035. in @ref array_t)
  1036. @tparam StringType type for JSON strings and object keys (`std::string` by
  1037. default; will be used in @ref string_t)
  1038. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  1039. in @ref boolean_t)
  1040. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  1041. default; will be used in @ref number_integer_t)
  1042. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  1043. `uint64_t` by default; will be used in @ref number_unsigned_t)
  1044. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  1045. default; will be used in @ref number_float_t)
  1046. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  1047. default)
  1048. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  1049. and `from_json()` (@ref adl_serializer by default)
  1050. @requirement The class satisfies the following concept requirements:
  1051. - Basic
  1052. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  1053. JSON values can be default constructed. The result will be a JSON null
  1054. value.
  1055. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  1056. A JSON value can be constructed from an rvalue argument.
  1057. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  1058. A JSON value can be copy-constructed from an lvalue expression.
  1059. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  1060. A JSON value van be assigned from an rvalue argument.
  1061. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  1062. A JSON value can be copy-assigned from an lvalue expression.
  1063. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  1064. JSON values can be destructed.
  1065. - Layout
  1066. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  1067. JSON values have
  1068. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  1069. All non-static data members are private and standard layout types, the
  1070. class has no virtual functions or (virtual) base classes.
  1071. - Library-wide
  1072. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  1073. JSON values can be compared with `==`, see @ref
  1074. operator==(const_reference,const_reference).
  1075. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  1076. JSON values can be compared with `<`, see @ref
  1077. operator<(const_reference,const_reference).
  1078. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  1079. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  1080. other compatible types, using unqualified function call @ref swap().
  1081. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  1082. JSON values can be compared against `std::nullptr_t` objects which are used
  1083. to model the `null` value.
  1084. - Container
  1085. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  1086. JSON values can be used like STL containers and provide iterator access.
  1087. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  1088. JSON values can be used like STL containers and provide reverse iterator
  1089. access.
  1090. @invariant The member variables @a m_value and @a m_type have the following
  1091. relationship:
  1092. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  1093. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  1094. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  1095. The invariants are checked by member function assert_invariant().
  1096. @internal
  1097. @note ObjectType trick from http://stackoverflow.com/a/9860911
  1098. @endinternal
  1099. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  1100. Format](http://rfc7159.net/rfc7159)
  1101. @since version 1.0.0
  1102. @nosubgrouping
  1103. */
  1104. template <
  1105. template<typename U, typename V, typename... Args> class ObjectType = std::map,
  1106. template<typename U, typename... Args> class ArrayType = std::vector,
  1107. class StringType = std::string,
  1108. class BooleanType = bool,
  1109. class NumberIntegerType = std::int64_t,
  1110. class NumberUnsignedType = std::uint64_t,
  1111. class NumberFloatType = double,
  1112. template<typename U> class AllocatorType = std::allocator,
  1113. template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer
  1114. >
  1115. class basic_json
  1116. {
  1117. private:
  1118. template<detail::value_t> friend struct detail::external_constructor;
  1119. /// workaround type for MSVC
  1120. using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
  1121. BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
  1122. AllocatorType, JSONSerializer>;
  1123. public:
  1124. using value_t = detail::value_t;
  1125. // forward declarations
  1126. template<typename U> class iter_impl;
  1127. template<typename Base> class json_reverse_iterator;
  1128. class json_pointer;
  1129. template<typename T, typename SFINAE>
  1130. using json_serializer = JSONSerializer<T, SFINAE>;
  1131. ////////////////
  1132. // exceptions //
  1133. ////////////////
  1134. /// @name exceptions
  1135. /// Classes to implement user-defined exceptions.
  1136. /// @{
  1137. /// @copydoc detail::exception
  1138. using exception = detail::exception;
  1139. /// @copydoc detail::parse_error
  1140. using parse_error = detail::parse_error;
  1141. /// @copydoc detail::invalid_iterator
  1142. using invalid_iterator = detail::invalid_iterator;
  1143. /// @copydoc detail::type_error
  1144. using type_error = detail::type_error;
  1145. /// @copydoc detail::out_of_range
  1146. using out_of_range = detail::out_of_range;
  1147. /// @copydoc detail::other_error
  1148. using other_error = detail::other_error;
  1149. /// @}
  1150. /////////////////////
  1151. // container types //
  1152. /////////////////////
  1153. /// @name container types
  1154. /// The canonic container types to use @ref basic_json like any other STL
  1155. /// container.
  1156. /// @{
  1157. /// the type of elements in a basic_json container
  1158. using value_type = basic_json;
  1159. /// the type of an element reference
  1160. using reference = value_type&;
  1161. /// the type of an element const reference
  1162. using const_reference = const value_type&;
  1163. /// a type to represent differences between iterators
  1164. using difference_type = std::ptrdiff_t;
  1165. /// a type to represent container sizes
  1166. using size_type = std::size_t;
  1167. /// the allocator type
  1168. using allocator_type = AllocatorType<basic_json>;
  1169. /// the type of an element pointer
  1170. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  1171. /// the type of an element const pointer
  1172. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  1173. /// an iterator for a basic_json container
  1174. using iterator = iter_impl<basic_json>;
  1175. /// a const iterator for a basic_json container
  1176. using const_iterator = iter_impl<const basic_json>;
  1177. /// a reverse iterator for a basic_json container
  1178. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  1179. /// a const reverse iterator for a basic_json container
  1180. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  1181. /// @}
  1182. /*!
  1183. @brief returns the allocator associated with the container
  1184. */
  1185. static allocator_type get_allocator()
  1186. {
  1187. return allocator_type();
  1188. }
  1189. /*!
  1190. @brief returns version information on the library
  1191. This function returns a JSON object with information about the library,
  1192. including the version number and information on the platform and compiler.
  1193. @return JSON object holding version information
  1194. key | description
  1195. ----------- | ---------------
  1196. `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).
  1197. `copyright` | The copyright line for the library as string.
  1198. `name` | The name of the library as string.
  1199. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  1200. `url` | The URL of the project as string.
  1201. `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).
  1202. @liveexample{The following code shows an example output of the `meta()`
  1203. function.,meta}
  1204. @complexity Constant.
  1205. @since 2.1.0
  1206. */
  1207. static basic_json meta()
  1208. {
  1209. basic_json result;
  1210. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  1211. result["name"] = "JSON for Modern C++";
  1212. result["url"] = "https://github.com/nlohmann/json";
  1213. result["version"] =
  1214. {
  1215. {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1}
  1216. };
  1217. #ifdef _WIN32
  1218. result["platform"] = "win32";
  1219. #elif defined __linux__
  1220. result["platform"] = "linux";
  1221. #elif defined __APPLE__
  1222. result["platform"] = "apple";
  1223. #elif defined __unix__
  1224. result["platform"] = "unix";
  1225. #else
  1226. result["platform"] = "unknown";
  1227. #endif
  1228. #if defined(__clang__)
  1229. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  1230. #elif defined(__ICC) || defined(__INTEL_COMPILER)
  1231. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  1232. #elif defined(__GNUC__) || defined(__GNUG__)
  1233. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  1234. #elif defined(__HP_cc) || defined(__HP_aCC)
  1235. result["compiler"] = "hp"
  1236. #elif defined(__IBMCPP__)
  1237. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  1238. #elif defined(_MSC_VER)
  1239. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  1240. #elif defined(__PGI)
  1241. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  1242. #elif defined(__SUNPRO_CC)
  1243. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  1244. #else
  1245. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  1246. #endif
  1247. #ifdef __cplusplus
  1248. result["compiler"]["c++"] = std::to_string(__cplusplus);
  1249. #else
  1250. result["compiler"]["c++"] = "unknown";
  1251. #endif
  1252. return result;
  1253. }
  1254. ///////////////////////////
  1255. // JSON value data types //
  1256. ///////////////////////////
  1257. /// @name JSON value data types
  1258. /// The data types to store a JSON value. These types are derived from
  1259. /// the template arguments passed to class @ref basic_json.
  1260. /// @{
  1261. /*!
  1262. @brief a type for an object
  1263. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  1264. > An object is an unordered collection of zero or more name/value pairs,
  1265. > where a name is a string and a value is a string, number, boolean, null,
  1266. > object, or array.
  1267. To store objects in C++, a type is defined by the template parameters
  1268. described below.
  1269. @tparam ObjectType the container to store objects (e.g., `std::map` or
  1270. `std::unordered_map`)
  1271. @tparam StringType the type of the keys or names (e.g., `std::string`).
  1272. The comparison function `std::less<StringType>` is used to order elements
  1273. inside the container.
  1274. @tparam AllocatorType the allocator to use for objects (e.g.,
  1275. `std::allocator`)
  1276. #### Default type
  1277. With the default values for @a ObjectType (`std::map`), @a StringType
  1278. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  1279. value for @a object_t is:
  1280. @code {.cpp}
  1281. std::map<
  1282. std::string, // key_type
  1283. basic_json, // value_type
  1284. std::less<std::string>, // key_compare
  1285. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  1286. >
  1287. @endcode
  1288. #### Behavior
  1289. The choice of @a object_t influences the behavior of the JSON class. With
  1290. the default type, objects have the following behavior:
  1291. - When all names are unique, objects will be interoperable in the sense
  1292. that all software implementations receiving that object will agree on
  1293. the name-value mappings.
  1294. - When the names within an object are not unique, later stored name/value
  1295. pairs overwrite previously stored name/value pairs, leaving the used
  1296. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  1297. be treated as equal and both stored as `{"key": 1}`.
  1298. - Internally, name/value pairs are stored in lexicographical order of the
  1299. names. Objects will also be serialized (see @ref dump) in this order.
  1300. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  1301. and serialized as `{"a": 2, "b": 1}`.
  1302. - When comparing objects, the order of the name/value pairs is irrelevant.
  1303. This makes objects interoperable in the sense that they will not be
  1304. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  1305. `{"a": 2, "b": 1}` will be treated as equal.
  1306. #### Limits
  1307. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1308. > An implementation may set limits on the maximum depth of nesting.
  1309. In this class, the object's limit of nesting is not constraint explicitly.
  1310. However, a maximum depth of nesting may be introduced by the compiler or
  1311. runtime environment. A theoretical limit can be queried by calling the
  1312. @ref max_size function of a JSON object.
  1313. #### Storage
  1314. Objects are stored as pointers in a @ref basic_json type. That is, for any
  1315. access to object values, a pointer of type `object_t*` must be
  1316. dereferenced.
  1317. @sa @ref array_t -- type for an array value
  1318. @since version 1.0.0
  1319. @note The order name/value pairs are added to the object is *not*
  1320. preserved by the library. Therefore, iterating an object may return
  1321. name/value pairs in a different order than they were originally stored. In
  1322. fact, keys will be traversed in alphabetical order as `std::map` with
  1323. `std::less` is used by default. Please note this behavior conforms to [RFC
  1324. 7159](http://rfc7159.net/rfc7159), because any order implements the
  1325. specified "unordered" nature of JSON objects.
  1326. */
  1327. using object_t = ObjectType<StringType,
  1328. basic_json,
  1329. std::less<StringType>,
  1330. AllocatorType<std::pair<const StringType,
  1331. basic_json>>>;
  1332. /*!
  1333. @brief a type for an array
  1334. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  1335. > An array is an ordered sequence of zero or more values.
  1336. To store objects in C++, a type is defined by the template parameters
  1337. explained below.
  1338. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  1339. `std::list`)
  1340. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  1341. #### Default type
  1342. With the default values for @a ArrayType (`std::vector`) and @a
  1343. AllocatorType (`std::allocator`), the default value for @a array_t is:
  1344. @code {.cpp}
  1345. std::vector<
  1346. basic_json, // value_type
  1347. std::allocator<basic_json> // allocator_type
  1348. >
  1349. @endcode
  1350. #### Limits
  1351. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1352. > An implementation may set limits on the maximum depth of nesting.
  1353. In this class, the array's limit of nesting is not constraint explicitly.
  1354. However, a maximum depth of nesting may be introduced by the compiler or
  1355. runtime environment. A theoretical limit can be queried by calling the
  1356. @ref max_size function of a JSON array.
  1357. #### Storage
  1358. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  1359. access to array values, a pointer of type `array_t*` must be dereferenced.
  1360. @sa @ref object_t -- type for an object value
  1361. @since version 1.0.0
  1362. */
  1363. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  1364. /*!
  1365. @brief a type for a string
  1366. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  1367. > A string is a sequence of zero or more Unicode characters.
  1368. To store objects in C++, a type is defined by the template parameter
  1369. described below. Unicode values are split by the JSON class into
  1370. byte-sized characters during deserialization.
  1371. @tparam StringType the container to store strings (e.g., `std::string`).
  1372. Note this container is used for keys/names in objects, see @ref object_t.
  1373. #### Default type
  1374. With the default values for @a StringType (`std::string`), the default
  1375. value for @a string_t is:
  1376. @code {.cpp}
  1377. std::string
  1378. @endcode
  1379. #### Encoding
  1380. Strings are stored in UTF-8 encoding. Therefore, functions like
  1381. `std::string::size()` or `std::string::length()` return the number of
  1382. bytes in the string rather than the number of characters or glyphs.
  1383. #### String comparison
  1384. [RFC 7159](http://rfc7159.net/rfc7159) states:
  1385. > Software implementations are typically required to test names of object
  1386. > members for equality. Implementations that transform the textual
  1387. > representation into sequences of Unicode code units and then perform the
  1388. > comparison numerically, code unit by code unit, are interoperable in the
  1389. > sense that implementations will agree in all cases on equality or
  1390. > inequality of two strings. For example, implementations that compare
  1391. > strings with escaped characters unconverted may incorrectly find that
  1392. > `"a\\b"` and `"a\u005Cb"` are not equal.
  1393. This implementation is interoperable as it does compare strings code unit
  1394. by code unit.
  1395. #### Storage
  1396. String values are stored as pointers in a @ref basic_json type. That is,
  1397. for any access to string values, a pointer of type `string_t*` must be
  1398. dereferenced.
  1399. @since version 1.0.0
  1400. */
  1401. using string_t = StringType;
  1402. /*!
  1403. @brief a type for a boolean
  1404. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  1405. type which differentiates the two literals `true` and `false`.
  1406. To store objects in C++, a type is defined by the template parameter @a
  1407. BooleanType which chooses the type to use.
  1408. #### Default type
  1409. With the default values for @a BooleanType (`bool`), the default value for
  1410. @a boolean_t is:
  1411. @code {.cpp}
  1412. bool
  1413. @endcode
  1414. #### Storage
  1415. Boolean values are stored directly inside a @ref basic_json type.
  1416. @since version 1.0.0
  1417. */
  1418. using boolean_t = BooleanType;
  1419. /*!
  1420. @brief a type for a number (integer)
  1421. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1422. > The representation of numbers is similar to that used in most
  1423. > programming languages. A number is represented in base 10 using decimal
  1424. > digits. It contains an integer component that may be prefixed with an
  1425. > optional minus sign, which may be followed by a fraction part and/or an
  1426. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1427. > cannot be represented in the grammar below (such as Infinity and NaN)
  1428. > are not permitted.
  1429. This description includes both integer and floating-point numbers.
  1430. However, C++ allows more precise storage if it is known whether the number
  1431. is a signed integer, an unsigned integer or a floating-point number.
  1432. Therefore, three different types, @ref number_integer_t, @ref
  1433. number_unsigned_t and @ref number_float_t are used.
  1434. To store integer numbers in C++, a type is defined by the template
  1435. parameter @a NumberIntegerType which chooses the type to use.
  1436. #### Default type
  1437. With the default values for @a NumberIntegerType (`int64_t`), the default
  1438. value for @a number_integer_t is:
  1439. @code {.cpp}
  1440. int64_t
  1441. @endcode
  1442. #### Default behavior
  1443. - The restrictions about leading zeros is not enforced in C++. Instead,
  1444. leading zeros in integer literals lead to an interpretation as octal
  1445. number. Internally, the value will be stored as decimal number. For
  1446. instance, the C++ integer literal `010` will be serialized to `8`.
  1447. During deserialization, leading zeros yield an error.
  1448. - Not-a-number (NaN) values will be serialized to `null`.
  1449. #### Limits
  1450. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1451. > An implementation may set limits on the range and precision of numbers.
  1452. When the default type is used, the maximal integer number that can be
  1453. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  1454. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  1455. that are out of range will yield over/underflow when used in a
  1456. constructor. During deserialization, too large or small integer numbers
  1457. will be automatically be stored as @ref number_unsigned_t or @ref
  1458. number_float_t.
  1459. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  1460. > Note that when such software is used, numbers that are integers and are
  1461. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  1462. > that implementations will agree exactly on their numeric values.
  1463. As this range is a subrange of the exactly supported range [INT64_MIN,
  1464. INT64_MAX], this class's integer type is interoperable.
  1465. #### Storage
  1466. Integer number values are stored directly inside a @ref basic_json type.
  1467. @sa @ref number_float_t -- type for number values (floating-point)
  1468. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  1469. @since version 1.0.0
  1470. */
  1471. using number_integer_t = NumberIntegerType;
  1472. /*!
  1473. @brief a type for a number (unsigned)
  1474. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1475. > The representation of numbers is similar to that used in most
  1476. > programming languages. A number is represented in base 10 using decimal
  1477. > digits. It contains an integer component that may be prefixed with an
  1478. > optional minus sign, which may be followed by a fraction part and/or an
  1479. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1480. > cannot be represented in the grammar below (such as Infinity and NaN)
  1481. > are not permitted.
  1482. This description includes both integer and floating-point numbers.
  1483. However, C++ allows more precise storage if it is known whether the number
  1484. is a signed integer, an unsigned integer or a floating-point number.
  1485. Therefore, three different types, @ref number_integer_t, @ref
  1486. number_unsigned_t and @ref number_float_t are used.
  1487. To store unsigned integer numbers in C++, a type is defined by the
  1488. template parameter @a NumberUnsignedType which chooses the type to use.
  1489. #### Default type
  1490. With the default values for @a NumberUnsignedType (`uint64_t`), the
  1491. default value for @a number_unsigned_t is:
  1492. @code {.cpp}
  1493. uint64_t
  1494. @endcode
  1495. #### Default behavior
  1496. - The restrictions about leading zeros is not enforced in C++. Instead,
  1497. leading zeros in integer literals lead to an interpretation as octal
  1498. number. Internally, the value will be stored as decimal number. For
  1499. instance, the C++ integer literal `010` will be serialized to `8`.
  1500. During deserialization, leading zeros yield an error.
  1501. - Not-a-number (NaN) values will be serialized to `null`.
  1502. #### Limits
  1503. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  1504. > An implementation may set limits on the range and precision of numbers.
  1505. When the default type is used, the maximal integer number that can be
  1506. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  1507. number that can be stored is `0`. Integer numbers that are out of range
  1508. will yield over/underflow when used in a constructor. During
  1509. deserialization, too large or small integer numbers will be automatically
  1510. be stored as @ref number_integer_t or @ref number_float_t.
  1511. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  1512. > Note that when such software is used, numbers that are integers and are
  1513. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  1514. > that implementations will agree exactly on their numeric values.
  1515. As this range is a subrange (when considered in conjunction with the
  1516. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  1517. this class's integer type is interoperable.
  1518. #### Storage
  1519. Integer number values are stored directly inside a @ref basic_json type.
  1520. @sa @ref number_float_t -- type for number values (floating-point)
  1521. @sa @ref number_integer_t -- type for number values (integer)
  1522. @since version 2.0.0
  1523. */
  1524. using number_unsigned_t = NumberUnsignedType;
  1525. /*!
  1526. @brief a type for a number (floating-point)
  1527. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  1528. > The representation of numbers is similar to that used in most
  1529. > programming languages. A number is represented in base 10 using decimal
  1530. > digits. It contains an integer component that may be prefixed with an
  1531. > optional minus sign, which may be followed by a fraction part and/or an
  1532. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  1533. > cannot be represented in the grammar below (such as Infinity and NaN)
  1534. > are not permitted.
  1535. This description includes both integer and floating-point numbers.
  1536. However, C++ allows more precise storage if it is known whether the number
  1537. is a signed integer, an unsigned integer or a floating-point number.
  1538. Therefore, three different types, @ref number_integer_t, @ref
  1539. number_unsigned_t and @ref number_float_t are used.
  1540. To store floating-point numbers in C++, a type is defined by the template
  1541. parameter @a NumberFloatType which chooses the type to use.
  1542. #### Default type
  1543. With the default values for @a NumberFloatType (`double`), the default
  1544. value for @a number_float_t is:
  1545. @code {.cpp}
  1546. double
  1547. @endcode
  1548. #### Default behavior
  1549. - The restrictions about leading zeros is not enforced in C++. Instead,
  1550. leading zeros in floating-point literals will be ignored. Internally,
  1551. the value will be stored as decimal number. For instance, the C++
  1552. floating-point literal `01.2` will be serialized to `1.2`. During
  1553. deserialization, leading zeros yield an error.
  1554. - Not-a-number (NaN) values will be serialized to `null`.
  1555. #### Limits
  1556. [RFC 7159](http://rfc7159.net/rfc7159) states:
  1557. > This specification allows implementations to set limits on the range and
  1558. > precision of numbers accepted. Since software that implements IEEE
  1559. > 754-2008 binary64 (double precision) numbers is generally available and
  1560. > widely used, good interoperability can be achieved by implementations
  1561. > that expect no more precision or range than these provide, in the sense
  1562. > that implementations will approximate JSON numbers within the expected
  1563. > precision.
  1564. This implementation does exactly follow this approach, as it uses double
  1565. precision floating-point numbers. Note values smaller than
  1566. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  1567. will be stored as NaN internally and be serialized to `null`.
  1568. #### Storage
  1569. Floating-point number values are stored directly inside a @ref basic_json
  1570. type.
  1571. @sa @ref number_integer_t -- type for number values (integer)
  1572. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  1573. @since version 1.0.0
  1574. */
  1575. using number_float_t = NumberFloatType;
  1576. /// @}
  1577. private:
  1578. /// helper for exception-safe object creation
  1579. template<typename T, typename... Args>
  1580. static T* create(Args&& ... args)
  1581. {
  1582. AllocatorType<T> alloc;
  1583. auto deleter = [&](T * object)
  1584. {
  1585. alloc.deallocate(object, 1);
  1586. };
  1587. std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
  1588. alloc.construct(object.get(), std::forward<Args>(args)...);
  1589. assert(object != nullptr);
  1590. return object.release();
  1591. }
  1592. ////////////////////////
  1593. // JSON value storage //
  1594. ////////////////////////
  1595. /*!
  1596. @brief a JSON value
  1597. The actual storage for a JSON value of the @ref basic_json class. This
  1598. union combines the different storage types for the JSON value types
  1599. defined in @ref value_t.
  1600. JSON type | value_t type | used type
  1601. --------- | --------------- | ------------------------
  1602. object | object | pointer to @ref object_t
  1603. array | array | pointer to @ref array_t
  1604. string | string | pointer to @ref string_t
  1605. boolean | boolean | @ref boolean_t
  1606. number | number_integer | @ref number_integer_t
  1607. number | number_unsigned | @ref number_unsigned_t
  1608. number | number_float | @ref number_float_t
  1609. null | null | *no value is stored*
  1610. @note Variable-length types (objects, arrays, and strings) are stored as
  1611. pointers. The size of the union should not exceed 64 bits if the default
  1612. value types are used.
  1613. @since version 1.0.0
  1614. */
  1615. union json_value
  1616. {
  1617. /// object (stored with pointer to save storage)
  1618. object_t* object;
  1619. /// array (stored with pointer to save storage)
  1620. array_t* array;
  1621. /// string (stored with pointer to save storage)
  1622. string_t* string;
  1623. /// boolean
  1624. boolean_t boolean;
  1625. /// number (integer)
  1626. number_integer_t number_integer;
  1627. /// number (unsigned integer)
  1628. number_unsigned_t number_unsigned;
  1629. /// number (floating-point)
  1630. number_float_t number_float;
  1631. /// default constructor (for null values)
  1632. json_value() = default;
  1633. /// constructor for booleans
  1634. json_value(boolean_t v) noexcept : boolean(v) {}
  1635. /// constructor for numbers (integer)
  1636. json_value(number_integer_t v) noexcept : number_integer(v) {}
  1637. /// constructor for numbers (unsigned)
  1638. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  1639. /// constructor for numbers (floating-point)
  1640. json_value(number_float_t v) noexcept : number_float(v) {}
  1641. /// constructor for empty values of a given type
  1642. json_value(value_t t)
  1643. {
  1644. switch (t)
  1645. {
  1646. case value_t::object:
  1647. {
  1648. object = create<object_t>();
  1649. break;
  1650. }
  1651. case value_t::array:
  1652. {
  1653. array = create<array_t>();
  1654. break;
  1655. }
  1656. case value_t::string:
  1657. {
  1658. string = create<string_t>("");
  1659. break;
  1660. }
  1661. case value_t::boolean:
  1662. {
  1663. boolean = boolean_t(false);
  1664. break;
  1665. }
  1666. case value_t::number_integer:
  1667. {
  1668. number_integer = number_integer_t(0);
  1669. break;
  1670. }
  1671. case value_t::number_unsigned:
  1672. {
  1673. number_unsigned = number_unsigned_t(0);
  1674. break;
  1675. }
  1676. case value_t::number_float:
  1677. {
  1678. number_float = number_float_t(0.0);
  1679. break;
  1680. }
  1681. case value_t::null:
  1682. {
  1683. break;
  1684. }
  1685. default:
  1686. {
  1687. if (t == value_t::null)
  1688. {
  1689. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE
  1690. }
  1691. break;
  1692. }
  1693. }
  1694. }
  1695. /// constructor for strings
  1696. json_value(const string_t& value)
  1697. {
  1698. string = create<string_t>(value);
  1699. }
  1700. /// constructor for objects
  1701. json_value(const object_t& value)
  1702. {
  1703. object = create<object_t>(value);
  1704. }
  1705. /// constructor for arrays
  1706. json_value(const array_t& value)
  1707. {
  1708. array = create<array_t>(value);
  1709. }
  1710. };
  1711. /*!
  1712. @brief checks the class invariants
  1713. This function asserts the class invariants. It needs to be called at the
  1714. end of every constructor to make sure that created objects respect the
  1715. invariant. Furthermore, it has to be called each time the type of a JSON
  1716. value is changed, because the invariant expresses a relationship between
  1717. @a m_type and @a m_value.
  1718. */
  1719. void assert_invariant() const
  1720. {
  1721. assert(m_type != value_t::object or m_value.object != nullptr);
  1722. assert(m_type != value_t::array or m_value.array != nullptr);
  1723. assert(m_type != value_t::string or m_value.string != nullptr);
  1724. }
  1725. public:
  1726. //////////////////////////
  1727. // JSON parser callback //
  1728. //////////////////////////
  1729. /*!
  1730. @brief JSON callback events
  1731. This enumeration lists the parser events that can trigger calling a
  1732. callback function of type @ref parser_callback_t during parsing.
  1733. @image html callback_events.png "Example when certain parse events are triggered"
  1734. @since version 1.0.0
  1735. */
  1736. enum class parse_event_t : uint8_t
  1737. {
  1738. /// the parser read `{` and started to process a JSON object
  1739. object_start,
  1740. /// the parser read `}` and finished processing a JSON object
  1741. object_end,
  1742. /// the parser read `[` and started to process a JSON array
  1743. array_start,
  1744. /// the parser read `]` and finished processing a JSON array
  1745. array_end,
  1746. /// the parser read a key of a value in an object
  1747. key,
  1748. /// the parser finished reading a JSON value
  1749. value
  1750. };
  1751. /*!
  1752. @brief per-element parser callback type
  1753. With a parser callback function, the result of parsing a JSON text can be
  1754. influenced. When passed to @ref parse(std::istream&, const
  1755. parser_callback_t) or @ref parse(const CharT, const parser_callback_t),
  1756. it is called on certain events (passed as @ref parse_event_t via parameter
  1757. @a event) with a set recursion depth @a depth and context JSON value
  1758. @a parsed. The return value of the callback function is a boolean
  1759. indicating whether the element that emitted the callback shall be kept or
  1760. not.
  1761. We distinguish six scenarios (determined by the event type) in which the
  1762. callback function can be called. The following table describes the values
  1763. of the parameters @a depth, @a event, and @a parsed.
  1764. parameter @a event | description | parameter @a depth | parameter @a parsed
  1765. ------------------ | ----------- | ------------------ | -------------------
  1766. 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
  1767. 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
  1768. 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
  1769. 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
  1770. 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
  1771. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  1772. @image html callback_events.png "Example when certain parse events are triggered"
  1773. Discarding a value (i.e., returning `false`) has different effects
  1774. depending on the context in which function was called:
  1775. - Discarded values in structured types are skipped. That is, the parser
  1776. will behave as if the discarded value was never read.
  1777. - In case a value outside a structured type is skipped, it is replaced
  1778. with `null`. This case happens if the top-level element is skipped.
  1779. @param[in] depth the depth of the recursion during parsing
  1780. @param[in] event an event of type parse_event_t indicating the context in
  1781. the callback function has been called
  1782. @param[in,out] parsed the current intermediate parse result; note that
  1783. writing to this value has no effect for parse_event_t::key events
  1784. @return Whether the JSON value which called the function during parsing
  1785. should be kept (`true`) or not (`false`). In the latter case, it is either
  1786. skipped completely or replaced by an empty discarded object.
  1787. @sa @ref parse(std::istream&, parser_callback_t) or
  1788. @ref parse(const CharT, const parser_callback_t) for examples
  1789. @since version 1.0.0
  1790. */
  1791. using parser_callback_t = std::function<bool(int depth,
  1792. parse_event_t event,
  1793. basic_json& parsed)>;
  1794. //////////////////
  1795. // constructors //
  1796. //////////////////
  1797. /// @name constructors and destructors
  1798. /// Constructors of class @ref basic_json, copy/move constructor, copy
  1799. /// assignment, static functions creating objects, and the destructor.
  1800. /// @{
  1801. /*!
  1802. @brief create an empty value with a given type
  1803. Create an empty JSON value with a given type. The value will be default
  1804. initialized with an empty value which depends on the type:
  1805. Value type | initial value
  1806. ----------- | -------------
  1807. null | `null`
  1808. boolean | `false`
  1809. string | `""`
  1810. number | `0`
  1811. object | `{}`
  1812. array | `[]`
  1813. @param[in] value_type the type of the value to create
  1814. @complexity Constant.
  1815. @liveexample{The following code shows the constructor for different @ref
  1816. value_t values,basic_json__value_t}
  1817. @since version 1.0.0
  1818. */
  1819. basic_json(const value_t value_type)
  1820. : m_type(value_type), m_value(value_type)
  1821. {
  1822. assert_invariant();
  1823. }
  1824. /*!
  1825. @brief create a null object
  1826. Create a `null` JSON value. It either takes a null pointer as parameter
  1827. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  1828. The passed null pointer itself is not read -- it is only used to choose
  1829. the right constructor.
  1830. @complexity Constant.
  1831. @exceptionsafety No-throw guarantee: this constructor never throws
  1832. exceptions.
  1833. @liveexample{The following code shows the constructor with and without a
  1834. null pointer parameter.,basic_json__nullptr_t}
  1835. @since version 1.0.0
  1836. */
  1837. basic_json(std::nullptr_t = nullptr) noexcept
  1838. : basic_json(value_t::null)
  1839. {
  1840. assert_invariant();
  1841. }
  1842. /*!
  1843. @brief create a JSON value
  1844. This is a "catch all" constructor for all compatible JSON types; that is,
  1845. types for which a `to_json()` method exsits. The constructor forwards the
  1846. parameter @a val to that method (to `json_serializer<U>::to_json` method
  1847. with `U = uncvref_t<CompatibleType>`, to be exact).
  1848. Template type @a CompatibleType includes, but is not limited to, the
  1849. following types:
  1850. - **arrays**: @ref array_t and all kinds of compatible containers such as
  1851. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  1852. `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and
  1853. `unordered_multiset` with a `value_type` from which a @ref basic_json
  1854. value can be constructed.
  1855. - **objects**: @ref object_t and all kinds of compatible associative
  1856. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  1857. and `std::unordered_multimap` with a `key_type` compatible to
  1858. @ref string_t and a `value_type` from which a @ref basic_json value can
  1859. be constructed.
  1860. - **strings**: @ref string_t, string literals, and all compatible string
  1861. containers can be used.
  1862. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  1863. @ref number_float_t, and all convertible number types such as `int`,
  1864. `size_t`, `int64_t`, `float` or `double` can be used.
  1865. - **boolean**: @ref boolean_t / `bool` can be used.
  1866. See the examples below.
  1867. @tparam CompatibleType a type such that:
  1868. - @a CompatibleType is not derived from `std::istream`,
  1869. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  1870. constructors),
  1871. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  1872. @ref json_pointer, @ref iterator, etc ...)
  1873. - @ref @ref json_serializer<U> has a
  1874. `to_json(basic_json_t&, CompatibleType&&)` method
  1875. @tparam U = `uncvref_t<CompatibleType>`
  1876. @param[in] val the value to be forwarded
  1877. @complexity Usually linear in the size of the passed @a val, also
  1878. depending on the implementation of the called `to_json()`
  1879. method.
  1880. @throw what `json_serializer<U>::to_json()` throws
  1881. @liveexample{The following code shows the constructor with several
  1882. compatible types.,basic_json__CompatibleType}
  1883. @since version 2.1.0
  1884. */
  1885. template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
  1886. detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
  1887. not std::is_same<U, basic_json_t>::value and
  1888. not detail::is_basic_json_nested_type<
  1889. basic_json_t, U>::value and
  1890. detail::has_to_json<basic_json, U>::value,
  1891. int> = 0>
  1892. basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
  1893. std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
  1894. {
  1895. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  1896. assert_invariant();
  1897. }
  1898. /*!
  1899. @brief create a container (array or object) from an initializer list
  1900. Creates a JSON value of type array or object from the passed initializer
  1901. list @a init. In case @a type_deduction is `true` (default), the type of
  1902. the JSON value to be created is deducted from the initializer list @a init
  1903. according to the following rules:
  1904. 1. If the list is empty, an empty JSON object value `{}` is created.
  1905. 2. If the list consists of pairs whose first element is a string, a JSON
  1906. object value is created where the first elements of the pairs are
  1907. treated as keys and the second elements are as values.
  1908. 3. In all other cases, an array is created.
  1909. The rules aim to create the best fit between a C++ initializer list and
  1910. JSON values. The rationale is as follows:
  1911. 1. The empty initializer list is written as `{}` which is exactly an empty
  1912. JSON object.
  1913. 2. C++ has now way of describing mapped types other than to list a list of
  1914. pairs. As JSON requires that keys must be of type string, rule 2 is the
  1915. weakest constraint one can pose on initializer lists to interpret them
  1916. as an object.
  1917. 3. In all other cases, the initializer list could not be interpreted as
  1918. JSON object type, so interpreting it as JSON array type is safe.
  1919. With the rules described above, the following JSON values cannot be
  1920. expressed by an initializer list:
  1921. - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
  1922. with an empty initializer list in this case
  1923. - arrays whose elements satisfy rule 2: use @ref
  1924. array(std::initializer_list<basic_json>) with the same initializer list
  1925. in this case
  1926. @note When used without parentheses around an empty initializer list, @ref
  1927. basic_json() is called instead of this function, yielding the JSON null
  1928. value.
  1929. @param[in] init initializer list with JSON values
  1930. @param[in] type_deduction internal parameter; when set to `true`, the type
  1931. of the JSON value is deducted from the initializer list @a init; when set
  1932. to `false`, the type provided via @a manual_type is forced. This mode is
  1933. used by the functions @ref array(std::initializer_list<basic_json>) and
  1934. @ref object(std::initializer_list<basic_json>).
  1935. @param[in] manual_type internal parameter; when @a type_deduction is set
  1936. to `false`, the created JSON value will use the provided type (only @ref
  1937. value_t::array and @ref value_t::object are valid); when @a type_deduction
  1938. is set to `true`, this parameter has no effect
  1939. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  1940. `value_t::object`, but @a init contains an element which is not a pair
  1941. whose first element is a string. In this case, the constructor could not
  1942. create an object. If @a type_deduction would have be `true`, an array
  1943. would have been created. See @ref object(std::initializer_list<basic_json>)
  1944. for an example.
  1945. @complexity Linear in the size of the initializer list @a init.
  1946. @liveexample{The example below shows how JSON values are created from
  1947. initializer lists.,basic_json__list_init_t}
  1948. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  1949. value from an initializer list
  1950. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  1951. value from an initializer list
  1952. @since version 1.0.0
  1953. */
  1954. basic_json(std::initializer_list<basic_json> init,
  1955. bool type_deduction = true,
  1956. value_t manual_type = value_t::array)
  1957. {
  1958. // check if each element is an array with two elements whose first
  1959. // element is a string
  1960. bool is_an_object = std::all_of(init.begin(), init.end(),
  1961. [](const basic_json & element)
  1962. {
  1963. return element.is_array() and element.size() == 2 and element[0].is_string();
  1964. });
  1965. // adjust type if type deduction is not wanted
  1966. if (not type_deduction)
  1967. {
  1968. // if array is wanted, do not create an object though possible
  1969. if (manual_type == value_t::array)
  1970. {
  1971. is_an_object = false;
  1972. }
  1973. // if object is wanted but impossible, throw an exception
  1974. if (manual_type == value_t::object and not is_an_object)
  1975. {
  1976. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  1977. }
  1978. }
  1979. if (is_an_object)
  1980. {
  1981. // the initializer list is a list of pairs -> create object
  1982. m_type = value_t::object;
  1983. m_value = value_t::object;
  1984. std::for_each(init.begin(), init.end(), [this](const basic_json & element)
  1985. {
  1986. m_value.object->emplace(*(element[0].m_value.string), element[1]);
  1987. });
  1988. }
  1989. else
  1990. {
  1991. // the initializer list describes an array -> create array
  1992. m_type = value_t::array;
  1993. m_value.array = create<array_t>(init);
  1994. }
  1995. assert_invariant();
  1996. }
  1997. /*!
  1998. @brief explicitly create an array from an initializer list
  1999. Creates a JSON array value from a given initializer list. That is, given a
  2000. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  2001. initializer list is empty, the empty array `[]` is created.
  2002. @note This function is only needed to express two edge cases that cannot
  2003. be realized with the initializer list constructor (@ref
  2004. basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
  2005. are:
  2006. 1. creating an array whose elements are all pairs whose first element is a
  2007. string -- in this case, the initializer list constructor would create an
  2008. object, taking the first elements as keys
  2009. 2. creating an empty array -- passing the empty initializer list to the
  2010. initializer list constructor yields an empty object
  2011. @param[in] init initializer list with JSON values to create an array from
  2012. (optional)
  2013. @return JSON array value
  2014. @complexity Linear in the size of @a init.
  2015. @liveexample{The following code shows an example for the `array`
  2016. function.,array}
  2017. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  2018. create a JSON value from an initializer list
  2019. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  2020. value from an initializer list
  2021. @since version 1.0.0
  2022. */
  2023. static basic_json array(std::initializer_list<basic_json> init =
  2024. std::initializer_list<basic_json>())
  2025. {
  2026. return basic_json(init, false, value_t::array);
  2027. }
  2028. /*!
  2029. @brief explicitly create an object from an initializer list
  2030. Creates a JSON object value from a given initializer list. The initializer
  2031. lists elements must be pairs, and their first elements must be strings. If
  2032. the initializer list is empty, the empty object `{}` is created.
  2033. @note This function is only added for symmetry reasons. In contrast to the
  2034. related function @ref array(std::initializer_list<basic_json>), there are
  2035. no cases which can only be expressed by this function. That is, any
  2036. initializer list @a init can also be passed to the initializer list
  2037. constructor @ref basic_json(std::initializer_list<basic_json>, bool, value_t).
  2038. @param[in] init initializer list to create an object from (optional)
  2039. @return JSON object value
  2040. @throw type_error.301 if @a init is not a list of pairs whose first
  2041. elements are strings. In this case, no object can be created. When such a
  2042. value is passed to @ref basic_json(std::initializer_list<basic_json>, bool, value_t),
  2043. an array would have been created from the passed initializer list @a init.
  2044. See example below.
  2045. @complexity Linear in the size of @a init.
  2046. @liveexample{The following code shows an example for the `object`
  2047. function.,object}
  2048. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  2049. create a JSON value from an initializer list
  2050. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  2051. value from an initializer list
  2052. @since version 1.0.0
  2053. */
  2054. static basic_json object(std::initializer_list<basic_json> init =
  2055. std::initializer_list<basic_json>())
  2056. {
  2057. return basic_json(init, false, value_t::object);
  2058. }
  2059. /*!
  2060. @brief construct an array with count copies of given value
  2061. Constructs a JSON array value by creating @a cnt copies of a passed value.
  2062. In case @a cnt is `0`, an empty array is created. As postcondition,
  2063. `std::distance(begin(),end()) == cnt` holds.
  2064. @param[in] cnt the number of JSON copies of @a val to create
  2065. @param[in] val the JSON value to copy
  2066. @complexity Linear in @a cnt.
  2067. @liveexample{The following code shows examples for the @ref
  2068. basic_json(size_type\, const basic_json&)
  2069. constructor.,basic_json__size_type_basic_json}
  2070. @since version 1.0.0
  2071. */
  2072. basic_json(size_type cnt, const basic_json& val)
  2073. : m_type(value_t::array)
  2074. {
  2075. m_value.array = create<array_t>(cnt, val);
  2076. assert_invariant();
  2077. }
  2078. /*!
  2079. @brief construct a JSON container given an iterator range
  2080. Constructs the JSON value with the contents of the range `[first, last)`.
  2081. The semantics depends on the different types a JSON value can have:
  2082. - In case of primitive types (number, boolean, or string), @a first must
  2083. be `begin()` and @a last must be `end()`. In this case, the value is
  2084. copied. Otherwise, invalid_iterator.204 is thrown.
  2085. - In case of structured types (array, object), the constructor behaves as
  2086. similar versions for `std::vector`.
  2087. - In case of a null type, invalid_iterator.206 is thrown.
  2088. @tparam InputIT an input iterator type (@ref iterator or @ref
  2089. const_iterator)
  2090. @param[in] first begin of the range to copy from (included)
  2091. @param[in] last end of the range to copy from (excluded)
  2092. @pre Iterators @a first and @a last must be initialized. **This
  2093. precondition is enforced with an assertion.**
  2094. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  2095. checked efficiently. Only certain edge cases are detected; see the
  2096. description of the exceptions below.
  2097. @throw invalid_iterator.201 if iterators @a first and @a last are not
  2098. compatible (i.e., do not belong to the same JSON value). In this case,
  2099. the range `[first, last)` is undefined.
  2100. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  2101. primitive type (number, boolean, or string), but @a first does not point
  2102. to the first element any more. In this case, the range `[first, last)` is
  2103. undefined. See example code below.
  2104. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  2105. null value. In this case, the range `[first, last)` is undefined.
  2106. @complexity Linear in distance between @a first and @a last.
  2107. @liveexample{The example below shows several ways to create JSON values by
  2108. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  2109. @since version 1.0.0
  2110. */
  2111. template<class InputIT, typename std::enable_if<
  2112. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  2113. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  2114. basic_json(InputIT first, InputIT last)
  2115. {
  2116. assert(first.m_object != nullptr);
  2117. assert(last.m_object != nullptr);
  2118. // make sure iterator fits the current value
  2119. if (first.m_object != last.m_object)
  2120. {
  2121. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  2122. }
  2123. // copy type from first iterator
  2124. m_type = first.m_object->m_type;
  2125. // check if iterator range is complete for primitive values
  2126. switch (m_type)
  2127. {
  2128. case value_t::boolean:
  2129. case value_t::number_float:
  2130. case value_t::number_integer:
  2131. case value_t::number_unsigned:
  2132. case value_t::string:
  2133. {
  2134. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  2135. {
  2136. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  2137. }
  2138. break;
  2139. }
  2140. default:
  2141. {
  2142. break;
  2143. }
  2144. }
  2145. switch (m_type)
  2146. {
  2147. case value_t::number_integer:
  2148. {
  2149. m_value.number_integer = first.m_object->m_value.number_integer;
  2150. break;
  2151. }
  2152. case value_t::number_unsigned:
  2153. {
  2154. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  2155. break;
  2156. }
  2157. case value_t::number_float:
  2158. {
  2159. m_value.number_float = first.m_object->m_value.number_float;
  2160. break;
  2161. }
  2162. case value_t::boolean:
  2163. {
  2164. m_value.boolean = first.m_object->m_value.boolean;
  2165. break;
  2166. }
  2167. case value_t::string:
  2168. {
  2169. m_value = *first.m_object->m_value.string;
  2170. break;
  2171. }
  2172. case value_t::object:
  2173. {
  2174. m_value.object = create<object_t>(first.m_it.object_iterator,
  2175. last.m_it.object_iterator);
  2176. break;
  2177. }
  2178. case value_t::array:
  2179. {
  2180. m_value.array = create<array_t>(first.m_it.array_iterator,
  2181. last.m_it.array_iterator);
  2182. break;
  2183. }
  2184. default:
  2185. {
  2186. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  2187. first.m_object->type_name()));
  2188. }
  2189. }
  2190. assert_invariant();
  2191. }
  2192. ///////////////////////////////////////
  2193. // other constructors and destructor //
  2194. ///////////////////////////////////////
  2195. /*!
  2196. @brief copy constructor
  2197. Creates a copy of a given JSON value.
  2198. @param[in] other the JSON value to copy
  2199. @complexity Linear in the size of @a other.
  2200. @requirement This function helps `basic_json` satisfying the
  2201. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2202. requirements:
  2203. - The complexity is linear.
  2204. - As postcondition, it holds: `other == basic_json(other)`.
  2205. @liveexample{The following code shows an example for the copy
  2206. constructor.,basic_json__basic_json}
  2207. @since version 1.0.0
  2208. */
  2209. basic_json(const basic_json& other)
  2210. : m_type(other.m_type)
  2211. {
  2212. // check of passed value is valid
  2213. other.assert_invariant();
  2214. switch (m_type)
  2215. {
  2216. case value_t::object:
  2217. {
  2218. m_value = *other.m_value.object;
  2219. break;
  2220. }
  2221. case value_t::array:
  2222. {
  2223. m_value = *other.m_value.array;
  2224. break;
  2225. }
  2226. case value_t::string:
  2227. {
  2228. m_value = *other.m_value.string;
  2229. break;
  2230. }
  2231. case value_t::boolean:
  2232. {
  2233. m_value = other.m_value.boolean;
  2234. break;
  2235. }
  2236. case value_t::number_integer:
  2237. {
  2238. m_value = other.m_value.number_integer;
  2239. break;
  2240. }
  2241. case value_t::number_unsigned:
  2242. {
  2243. m_value = other.m_value.number_unsigned;
  2244. break;
  2245. }
  2246. case value_t::number_float:
  2247. {
  2248. m_value = other.m_value.number_float;
  2249. break;
  2250. }
  2251. default:
  2252. {
  2253. break;
  2254. }
  2255. }
  2256. assert_invariant();
  2257. }
  2258. /*!
  2259. @brief move constructor
  2260. Move constructor. Constructs a JSON value with the contents of the given
  2261. value @a other using move semantics. It "steals" the resources from @a
  2262. other and leaves it as JSON null value.
  2263. @param[in,out] other value to move to this object
  2264. @post @a other is a JSON null value
  2265. @complexity Constant.
  2266. @liveexample{The code below shows the move constructor explicitly called
  2267. via std::move.,basic_json__moveconstructor}
  2268. @since version 1.0.0
  2269. */
  2270. basic_json(basic_json&& other) noexcept
  2271. : m_type(std::move(other.m_type)),
  2272. m_value(std::move(other.m_value))
  2273. {
  2274. // check that passed value is valid
  2275. other.assert_invariant();
  2276. // invalidate payload
  2277. other.m_type = value_t::null;
  2278. other.m_value = {};
  2279. assert_invariant();
  2280. }
  2281. /*!
  2282. @brief copy assignment
  2283. Copy assignment operator. Copies a JSON value via the "copy and swap"
  2284. strategy: It is expressed in terms of the copy constructor, destructor,
  2285. and the swap() member function.
  2286. @param[in] other value to copy from
  2287. @complexity Linear.
  2288. @requirement This function helps `basic_json` satisfying the
  2289. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2290. requirements:
  2291. - The complexity is linear.
  2292. @liveexample{The code below shows and example for the copy assignment. It
  2293. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  2294. copy of `a` (which is the null value after the swap) is
  2295. destroyed.,basic_json__copyassignment}
  2296. @since version 1.0.0
  2297. */
  2298. reference& operator=(basic_json other) noexcept (
  2299. std::is_nothrow_move_constructible<value_t>::value and
  2300. std::is_nothrow_move_assignable<value_t>::value and
  2301. std::is_nothrow_move_constructible<json_value>::value and
  2302. std::is_nothrow_move_assignable<json_value>::value
  2303. )
  2304. {
  2305. // check that passed value is valid
  2306. other.assert_invariant();
  2307. using std::swap;
  2308. swap(m_type, other.m_type);
  2309. swap(m_value, other.m_value);
  2310. assert_invariant();
  2311. return *this;
  2312. }
  2313. /*!
  2314. @brief destructor
  2315. Destroys the JSON value and frees all allocated memory.
  2316. @complexity Linear.
  2317. @requirement This function helps `basic_json` satisfying the
  2318. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  2319. requirements:
  2320. - The complexity is linear.
  2321. - All stored elements are destroyed and all memory is freed.
  2322. @since version 1.0.0
  2323. */
  2324. ~basic_json()
  2325. {
  2326. assert_invariant();
  2327. switch (m_type)
  2328. {
  2329. case value_t::object:
  2330. {
  2331. AllocatorType<object_t> alloc;
  2332. alloc.destroy(m_value.object);
  2333. alloc.deallocate(m_value.object, 1);
  2334. break;
  2335. }
  2336. case value_t::array:
  2337. {
  2338. AllocatorType<array_t> alloc;
  2339. alloc.destroy(m_value.array);
  2340. alloc.deallocate(m_value.array, 1);
  2341. break;
  2342. }
  2343. case value_t::string:
  2344. {
  2345. AllocatorType<string_t> alloc;
  2346. alloc.destroy(m_value.string);
  2347. alloc.deallocate(m_value.string, 1);
  2348. break;
  2349. }
  2350. default:
  2351. {
  2352. // all other types need no specific destructor
  2353. break;
  2354. }
  2355. }
  2356. }
  2357. /// @}
  2358. public:
  2359. ///////////////////////
  2360. // object inspection //
  2361. ///////////////////////
  2362. /// @name object inspection
  2363. /// Functions to inspect the type of a JSON value.
  2364. /// @{
  2365. /*!
  2366. @brief serialization
  2367. Serialization function for JSON values. The function tries to mimic
  2368. Python's `json.dumps()` function, and currently supports its @a indent
  2369. parameter.
  2370. @param[in] indent If indent is nonnegative, then array elements and object
  2371. members will be pretty-printed with that indent level. An indent level of
  2372. `0` will only insert newlines. `-1` (the default) selects the most compact
  2373. representation.
  2374. @return string containing the serialization of the JSON value
  2375. @complexity Linear.
  2376. @liveexample{The following example shows the effect of different @a indent
  2377. parameters to the result of the serialization.,dump}
  2378. @see https://docs.python.org/2/library/json.html#json.dump
  2379. @since version 1.0.0
  2380. */
  2381. string_t dump(const int indent = -1) const
  2382. {
  2383. std::stringstream ss;
  2384. serializer s(ss);
  2385. if (indent >= 0)
  2386. {
  2387. s.dump(*this, true, static_cast<unsigned int>(indent));
  2388. }
  2389. else
  2390. {
  2391. s.dump(*this, false, 0);
  2392. }
  2393. return ss.str();
  2394. }
  2395. /*!
  2396. @brief return the type of the JSON value (explicit)
  2397. Return the type of the JSON value as a value from the @ref value_t
  2398. enumeration.
  2399. @return the type of the JSON value
  2400. @complexity Constant.
  2401. @exceptionsafety No-throw guarantee: this member function never throws
  2402. exceptions.
  2403. @liveexample{The following code exemplifies `type()` for all JSON
  2404. types.,type}
  2405. @since version 1.0.0
  2406. */
  2407. constexpr value_t type() const noexcept
  2408. {
  2409. return m_type;
  2410. }
  2411. /*!
  2412. @brief return whether type is primitive
  2413. This function returns true iff the JSON type is primitive (string, number,
  2414. boolean, or null).
  2415. @return `true` if type is primitive (string, number, boolean, or null),
  2416. `false` otherwise.
  2417. @complexity Constant.
  2418. @exceptionsafety No-throw guarantee: this member function never throws
  2419. exceptions.
  2420. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  2421. types.,is_primitive}
  2422. @sa @ref is_structured() -- returns whether JSON value is structured
  2423. @sa @ref is_null() -- returns whether JSON value is `null`
  2424. @sa @ref is_string() -- returns whether JSON value is a string
  2425. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  2426. @sa @ref is_number() -- returns whether JSON value is a number
  2427. @since version 1.0.0
  2428. */
  2429. constexpr bool is_primitive() const noexcept
  2430. {
  2431. return is_null() or is_string() or is_boolean() or is_number();
  2432. }
  2433. /*!
  2434. @brief return whether type is structured
  2435. This function returns true iff the JSON type is structured (array or
  2436. object).
  2437. @return `true` if type is structured (array or object), `false` otherwise.
  2438. @complexity Constant.
  2439. @exceptionsafety No-throw guarantee: this member function never throws
  2440. exceptions.
  2441. @liveexample{The following code exemplifies `is_structured()` for all JSON
  2442. types.,is_structured}
  2443. @sa @ref is_primitive() -- returns whether value is primitive
  2444. @sa @ref is_array() -- returns whether value is an array
  2445. @sa @ref is_object() -- returns whether value is an object
  2446. @since version 1.0.0
  2447. */
  2448. constexpr bool is_structured() const noexcept
  2449. {
  2450. return is_array() or is_object();
  2451. }
  2452. /*!
  2453. @brief return whether value is null
  2454. This function returns true iff the JSON value is null.
  2455. @return `true` if type is null, `false` otherwise.
  2456. @complexity Constant.
  2457. @exceptionsafety No-throw guarantee: this member function never throws
  2458. exceptions.
  2459. @liveexample{The following code exemplifies `is_null()` for all JSON
  2460. types.,is_null}
  2461. @since version 1.0.0
  2462. */
  2463. constexpr bool is_null() const noexcept
  2464. {
  2465. return m_type == value_t::null;
  2466. }
  2467. /*!
  2468. @brief return whether value is a boolean
  2469. This function returns true iff the JSON value is a boolean.
  2470. @return `true` if type is boolean, `false` otherwise.
  2471. @complexity Constant.
  2472. @exceptionsafety No-throw guarantee: this member function never throws
  2473. exceptions.
  2474. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  2475. types.,is_boolean}
  2476. @since version 1.0.0
  2477. */
  2478. constexpr bool is_boolean() const noexcept
  2479. {
  2480. return m_type == value_t::boolean;
  2481. }
  2482. /*!
  2483. @brief return whether value is a number
  2484. This function returns true iff the JSON value is a number. This includes
  2485. both integer and floating-point values.
  2486. @return `true` if type is number (regardless whether integer, unsigned
  2487. integer or floating-type), `false` otherwise.
  2488. @complexity Constant.
  2489. @exceptionsafety No-throw guarantee: this member function never throws
  2490. exceptions.
  2491. @liveexample{The following code exemplifies `is_number()` for all JSON
  2492. types.,is_number}
  2493. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  2494. integer number
  2495. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2496. number
  2497. @sa @ref is_number_float() -- check if value is a floating-point number
  2498. @since version 1.0.0
  2499. */
  2500. constexpr bool is_number() const noexcept
  2501. {
  2502. return is_number_integer() or is_number_float();
  2503. }
  2504. /*!
  2505. @brief return whether value is an integer number
  2506. This function returns true iff the JSON value is an integer or unsigned
  2507. integer number. This excludes floating-point values.
  2508. @return `true` if type is an integer or unsigned integer number, `false`
  2509. otherwise.
  2510. @complexity Constant.
  2511. @exceptionsafety No-throw guarantee: this member function never throws
  2512. exceptions.
  2513. @liveexample{The following code exemplifies `is_number_integer()` for all
  2514. JSON types.,is_number_integer}
  2515. @sa @ref is_number() -- check if value is a number
  2516. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2517. number
  2518. @sa @ref is_number_float() -- check if value is a floating-point number
  2519. @since version 1.0.0
  2520. */
  2521. constexpr bool is_number_integer() const noexcept
  2522. {
  2523. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  2524. }
  2525. /*!
  2526. @brief return whether value is an unsigned integer number
  2527. This function returns true iff the JSON value is an unsigned integer
  2528. number. This excludes floating-point and (signed) integer values.
  2529. @return `true` if type is an unsigned integer number, `false` otherwise.
  2530. @complexity Constant.
  2531. @exceptionsafety No-throw guarantee: this member function never throws
  2532. exceptions.
  2533. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  2534. JSON types.,is_number_unsigned}
  2535. @sa @ref is_number() -- check if value is a number
  2536. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  2537. integer number
  2538. @sa @ref is_number_float() -- check if value is a floating-point number
  2539. @since version 2.0.0
  2540. */
  2541. constexpr bool is_number_unsigned() const noexcept
  2542. {
  2543. return m_type == value_t::number_unsigned;
  2544. }
  2545. /*!
  2546. @brief return whether value is a floating-point number
  2547. This function returns true iff the JSON value is a floating-point number.
  2548. This excludes integer and unsigned integer values.
  2549. @return `true` if type is a floating-point number, `false` otherwise.
  2550. @complexity Constant.
  2551. @exceptionsafety No-throw guarantee: this member function never throws
  2552. exceptions.
  2553. @liveexample{The following code exemplifies `is_number_float()` for all
  2554. JSON types.,is_number_float}
  2555. @sa @ref is_number() -- check if value is number
  2556. @sa @ref is_number_integer() -- check if value is an integer number
  2557. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  2558. number
  2559. @since version 1.0.0
  2560. */
  2561. constexpr bool is_number_float() const noexcept
  2562. {
  2563. return m_type == value_t::number_float;
  2564. }
  2565. /*!
  2566. @brief return whether value is an object
  2567. This function returns true iff the JSON value is an object.
  2568. @return `true` if type is object, `false` otherwise.
  2569. @complexity Constant.
  2570. @exceptionsafety No-throw guarantee: this member function never throws
  2571. exceptions.
  2572. @liveexample{The following code exemplifies `is_object()` for all JSON
  2573. types.,is_object}
  2574. @since version 1.0.0
  2575. */
  2576. constexpr bool is_object() const noexcept
  2577. {
  2578. return m_type == value_t::object;
  2579. }
  2580. /*!
  2581. @brief return whether value is an array
  2582. This function returns true iff the JSON value is an array.
  2583. @return `true` if type is array, `false` otherwise.
  2584. @complexity Constant.
  2585. @exceptionsafety No-throw guarantee: this member function never throws
  2586. exceptions.
  2587. @liveexample{The following code exemplifies `is_array()` for all JSON
  2588. types.,is_array}
  2589. @since version 1.0.0
  2590. */
  2591. constexpr bool is_array() const noexcept
  2592. {
  2593. return m_type == value_t::array;
  2594. }
  2595. /*!
  2596. @brief return whether value is a string
  2597. This function returns true iff the JSON value is a string.
  2598. @return `true` if type is string, `false` otherwise.
  2599. @complexity Constant.
  2600. @exceptionsafety No-throw guarantee: this member function never throws
  2601. exceptions.
  2602. @liveexample{The following code exemplifies `is_string()` for all JSON
  2603. types.,is_string}
  2604. @since version 1.0.0
  2605. */
  2606. constexpr bool is_string() const noexcept
  2607. {
  2608. return m_type == value_t::string;
  2609. }
  2610. /*!
  2611. @brief return whether value is discarded
  2612. This function returns true iff the JSON value was discarded during parsing
  2613. with a callback function (see @ref parser_callback_t).
  2614. @note This function will always be `false` for JSON values after parsing.
  2615. That is, discarded values can only occur during parsing, but will be
  2616. removed when inside a structured value or replaced by null in other cases.
  2617. @return `true` if type is discarded, `false` otherwise.
  2618. @complexity Constant.
  2619. @exceptionsafety No-throw guarantee: this member function never throws
  2620. exceptions.
  2621. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  2622. types.,is_discarded}
  2623. @since version 1.0.0
  2624. */
  2625. constexpr bool is_discarded() const noexcept
  2626. {
  2627. return m_type == value_t::discarded;
  2628. }
  2629. /*!
  2630. @brief return the type of the JSON value (implicit)
  2631. Implicitly return the type of the JSON value as a value from the @ref
  2632. value_t enumeration.
  2633. @return the type of the JSON value
  2634. @complexity Constant.
  2635. @exceptionsafety No-throw guarantee: this member function never throws
  2636. exceptions.
  2637. @liveexample{The following code exemplifies the @ref value_t operator for
  2638. all JSON types.,operator__value_t}
  2639. @since version 1.0.0
  2640. */
  2641. constexpr operator value_t() const noexcept
  2642. {
  2643. return m_type;
  2644. }
  2645. /// @}
  2646. private:
  2647. //////////////////
  2648. // value access //
  2649. //////////////////
  2650. /// get a boolean (explicit)
  2651. boolean_t get_impl(boolean_t* /*unused*/) const
  2652. {
  2653. if (is_boolean())
  2654. {
  2655. return m_value.boolean;
  2656. }
  2657. JSON_THROW(type_error::create(302, "type must be boolean, but is " + type_name()));
  2658. }
  2659. /// get a pointer to the value (object)
  2660. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  2661. {
  2662. return is_object() ? m_value.object : nullptr;
  2663. }
  2664. /// get a pointer to the value (object)
  2665. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  2666. {
  2667. return is_object() ? m_value.object : nullptr;
  2668. }
  2669. /// get a pointer to the value (array)
  2670. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  2671. {
  2672. return is_array() ? m_value.array : nullptr;
  2673. }
  2674. /// get a pointer to the value (array)
  2675. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  2676. {
  2677. return is_array() ? m_value.array : nullptr;
  2678. }
  2679. /// get a pointer to the value (string)
  2680. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  2681. {
  2682. return is_string() ? m_value.string : nullptr;
  2683. }
  2684. /// get a pointer to the value (string)
  2685. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  2686. {
  2687. return is_string() ? m_value.string : nullptr;
  2688. }
  2689. /// get a pointer to the value (boolean)
  2690. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  2691. {
  2692. return is_boolean() ? &m_value.boolean : nullptr;
  2693. }
  2694. /// get a pointer to the value (boolean)
  2695. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  2696. {
  2697. return is_boolean() ? &m_value.boolean : nullptr;
  2698. }
  2699. /// get a pointer to the value (integer number)
  2700. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  2701. {
  2702. return is_number_integer() ? &m_value.number_integer : nullptr;
  2703. }
  2704. /// get a pointer to the value (integer number)
  2705. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  2706. {
  2707. return is_number_integer() ? &m_value.number_integer : nullptr;
  2708. }
  2709. /// get a pointer to the value (unsigned number)
  2710. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  2711. {
  2712. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2713. }
  2714. /// get a pointer to the value (unsigned number)
  2715. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  2716. {
  2717. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2718. }
  2719. /// get a pointer to the value (floating-point number)
  2720. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  2721. {
  2722. return is_number_float() ? &m_value.number_float : nullptr;
  2723. }
  2724. /// get a pointer to the value (floating-point number)
  2725. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  2726. {
  2727. return is_number_float() ? &m_value.number_float : nullptr;
  2728. }
  2729. /*!
  2730. @brief helper function to implement get_ref()
  2731. This funcion helps to implement get_ref() without code duplication for
  2732. const and non-const overloads
  2733. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  2734. @throw type_error.303 if ReferenceType does not match underlying value
  2735. type of the current JSON
  2736. */
  2737. template<typename ReferenceType, typename ThisType>
  2738. static ReferenceType get_ref_impl(ThisType& obj)
  2739. {
  2740. // helper type
  2741. using PointerType = typename std::add_pointer<ReferenceType>::type;
  2742. // delegate the call to get_ptr<>()
  2743. auto ptr = obj.template get_ptr<PointerType>();
  2744. if (ptr != nullptr)
  2745. {
  2746. return *ptr;
  2747. }
  2748. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + obj.type_name()));
  2749. }
  2750. public:
  2751. /// @name value access
  2752. /// Direct access to the stored value of a JSON value.
  2753. /// @{
  2754. /*!
  2755. @brief get special-case overload
  2756. This overloads avoids a lot of template boilerplate, it can be seen as the
  2757. identity method
  2758. @tparam BasicJsonType == @ref basic_json
  2759. @return a copy of *this
  2760. @complexity Constant.
  2761. @since version 2.1.0
  2762. */
  2763. template <
  2764. typename BasicJsonType,
  2765. detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type,
  2766. basic_json_t>::value,
  2767. int> = 0 >
  2768. basic_json get() const
  2769. {
  2770. return *this;
  2771. }
  2772. /*!
  2773. @brief get a value (explicit)
  2774. Explicit type conversion between the JSON value and a compatible value
  2775. which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  2776. and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  2777. The value is converted by calling the @ref json_serializer<ValueType>
  2778. `from_json()` method.
  2779. The function is equivalent to executing
  2780. @code {.cpp}
  2781. ValueType ret;
  2782. JSONSerializer<ValueType>::from_json(*this, ret);
  2783. return ret;
  2784. @endcode
  2785. This overloads is chosen if:
  2786. - @a ValueType is not @ref basic_json,
  2787. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2788. `void from_json(const @ref basic_json&, ValueType&)`, and
  2789. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  2790. the form `ValueType from_json(const @ref basic_json&)`
  2791. @tparam ValueTypeCV the provided value type
  2792. @tparam ValueType the returned value type
  2793. @return copy of the JSON value, converted to @a ValueType
  2794. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2795. @liveexample{The example below shows several conversions from JSON values
  2796. to other types. There a few things to note: (1) Floating-point numbers can
  2797. be converted to integers\, (2) A JSON array can be converted to a standard
  2798. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2799. associative containers such as `std::unordered_map<std::string\,
  2800. json>`.,get__ValueType_const}
  2801. @since version 2.1.0
  2802. */
  2803. template <
  2804. typename ValueTypeCV,
  2805. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2806. detail::enable_if_t <
  2807. not std::is_same<basic_json_t, ValueType>::value and
  2808. detail::has_from_json<basic_json_t, ValueType>::value and
  2809. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  2810. int > = 0 >
  2811. ValueType get() const noexcept(noexcept(
  2812. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  2813. {
  2814. // we cannot static_assert on ValueTypeCV being non-const, because
  2815. // there is support for get<const basic_json_t>(), which is why we
  2816. // still need the uncvref
  2817. static_assert(not std::is_reference<ValueTypeCV>::value,
  2818. "get() cannot be used with reference types, you might want to use get_ref()");
  2819. static_assert(std::is_default_constructible<ValueType>::value,
  2820. "types must be DefaultConstructible when used with get()");
  2821. ValueType ret;
  2822. JSONSerializer<ValueType>::from_json(*this, ret);
  2823. return ret;
  2824. }
  2825. /*!
  2826. @brief get a value (explicit); special case
  2827. Explicit type conversion between the JSON value and a compatible value
  2828. which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  2829. and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  2830. The value is converted by calling the @ref json_serializer<ValueType>
  2831. `from_json()` method.
  2832. The function is equivalent to executing
  2833. @code {.cpp}
  2834. return JSONSerializer<ValueTypeCV>::from_json(*this);
  2835. @endcode
  2836. This overloads is chosen if:
  2837. - @a ValueType is not @ref basic_json and
  2838. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  2839. `ValueType from_json(const @ref basic_json&)`
  2840. @note If @ref json_serializer<ValueType> has both overloads of
  2841. `from_json()`, this one is chosen.
  2842. @tparam ValueTypeCV the provided value type
  2843. @tparam ValueType the returned value type
  2844. @return copy of the JSON value, converted to @a ValueType
  2845. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  2846. @since version 2.1.0
  2847. */
  2848. template <
  2849. typename ValueTypeCV,
  2850. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  2851. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  2852. detail::has_non_default_from_json<basic_json_t,
  2853. ValueType>::value, int> = 0 >
  2854. ValueType get() const noexcept(noexcept(
  2855. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  2856. {
  2857. static_assert(not std::is_reference<ValueTypeCV>::value,
  2858. "get() cannot be used with reference types, you might want to use get_ref()");
  2859. return JSONSerializer<ValueTypeCV>::from_json(*this);
  2860. }
  2861. /*!
  2862. @brief get a pointer value (explicit)
  2863. Explicit pointer access to the internally stored JSON value. No copies are
  2864. made.
  2865. @warning The pointer becomes invalid if the underlying JSON object
  2866. changes.
  2867. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2868. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2869. @ref number_unsigned_t, or @ref number_float_t.
  2870. @return pointer to the internally stored JSON value if the requested
  2871. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2872. @complexity Constant.
  2873. @liveexample{The example below shows how pointers to internal values of a
  2874. JSON value can be requested. Note that no type conversions are made and a
  2875. `nullptr` is returned if the value and the requested pointer type does not
  2876. match.,get__PointerType}
  2877. @sa @ref get_ptr() for explicit pointer-member access
  2878. @since version 1.0.0
  2879. */
  2880. template<typename PointerType, typename std::enable_if<
  2881. std::is_pointer<PointerType>::value, int>::type = 0>
  2882. PointerType get() noexcept
  2883. {
  2884. // delegate the call to get_ptr
  2885. return get_ptr<PointerType>();
  2886. }
  2887. /*!
  2888. @brief get a pointer value (explicit)
  2889. @copydoc get()
  2890. */
  2891. template<typename PointerType, typename std::enable_if<
  2892. std::is_pointer<PointerType>::value, int>::type = 0>
  2893. constexpr const PointerType get() const noexcept
  2894. {
  2895. // delegate the call to get_ptr
  2896. return get_ptr<PointerType>();
  2897. }
  2898. /*!
  2899. @brief get a pointer value (implicit)
  2900. Implicit pointer access to the internally stored JSON value. No copies are
  2901. made.
  2902. @warning Writing data to the pointee of the result yields an undefined
  2903. state.
  2904. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2905. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2906. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  2907. assertion.
  2908. @return pointer to the internally stored JSON value if the requested
  2909. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2910. @complexity Constant.
  2911. @liveexample{The example below shows how pointers to internal values of a
  2912. JSON value can be requested. Note that no type conversions are made and a
  2913. `nullptr` is returned if the value and the requested pointer type does not
  2914. match.,get_ptr}
  2915. @since version 1.0.0
  2916. */
  2917. template<typename PointerType, typename std::enable_if<
  2918. std::is_pointer<PointerType>::value, int>::type = 0>
  2919. PointerType get_ptr() noexcept
  2920. {
  2921. // get the type of the PointerType (remove pointer and const)
  2922. using pointee_t = typename std::remove_const<typename
  2923. std::remove_pointer<typename
  2924. std::remove_const<PointerType>::type>::type>::type;
  2925. // make sure the type matches the allowed types
  2926. static_assert(
  2927. std::is_same<object_t, pointee_t>::value
  2928. or std::is_same<array_t, pointee_t>::value
  2929. or std::is_same<string_t, pointee_t>::value
  2930. or std::is_same<boolean_t, pointee_t>::value
  2931. or std::is_same<number_integer_t, pointee_t>::value
  2932. or std::is_same<number_unsigned_t, pointee_t>::value
  2933. or std::is_same<number_float_t, pointee_t>::value
  2934. , "incompatible pointer type");
  2935. // delegate the call to get_impl_ptr<>()
  2936. return get_impl_ptr(static_cast<PointerType>(nullptr));
  2937. }
  2938. /*!
  2939. @brief get a pointer value (implicit)
  2940. @copydoc get_ptr()
  2941. */
  2942. template<typename PointerType, typename std::enable_if<
  2943. std::is_pointer<PointerType>::value and
  2944. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  2945. constexpr const PointerType get_ptr() const noexcept
  2946. {
  2947. // get the type of the PointerType (remove pointer and const)
  2948. using pointee_t = typename std::remove_const<typename
  2949. std::remove_pointer<typename
  2950. std::remove_const<PointerType>::type>::type>::type;
  2951. // make sure the type matches the allowed types
  2952. static_assert(
  2953. std::is_same<object_t, pointee_t>::value
  2954. or std::is_same<array_t, pointee_t>::value
  2955. or std::is_same<string_t, pointee_t>::value
  2956. or std::is_same<boolean_t, pointee_t>::value
  2957. or std::is_same<number_integer_t, pointee_t>::value
  2958. or std::is_same<number_unsigned_t, pointee_t>::value
  2959. or std::is_same<number_float_t, pointee_t>::value
  2960. , "incompatible pointer type");
  2961. // delegate the call to get_impl_ptr<>() const
  2962. return get_impl_ptr(static_cast<const PointerType>(nullptr));
  2963. }
  2964. /*!
  2965. @brief get a reference value (implicit)
  2966. Implicit reference access to the internally stored JSON value. No copies
  2967. are made.
  2968. @warning Writing data to the referee of the result yields an undefined
  2969. state.
  2970. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  2971. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  2972. @ref number_float_t. Enforced by static assertion.
  2973. @return reference to the internally stored JSON value if the requested
  2974. reference type @a ReferenceType fits to the JSON value; throws
  2975. type_error.303 otherwise
  2976. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  2977. with the stored JSON value; see example below
  2978. @complexity Constant.
  2979. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  2980. @since version 1.1.0
  2981. */
  2982. template<typename ReferenceType, typename std::enable_if<
  2983. std::is_reference<ReferenceType>::value, int>::type = 0>
  2984. ReferenceType get_ref()
  2985. {
  2986. // delegate call to get_ref_impl
  2987. return get_ref_impl<ReferenceType>(*this);
  2988. }
  2989. /*!
  2990. @brief get a reference value (implicit)
  2991. @copydoc get_ref()
  2992. */
  2993. template<typename ReferenceType, typename std::enable_if<
  2994. std::is_reference<ReferenceType>::value and
  2995. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  2996. ReferenceType get_ref() const
  2997. {
  2998. // delegate call to get_ref_impl
  2999. return get_ref_impl<ReferenceType>(*this);
  3000. }
  3001. /*!
  3002. @brief get a value (implicit)
  3003. Implicit type conversion between the JSON value and a compatible value.
  3004. The call is realized by calling @ref get() const.
  3005. @tparam ValueType non-pointer type compatible to the JSON value, for
  3006. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  3007. `std::vector` types for JSON arrays. The character type of @ref string_t
  3008. as well as an initializer list of this type is excluded to avoid
  3009. ambiguities as these types implicitly convert to `std::string`.
  3010. @return copy of the JSON value, converted to type @a ValueType
  3011. @throw type_error.302 in case passed type @a ValueType is incompatible
  3012. to the JSON value type (e.g., the JSON value is of type boolean, but a
  3013. string is requested); see example below
  3014. @complexity Linear in the size of the JSON value.
  3015. @liveexample{The example below shows several conversions from JSON values
  3016. to other types. There a few things to note: (1) Floating-point numbers can
  3017. be converted to integers\, (2) A JSON array can be converted to a standard
  3018. `std::vector<short>`\, (3) A JSON object can be converted to C++
  3019. associative containers such as `std::unordered_map<std::string\,
  3020. json>`.,operator__ValueType}
  3021. @since version 1.0.0
  3022. */
  3023. template < typename ValueType, typename std::enable_if <
  3024. not std::is_pointer<ValueType>::value and
  3025. not std::is_same<ValueType, typename string_t::value_type>::value
  3026. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  3027. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  3028. #endif
  3029. #if defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1 // fix for issue #464
  3030. and not std::is_same<ValueType, typename std::string_view>::value
  3031. #endif
  3032. , int >::type = 0 >
  3033. operator ValueType() const
  3034. {
  3035. // delegate the call to get<>() const
  3036. return get<ValueType>();
  3037. }
  3038. /// @}
  3039. ////////////////////
  3040. // element access //
  3041. ////////////////////
  3042. /// @name element access
  3043. /// Access to the JSON value.
  3044. /// @{
  3045. /*!
  3046. @brief access specified array element with bounds checking
  3047. Returns a reference to the element at specified location @a idx, with
  3048. bounds checking.
  3049. @param[in] idx index of the element to access
  3050. @return reference to the element at index @a idx
  3051. @throw type_error.304 if the JSON value is not an array; in this case,
  3052. calling `at` with an index makes no sense. See example below.
  3053. @throw out_of_range.401 if the index @a idx is out of range of the array;
  3054. that is, `idx >= size()`. See example below.
  3055. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3056. changes in the JSON value.
  3057. @complexity Constant.
  3058. @since version 1.0.0
  3059. @liveexample{The example below shows how array elements can be read and
  3060. written using `at()`. It also demonstrates the different exceptions that
  3061. can be thrown.,at__size_type}
  3062. */
  3063. reference at(size_type idx)
  3064. {
  3065. // at only works for arrays
  3066. if (is_array())
  3067. {
  3068. JSON_TRY
  3069. {
  3070. return m_value.array->at(idx);
  3071. }
  3072. JSON_CATCH (std::out_of_range&)
  3073. {
  3074. // create better exception explanation
  3075. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3076. }
  3077. }
  3078. else
  3079. {
  3080. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3081. }
  3082. }
  3083. /*!
  3084. @brief access specified array element with bounds checking
  3085. Returns a const reference to the element at specified location @a idx,
  3086. with bounds checking.
  3087. @param[in] idx index of the element to access
  3088. @return const reference to the element at index @a idx
  3089. @throw type_error.304 if the JSON value is not an array; in this case,
  3090. calling `at` with an index makes no sense. See example below.
  3091. @throw out_of_range.401 if the index @a idx is out of range of the array;
  3092. that is, `idx >= size()`. See example below.
  3093. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3094. changes in the JSON value.
  3095. @complexity Constant.
  3096. @since version 1.0.0
  3097. @liveexample{The example below shows how array elements can be read using
  3098. `at()`. It also demonstrates the different exceptions that can be thrown.,
  3099. at__size_type_const}
  3100. */
  3101. const_reference at(size_type idx) const
  3102. {
  3103. // at only works for arrays
  3104. if (is_array())
  3105. {
  3106. JSON_TRY
  3107. {
  3108. return m_value.array->at(idx);
  3109. }
  3110. JSON_CATCH (std::out_of_range&)
  3111. {
  3112. // create better exception explanation
  3113. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3114. }
  3115. }
  3116. else
  3117. {
  3118. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3119. }
  3120. }
  3121. /*!
  3122. @brief access specified object element with bounds checking
  3123. Returns a reference to the element at with specified key @a key, with
  3124. bounds checking.
  3125. @param[in] key key of the element to access
  3126. @return reference to the element at key @a key
  3127. @throw type_error.304 if the JSON value is not an object; in this case,
  3128. calling `at` with a key makes no sense. See example below.
  3129. @throw out_of_range.403 if the key @a key is is not stored in the object;
  3130. that is, `find(key) == end()`. See example below.
  3131. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3132. changes in the JSON value.
  3133. @complexity Logarithmic in the size of the container.
  3134. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3135. access by reference
  3136. @sa @ref value() for access by value with a default value
  3137. @since version 1.0.0
  3138. @liveexample{The example below shows how object elements can be read and
  3139. written using `at()`. It also demonstrates the different exceptions that
  3140. can be thrown.,at__object_t_key_type}
  3141. */
  3142. reference at(const typename object_t::key_type& key)
  3143. {
  3144. // at only works for objects
  3145. if (is_object())
  3146. {
  3147. JSON_TRY
  3148. {
  3149. return m_value.object->at(key);
  3150. }
  3151. JSON_CATCH (std::out_of_range&)
  3152. {
  3153. // create better exception explanation
  3154. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  3155. }
  3156. }
  3157. else
  3158. {
  3159. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3160. }
  3161. }
  3162. /*!
  3163. @brief access specified object element with bounds checking
  3164. Returns a const reference to the element at with specified key @a key,
  3165. with bounds checking.
  3166. @param[in] key key of the element to access
  3167. @return const reference to the element at key @a key
  3168. @throw type_error.304 if the JSON value is not an object; in this case,
  3169. calling `at` with a key makes no sense. See example below.
  3170. @throw out_of_range.403 if the key @a key is is not stored in the object;
  3171. that is, `find(key) == end()`. See example below.
  3172. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  3173. changes in the JSON value.
  3174. @complexity Logarithmic in the size of the container.
  3175. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3176. access by reference
  3177. @sa @ref value() for access by value with a default value
  3178. @since version 1.0.0
  3179. @liveexample{The example below shows how object elements can be read using
  3180. `at()`. It also demonstrates the different exceptions that can be thrown.,
  3181. at__object_t_key_type_const}
  3182. */
  3183. const_reference at(const typename object_t::key_type& key) const
  3184. {
  3185. // at only works for objects
  3186. if (is_object())
  3187. {
  3188. JSON_TRY
  3189. {
  3190. return m_value.object->at(key);
  3191. }
  3192. JSON_CATCH (std::out_of_range&)
  3193. {
  3194. // create better exception explanation
  3195. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  3196. }
  3197. }
  3198. else
  3199. {
  3200. JSON_THROW(type_error::create(304, "cannot use at() with " + type_name()));
  3201. }
  3202. }
  3203. /*!
  3204. @brief access specified array element
  3205. Returns a reference to the element at specified location @a idx.
  3206. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  3207. then the array is silently filled up with `null` values to make `idx` a
  3208. valid reference to the last stored element.
  3209. @param[in] idx index of the element to access
  3210. @return reference to the element at index @a idx
  3211. @throw type_error.305 if the JSON value is not an array or null; in that
  3212. cases, using the [] operator with an index makes no sense.
  3213. @complexity Constant if @a idx is in the range of the array. Otherwise
  3214. linear in `idx - size()`.
  3215. @liveexample{The example below shows how array elements can be read and
  3216. written using `[]` operator. Note the addition of `null`
  3217. values.,operatorarray__size_type}
  3218. @since version 1.0.0
  3219. */
  3220. reference operator[](size_type idx)
  3221. {
  3222. // implicitly convert null value to an empty array
  3223. if (is_null())
  3224. {
  3225. m_type = value_t::array;
  3226. m_value.array = create<array_t>();
  3227. assert_invariant();
  3228. }
  3229. // operator[] only works for arrays
  3230. if (is_array())
  3231. {
  3232. // fill up array with null values if given idx is outside range
  3233. if (idx >= m_value.array->size())
  3234. {
  3235. m_value.array->insert(m_value.array->end(),
  3236. idx - m_value.array->size() + 1,
  3237. basic_json());
  3238. }
  3239. return m_value.array->operator[](idx);
  3240. }
  3241. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3242. }
  3243. /*!
  3244. @brief access specified array element
  3245. Returns a const reference to the element at specified location @a idx.
  3246. @param[in] idx index of the element to access
  3247. @return const reference to the element at index @a idx
  3248. @throw type_error.305 if the JSON value is not an array; in that cases,
  3249. using the [] operator with an index makes no sense.
  3250. @complexity Constant.
  3251. @liveexample{The example below shows how array elements can be read using
  3252. the `[]` operator.,operatorarray__size_type_const}
  3253. @since version 1.0.0
  3254. */
  3255. const_reference operator[](size_type idx) const
  3256. {
  3257. // const operator[] only works for arrays
  3258. if (is_array())
  3259. {
  3260. return m_value.array->operator[](idx);
  3261. }
  3262. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3263. }
  3264. /*!
  3265. @brief access specified object element
  3266. Returns a reference to the element at with specified key @a key.
  3267. @note If @a key is not found in the object, then it is silently added to
  3268. the object and filled with a `null` value to make `key` a valid reference.
  3269. In case the value was `null` before, it is converted to an object.
  3270. @param[in] key key of the element to access
  3271. @return reference to the element at key @a key
  3272. @throw type_error.305 if the JSON value is not an object or null; in that
  3273. cases, using the [] operator with a key makes no sense.
  3274. @complexity Logarithmic in the size of the container.
  3275. @liveexample{The example below shows how object elements can be read and
  3276. written using the `[]` operator.,operatorarray__key_type}
  3277. @sa @ref at(const typename object_t::key_type&) for access by reference
  3278. with range checking
  3279. @sa @ref value() for access by value with a default value
  3280. @since version 1.0.0
  3281. */
  3282. reference operator[](const typename object_t::key_type& key)
  3283. {
  3284. // implicitly convert null value to an empty object
  3285. if (is_null())
  3286. {
  3287. m_type = value_t::object;
  3288. m_value.object = create<object_t>();
  3289. assert_invariant();
  3290. }
  3291. // operator[] only works for objects
  3292. if (is_object())
  3293. {
  3294. return m_value.object->operator[](key);
  3295. }
  3296. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3297. }
  3298. /*!
  3299. @brief read-only access specified object element
  3300. Returns a const reference to the element at with specified key @a key. No
  3301. bounds checking is performed.
  3302. @warning If the element with key @a key does not exist, the behavior is
  3303. undefined.
  3304. @param[in] key key of the element to access
  3305. @return const reference to the element at key @a key
  3306. @pre The element with key @a key must exist. **This precondition is
  3307. enforced with an assertion.**
  3308. @throw type_error.305 if the JSON value is not an object; in that cases,
  3309. using the [] operator with a key makes no sense.
  3310. @complexity Logarithmic in the size of the container.
  3311. @liveexample{The example below shows how object elements can be read using
  3312. the `[]` operator.,operatorarray__key_type_const}
  3313. @sa @ref at(const typename object_t::key_type&) for access by reference
  3314. with range checking
  3315. @sa @ref value() for access by value with a default value
  3316. @since version 1.0.0
  3317. */
  3318. const_reference operator[](const typename object_t::key_type& key) const
  3319. {
  3320. // const operator[] only works for objects
  3321. if (is_object())
  3322. {
  3323. assert(m_value.object->find(key) != m_value.object->end());
  3324. return m_value.object->find(key)->second;
  3325. }
  3326. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3327. }
  3328. /*!
  3329. @brief access specified object element
  3330. Returns a reference to the element at with specified key @a key.
  3331. @note If @a key is not found in the object, then it is silently added to
  3332. the object and filled with a `null` value to make `key` a valid reference.
  3333. In case the value was `null` before, it is converted to an object.
  3334. @param[in] key key of the element to access
  3335. @return reference to the element at key @a key
  3336. @throw type_error.305 if the JSON value is not an object or null; in that
  3337. cases, using the [] operator with a key makes no sense.
  3338. @complexity Logarithmic in the size of the container.
  3339. @liveexample{The example below shows how object elements can be read and
  3340. written using the `[]` operator.,operatorarray__key_type}
  3341. @sa @ref at(const typename object_t::key_type&) for access by reference
  3342. with range checking
  3343. @sa @ref value() for access by value with a default value
  3344. @since version 1.0.0
  3345. */
  3346. template<typename T, std::size_t n>
  3347. reference operator[](T * (&key)[n])
  3348. {
  3349. return operator[](static_cast<const T>(key));
  3350. }
  3351. /*!
  3352. @brief read-only access specified object element
  3353. Returns a const reference to the element at with specified key @a key. No
  3354. bounds checking is performed.
  3355. @warning If the element with key @a key does not exist, the behavior is
  3356. undefined.
  3357. @note This function is required for compatibility reasons with Clang.
  3358. @param[in] key key of the element to access
  3359. @return const reference to the element at key @a key
  3360. @throw type_error.305 if the JSON value is not an object; in that cases,
  3361. using the [] operator with a key makes no sense.
  3362. @complexity Logarithmic in the size of the container.
  3363. @liveexample{The example below shows how object elements can be read using
  3364. the `[]` operator.,operatorarray__key_type_const}
  3365. @sa @ref at(const typename object_t::key_type&) for access by reference
  3366. with range checking
  3367. @sa @ref value() for access by value with a default value
  3368. @since version 1.0.0
  3369. */
  3370. template<typename T, std::size_t n>
  3371. const_reference operator[](T * (&key)[n]) const
  3372. {
  3373. return operator[](static_cast<const T>(key));
  3374. }
  3375. /*!
  3376. @brief access specified object element
  3377. Returns a reference to the element at with specified key @a key.
  3378. @note If @a key is not found in the object, then it is silently added to
  3379. the object and filled with a `null` value to make `key` a valid reference.
  3380. In case the value was `null` before, it is converted to an object.
  3381. @param[in] key key of the element to access
  3382. @return reference to the element at key @a key
  3383. @throw type_error.305 if the JSON value is not an object or null; in that
  3384. cases, using the [] operator with a key makes no sense.
  3385. @complexity Logarithmic in the size of the container.
  3386. @liveexample{The example below shows how object elements can be read and
  3387. written using the `[]` operator.,operatorarray__key_type}
  3388. @sa @ref at(const typename object_t::key_type&) for access by reference
  3389. with range checking
  3390. @sa @ref value() for access by value with a default value
  3391. @since version 1.1.0
  3392. */
  3393. template<typename T>
  3394. reference operator[](T* key)
  3395. {
  3396. // implicitly convert null to object
  3397. if (is_null())
  3398. {
  3399. m_type = value_t::object;
  3400. m_value = value_t::object;
  3401. assert_invariant();
  3402. }
  3403. // at only works for objects
  3404. if (is_object())
  3405. {
  3406. return m_value.object->operator[](key);
  3407. }
  3408. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3409. }
  3410. /*!
  3411. @brief read-only access specified object element
  3412. Returns a const reference to the element at with specified key @a key. No
  3413. bounds checking is performed.
  3414. @warning If the element with key @a key does not exist, the behavior is
  3415. undefined.
  3416. @param[in] key key of the element to access
  3417. @return const reference to the element at key @a key
  3418. @pre The element with key @a key must exist. **This precondition is
  3419. enforced with an assertion.**
  3420. @throw type_error.305 if the JSON value is not an object; in that cases,
  3421. using the [] operator with a key makes no sense.
  3422. @complexity Logarithmic in the size of the container.
  3423. @liveexample{The example below shows how object elements can be read using
  3424. the `[]` operator.,operatorarray__key_type_const}
  3425. @sa @ref at(const typename object_t::key_type&) for access by reference
  3426. with range checking
  3427. @sa @ref value() for access by value with a default value
  3428. @since version 1.1.0
  3429. */
  3430. template<typename T>
  3431. const_reference operator[](T* key) const
  3432. {
  3433. // at only works for objects
  3434. if (is_object())
  3435. {
  3436. assert(m_value.object->find(key) != m_value.object->end());
  3437. return m_value.object->find(key)->second;
  3438. }
  3439. JSON_THROW(type_error::create(305, "cannot use operator[] with " + type_name()));
  3440. }
  3441. /*!
  3442. @brief access specified object element with default value
  3443. Returns either a copy of an object's element at the specified key @a key
  3444. or a given default value if no element with key @a key exists.
  3445. The function is basically equivalent to executing
  3446. @code {.cpp}
  3447. try {
  3448. return at(key);
  3449. } catch(out_of_range) {
  3450. return default_value;
  3451. }
  3452. @endcode
  3453. @note Unlike @ref at(const typename object_t::key_type&), this function
  3454. does not throw if the given key @a key was not found.
  3455. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  3456. function does not implicitly add an element to the position defined by @a
  3457. key. This function is furthermore also applicable to const objects.
  3458. @param[in] key key of the element to access
  3459. @param[in] default_value the value to return if @a key is not found
  3460. @tparam ValueType type compatible to JSON values, for instance `int` for
  3461. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  3462. JSON arrays. Note the type of the expected value at @a key and the default
  3463. value @a default_value must be compatible.
  3464. @return copy of the element at key @a key or @a default_value if @a key
  3465. is not found
  3466. @throw type_error.306 if the JSON value is not an objec; in that cases,
  3467. using `value()` with a key makes no sense.
  3468. @complexity Logarithmic in the size of the container.
  3469. @liveexample{The example below shows how object elements can be queried
  3470. with a default value.,basic_json__value}
  3471. @sa @ref at(const typename object_t::key_type&) for access by reference
  3472. with range checking
  3473. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  3474. access by reference
  3475. @since version 1.0.0
  3476. */
  3477. template<class ValueType, typename std::enable_if<
  3478. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  3479. ValueType value(const typename object_t::key_type& key, ValueType default_value) const
  3480. {
  3481. // at only works for objects
  3482. if (is_object())
  3483. {
  3484. // if key is found, return value and given default value otherwise
  3485. const auto it = find(key);
  3486. if (it != end())
  3487. {
  3488. return *it;
  3489. }
  3490. return default_value;
  3491. }
  3492. else
  3493. {
  3494. JSON_THROW(type_error::create(306, "cannot use value() with " + type_name()));
  3495. }
  3496. }
  3497. /*!
  3498. @brief overload for a default value of type const char*
  3499. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  3500. */
  3501. string_t value(const typename object_t::key_type& key, const char* default_value) const
  3502. {
  3503. return value(key, string_t(default_value));
  3504. }
  3505. /*!
  3506. @brief access specified object element via JSON Pointer with default value
  3507. Returns either a copy of an object's element at the specified key @a key
  3508. or a given default value if no element with key @a key exists.
  3509. The function is basically equivalent to executing
  3510. @code {.cpp}
  3511. try {
  3512. return at(ptr);
  3513. } catch(out_of_range) {
  3514. return default_value;
  3515. }
  3516. @endcode
  3517. @note Unlike @ref at(const json_pointer&), this function does not throw
  3518. if the given key @a key was not found.
  3519. @param[in] ptr a JSON pointer to the element to access
  3520. @param[in] default_value the value to return if @a ptr found no value
  3521. @tparam ValueType type compatible to JSON values, for instance `int` for
  3522. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  3523. JSON arrays. Note the type of the expected value at @a key and the default
  3524. value @a default_value must be compatible.
  3525. @return copy of the element at key @a key or @a default_value if @a key
  3526. is not found
  3527. @throw type_error.306 if the JSON value is not an objec; in that cases,
  3528. using `value()` with a key makes no sense.
  3529. @complexity Logarithmic in the size of the container.
  3530. @liveexample{The example below shows how object elements can be queried
  3531. with a default value.,basic_json__value_ptr}
  3532. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  3533. @since version 2.0.2
  3534. */
  3535. template<class ValueType, typename std::enable_if<
  3536. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  3537. ValueType value(const json_pointer& ptr, ValueType default_value) const
  3538. {
  3539. // at only works for objects
  3540. if (is_object())
  3541. {
  3542. // if pointer resolves a value, return it or use default value
  3543. JSON_TRY
  3544. {
  3545. return ptr.get_checked(this);
  3546. }
  3547. JSON_CATCH (out_of_range&)
  3548. {
  3549. return default_value;
  3550. }
  3551. }
  3552. JSON_THROW(type_error::create(306, "cannot use value() with " + type_name()));
  3553. }
  3554. /*!
  3555. @brief overload for a default value of type const char*
  3556. @copydoc basic_json::value(const json_pointer&, ValueType) const
  3557. */
  3558. string_t value(const json_pointer& ptr, const char* default_value) const
  3559. {
  3560. return value(ptr, string_t(default_value));
  3561. }
  3562. /*!
  3563. @brief access the first element
  3564. Returns a reference to the first element in the container. For a JSON
  3565. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  3566. @return In case of a structured type (array or object), a reference to the
  3567. first element is returned. In case of number, string, or boolean values, a
  3568. reference to the value is returned.
  3569. @complexity Constant.
  3570. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3571. or an empty array or object (undefined behavior, **guarded by
  3572. assertions**).
  3573. @post The JSON value remains unchanged.
  3574. @throw invalid_iterator.214 when called on `null` value
  3575. @liveexample{The following code shows an example for `front()`.,front}
  3576. @sa @ref back() -- access the last element
  3577. @since version 1.0.0
  3578. */
  3579. reference front()
  3580. {
  3581. return *begin();
  3582. }
  3583. /*!
  3584. @copydoc basic_json::front()
  3585. */
  3586. const_reference front() const
  3587. {
  3588. return *cbegin();
  3589. }
  3590. /*!
  3591. @brief access the last element
  3592. Returns a reference to the last element in the container. For a JSON
  3593. container `c`, the expression `c.back()` is equivalent to
  3594. @code {.cpp}
  3595. auto tmp = c.end();
  3596. --tmp;
  3597. return *tmp;
  3598. @endcode
  3599. @return In case of a structured type (array or object), a reference to the
  3600. last element is returned. In case of number, string, or boolean values, a
  3601. reference to the value is returned.
  3602. @complexity Constant.
  3603. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3604. or an empty array or object (undefined behavior, **guarded by
  3605. assertions**).
  3606. @post The JSON value remains unchanged.
  3607. @throw invalid_iterator.214 when called on a `null` value. See example
  3608. below.
  3609. @liveexample{The following code shows an example for `back()`.,back}
  3610. @sa @ref front() -- access the first element
  3611. @since version 1.0.0
  3612. */
  3613. reference back()
  3614. {
  3615. auto tmp = end();
  3616. --tmp;
  3617. return *tmp;
  3618. }
  3619. /*!
  3620. @copydoc basic_json::back()
  3621. */
  3622. const_reference back() const
  3623. {
  3624. auto tmp = cend();
  3625. --tmp;
  3626. return *tmp;
  3627. }
  3628. /*!
  3629. @brief remove element given an iterator
  3630. Removes the element specified by iterator @a pos. The iterator @a pos must
  3631. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  3632. but is not dereferenceable) cannot be used as a value for @a pos.
  3633. If called on a primitive type other than `null`, the resulting JSON value
  3634. will be `null`.
  3635. @param[in] pos iterator to the element to remove
  3636. @return Iterator following the last removed element. If the iterator @a
  3637. pos refers to the last element, the `end()` iterator is returned.
  3638. @tparam IteratorType an @ref iterator or @ref const_iterator
  3639. @post Invalidates iterators and references at or after the point of the
  3640. erase, including the `end()` iterator.
  3641. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3642. erase() with null"`
  3643. @throw invalid_iterator.202 if called on an iterator which does not belong
  3644. to the current JSON value; example: `"iterator does not fit current
  3645. value"`
  3646. @throw invalid_iterator.205 if called on a primitive type with invalid
  3647. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  3648. out of range"`
  3649. @complexity The complexity depends on the type:
  3650. - objects: amortized constant
  3651. - arrays: linear in distance between @a pos and the end of the container
  3652. - strings: linear in the length of the string
  3653. - other types: constant
  3654. @liveexample{The example shows the result of `erase()` for different JSON
  3655. types.,erase__IteratorType}
  3656. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3657. the given range
  3658. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3659. from an object at the given key
  3660. @sa @ref erase(const size_type) -- removes the element from an array at
  3661. the given index
  3662. @since version 1.0.0
  3663. */
  3664. template<class IteratorType, typename std::enable_if<
  3665. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3666. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3667. = 0>
  3668. IteratorType erase(IteratorType pos)
  3669. {
  3670. // make sure iterator fits the current value
  3671. if (this != pos.m_object)
  3672. {
  3673. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  3674. }
  3675. IteratorType result = end();
  3676. switch (m_type)
  3677. {
  3678. case value_t::boolean:
  3679. case value_t::number_float:
  3680. case value_t::number_integer:
  3681. case value_t::number_unsigned:
  3682. case value_t::string:
  3683. {
  3684. if (not pos.m_it.primitive_iterator.is_begin())
  3685. {
  3686. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  3687. }
  3688. if (is_string())
  3689. {
  3690. AllocatorType<string_t> alloc;
  3691. alloc.destroy(m_value.string);
  3692. alloc.deallocate(m_value.string, 1);
  3693. m_value.string = nullptr;
  3694. }
  3695. m_type = value_t::null;
  3696. assert_invariant();
  3697. break;
  3698. }
  3699. case value_t::object:
  3700. {
  3701. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  3702. break;
  3703. }
  3704. case value_t::array:
  3705. {
  3706. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  3707. break;
  3708. }
  3709. default:
  3710. {
  3711. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3712. }
  3713. }
  3714. return result;
  3715. }
  3716. /*!
  3717. @brief remove elements given an iterator range
  3718. Removes the element specified by the range `[first; last)`. The iterator
  3719. @a first does not need to be dereferenceable if `first == last`: erasing
  3720. an empty range is a no-op.
  3721. If called on a primitive type other than `null`, the resulting JSON value
  3722. will be `null`.
  3723. @param[in] first iterator to the beginning of the range to remove
  3724. @param[in] last iterator past the end of the range to remove
  3725. @return Iterator following the last removed element. If the iterator @a
  3726. second refers to the last element, the `end()` iterator is returned.
  3727. @tparam IteratorType an @ref iterator or @ref const_iterator
  3728. @post Invalidates iterators and references at or after the point of the
  3729. erase, including the `end()` iterator.
  3730. @throw type_error.307 if called on a `null` value; example: `"cannot use
  3731. erase() with null"`
  3732. @throw invalid_iterator.203 if called on iterators which does not belong
  3733. to the current JSON value; example: `"iterators do not fit current value"`
  3734. @throw invalid_iterator.204 if called on a primitive type with invalid
  3735. iterators (i.e., if `first != begin()` and `last != end()`); example:
  3736. `"iterators out of range"`
  3737. @complexity The complexity depends on the type:
  3738. - objects: `log(size()) + std::distance(first, last)`
  3739. - arrays: linear in the distance between @a first and @a last, plus linear
  3740. in the distance between @a last and end of the container
  3741. - strings: linear in the length of the string
  3742. - other types: constant
  3743. @liveexample{The example shows the result of `erase()` for different JSON
  3744. types.,erase__IteratorType_IteratorType}
  3745. @sa @ref erase(IteratorType) -- removes the element at a given position
  3746. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3747. from an object at the given key
  3748. @sa @ref erase(const size_type) -- removes the element from an array at
  3749. the given index
  3750. @since version 1.0.0
  3751. */
  3752. template<class IteratorType, typename std::enable_if<
  3753. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3754. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3755. = 0>
  3756. IteratorType erase(IteratorType first, IteratorType last)
  3757. {
  3758. // make sure iterator fits the current value
  3759. if (this != first.m_object or this != last.m_object)
  3760. {
  3761. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  3762. }
  3763. IteratorType result = end();
  3764. switch (m_type)
  3765. {
  3766. case value_t::boolean:
  3767. case value_t::number_float:
  3768. case value_t::number_integer:
  3769. case value_t::number_unsigned:
  3770. case value_t::string:
  3771. {
  3772. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  3773. {
  3774. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  3775. }
  3776. if (is_string())
  3777. {
  3778. AllocatorType<string_t> alloc;
  3779. alloc.destroy(m_value.string);
  3780. alloc.deallocate(m_value.string, 1);
  3781. m_value.string = nullptr;
  3782. }
  3783. m_type = value_t::null;
  3784. assert_invariant();
  3785. break;
  3786. }
  3787. case value_t::object:
  3788. {
  3789. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  3790. last.m_it.object_iterator);
  3791. break;
  3792. }
  3793. case value_t::array:
  3794. {
  3795. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  3796. last.m_it.array_iterator);
  3797. break;
  3798. }
  3799. default:
  3800. {
  3801. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3802. }
  3803. }
  3804. return result;
  3805. }
  3806. /*!
  3807. @brief remove element from a JSON object given a key
  3808. Removes elements from a JSON object with the key value @a key.
  3809. @param[in] key value of the elements to remove
  3810. @return Number of elements removed. If @a ObjectType is the default
  3811. `std::map` type, the return value will always be `0` (@a key was not
  3812. found) or `1` (@a key was found).
  3813. @post References and iterators to the erased elements are invalidated.
  3814. Other references and iterators are not affected.
  3815. @throw type_error.307 when called on a type other than JSON object;
  3816. example: `"cannot use erase() with null"`
  3817. @complexity `log(size()) + count(key)`
  3818. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  3819. @sa @ref erase(IteratorType) -- removes the element at a given position
  3820. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3821. the given range
  3822. @sa @ref erase(const size_type) -- removes the element from an array at
  3823. the given index
  3824. @since version 1.0.0
  3825. */
  3826. size_type erase(const typename object_t::key_type& key)
  3827. {
  3828. // this erase only works for objects
  3829. if (is_object())
  3830. {
  3831. return m_value.object->erase(key);
  3832. }
  3833. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3834. }
  3835. /*!
  3836. @brief remove element from a JSON array given an index
  3837. Removes element from a JSON array at the index @a idx.
  3838. @param[in] idx index of the element to remove
  3839. @throw type_error.307 when called on a type other than JSON object;
  3840. example: `"cannot use erase() with null"`
  3841. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  3842. is out of range"`
  3843. @complexity Linear in distance between @a idx and the end of the container.
  3844. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  3845. @sa @ref erase(IteratorType) -- removes the element at a given position
  3846. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3847. the given range
  3848. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3849. from an object at the given key
  3850. @since version 1.0.0
  3851. */
  3852. void erase(const size_type idx)
  3853. {
  3854. // this erase only works for arrays
  3855. if (is_array())
  3856. {
  3857. if (idx >= size())
  3858. {
  3859. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  3860. }
  3861. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  3862. }
  3863. else
  3864. {
  3865. JSON_THROW(type_error::create(307, "cannot use erase() with " + type_name()));
  3866. }
  3867. }
  3868. /// @}
  3869. ////////////
  3870. // lookup //
  3871. ////////////
  3872. /// @name lookup
  3873. /// @{
  3874. /*!
  3875. @brief find an element in a JSON object
  3876. Finds an element in a JSON object with key equivalent to @a key. If the
  3877. element is not found or the JSON value is not an object, end() is
  3878. returned.
  3879. @note This method always returns @ref end() when executed on a JSON type
  3880. that is not an object.
  3881. @param[in] key key value of the element to search for
  3882. @return Iterator to an element with key equivalent to @a key. If no such
  3883. element is found or the JSON value is not an object, past-the-end (see
  3884. @ref end()) iterator is returned.
  3885. @complexity Logarithmic in the size of the JSON object.
  3886. @liveexample{The example shows how `find()` is used.,find__key_type}
  3887. @since version 1.0.0
  3888. */
  3889. iterator find(typename object_t::key_type key)
  3890. {
  3891. auto result = end();
  3892. if (is_object())
  3893. {
  3894. result.m_it.object_iterator = m_value.object->find(key);
  3895. }
  3896. return result;
  3897. }
  3898. /*!
  3899. @brief find an element in a JSON object
  3900. @copydoc find(typename object_t::key_type)
  3901. */
  3902. const_iterator find(typename object_t::key_type key) const
  3903. {
  3904. auto result = cend();
  3905. if (is_object())
  3906. {
  3907. result.m_it.object_iterator = m_value.object->find(key);
  3908. }
  3909. return result;
  3910. }
  3911. /*!
  3912. @brief returns the number of occurrences of a key in a JSON object
  3913. Returns the number of elements with key @a key. If ObjectType is the
  3914. default `std::map` type, the return value will always be `0` (@a key was
  3915. not found) or `1` (@a key was found).
  3916. @note This method always returns `0` when executed on a JSON type that is
  3917. not an object.
  3918. @param[in] key key value of the element to count
  3919. @return Number of elements with key @a key. If the JSON value is not an
  3920. object, the return value will be `0`.
  3921. @complexity Logarithmic in the size of the JSON object.
  3922. @liveexample{The example shows how `count()` is used.,count}
  3923. @since version 1.0.0
  3924. */
  3925. size_type count(typename object_t::key_type key) const
  3926. {
  3927. // return 0 for all nonobject types
  3928. return is_object() ? m_value.object->count(key) : 0;
  3929. }
  3930. /// @}
  3931. ///////////////
  3932. // iterators //
  3933. ///////////////
  3934. /// @name iterators
  3935. /// @{
  3936. /*!
  3937. @brief returns an iterator to the first element
  3938. Returns an iterator to the first element.
  3939. @image html range-begin-end.svg "Illustration from cppreference.com"
  3940. @return iterator to the first element
  3941. @complexity Constant.
  3942. @requirement This function helps `basic_json` satisfying the
  3943. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3944. requirements:
  3945. - The complexity is constant.
  3946. @liveexample{The following code shows an example for `begin()`.,begin}
  3947. @sa @ref cbegin() -- returns a const iterator to the beginning
  3948. @sa @ref end() -- returns an iterator to the end
  3949. @sa @ref cend() -- returns a const iterator to the end
  3950. @since version 1.0.0
  3951. */
  3952. iterator begin() noexcept
  3953. {
  3954. iterator result(this);
  3955. result.set_begin();
  3956. return result;
  3957. }
  3958. /*!
  3959. @copydoc basic_json::cbegin()
  3960. */
  3961. const_iterator begin() const noexcept
  3962. {
  3963. return cbegin();
  3964. }
  3965. /*!
  3966. @brief returns a const iterator to the first element
  3967. Returns a const iterator to the first element.
  3968. @image html range-begin-end.svg "Illustration from cppreference.com"
  3969. @return const iterator to the first element
  3970. @complexity Constant.
  3971. @requirement This function helps `basic_json` satisfying the
  3972. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3973. requirements:
  3974. - The complexity is constant.
  3975. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  3976. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  3977. @sa @ref begin() -- returns an iterator to the beginning
  3978. @sa @ref end() -- returns an iterator to the end
  3979. @sa @ref cend() -- returns a const iterator to the end
  3980. @since version 1.0.0
  3981. */
  3982. const_iterator cbegin() const noexcept
  3983. {
  3984. const_iterator result(this);
  3985. result.set_begin();
  3986. return result;
  3987. }
  3988. /*!
  3989. @brief returns an iterator to one past the last element
  3990. Returns an iterator to one past the last element.
  3991. @image html range-begin-end.svg "Illustration from cppreference.com"
  3992. @return iterator one past the last element
  3993. @complexity Constant.
  3994. @requirement This function helps `basic_json` satisfying the
  3995. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3996. requirements:
  3997. - The complexity is constant.
  3998. @liveexample{The following code shows an example for `end()`.,end}
  3999. @sa @ref cend() -- returns a const iterator to the end
  4000. @sa @ref begin() -- returns an iterator to the beginning
  4001. @sa @ref cbegin() -- returns a const iterator to the beginning
  4002. @since version 1.0.0
  4003. */
  4004. iterator end() noexcept
  4005. {
  4006. iterator result(this);
  4007. result.set_end();
  4008. return result;
  4009. }
  4010. /*!
  4011. @copydoc basic_json::cend()
  4012. */
  4013. const_iterator end() const noexcept
  4014. {
  4015. return cend();
  4016. }
  4017. /*!
  4018. @brief returns a const iterator to one past the last element
  4019. Returns a const iterator to one past the last element.
  4020. @image html range-begin-end.svg "Illustration from cppreference.com"
  4021. @return const iterator one past the last element
  4022. @complexity Constant.
  4023. @requirement This function helps `basic_json` satisfying the
  4024. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4025. requirements:
  4026. - The complexity is constant.
  4027. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  4028. @liveexample{The following code shows an example for `cend()`.,cend}
  4029. @sa @ref end() -- returns an iterator to the end
  4030. @sa @ref begin() -- returns an iterator to the beginning
  4031. @sa @ref cbegin() -- returns a const iterator to the beginning
  4032. @since version 1.0.0
  4033. */
  4034. const_iterator cend() const noexcept
  4035. {
  4036. const_iterator result(this);
  4037. result.set_end();
  4038. return result;
  4039. }
  4040. /*!
  4041. @brief returns an iterator to the reverse-beginning
  4042. Returns an iterator to the reverse-beginning; that is, the last element.
  4043. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4044. @complexity Constant.
  4045. @requirement This function helps `basic_json` satisfying the
  4046. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4047. requirements:
  4048. - The complexity is constant.
  4049. - Has the semantics of `reverse_iterator(end())`.
  4050. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  4051. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4052. @sa @ref rend() -- returns a reverse iterator to the end
  4053. @sa @ref crend() -- returns a const reverse iterator to the end
  4054. @since version 1.0.0
  4055. */
  4056. reverse_iterator rbegin() noexcept
  4057. {
  4058. return reverse_iterator(end());
  4059. }
  4060. /*!
  4061. @copydoc basic_json::crbegin()
  4062. */
  4063. const_reverse_iterator rbegin() const noexcept
  4064. {
  4065. return crbegin();
  4066. }
  4067. /*!
  4068. @brief returns an iterator to the reverse-end
  4069. Returns an iterator to the reverse-end; that is, one before the first
  4070. element.
  4071. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4072. @complexity Constant.
  4073. @requirement This function helps `basic_json` satisfying the
  4074. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4075. requirements:
  4076. - The complexity is constant.
  4077. - Has the semantics of `reverse_iterator(begin())`.
  4078. @liveexample{The following code shows an example for `rend()`.,rend}
  4079. @sa @ref crend() -- returns a const reverse iterator to the end
  4080. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4081. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4082. @since version 1.0.0
  4083. */
  4084. reverse_iterator rend() noexcept
  4085. {
  4086. return reverse_iterator(begin());
  4087. }
  4088. /*!
  4089. @copydoc basic_json::crend()
  4090. */
  4091. const_reverse_iterator rend() const noexcept
  4092. {
  4093. return crend();
  4094. }
  4095. /*!
  4096. @brief returns a const reverse iterator to the last element
  4097. Returns a const iterator to the reverse-beginning; that is, the last
  4098. element.
  4099. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4100. @complexity Constant.
  4101. @requirement This function helps `basic_json` satisfying the
  4102. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4103. requirements:
  4104. - The complexity is constant.
  4105. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  4106. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  4107. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4108. @sa @ref rend() -- returns a reverse iterator to the end
  4109. @sa @ref crend() -- returns a const reverse iterator to the end
  4110. @since version 1.0.0
  4111. */
  4112. const_reverse_iterator crbegin() const noexcept
  4113. {
  4114. return const_reverse_iterator(cend());
  4115. }
  4116. /*!
  4117. @brief returns a const reverse iterator to one before the first
  4118. Returns a const reverse iterator to the reverse-end; that is, one before
  4119. the first element.
  4120. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  4121. @complexity Constant.
  4122. @requirement This function helps `basic_json` satisfying the
  4123. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  4124. requirements:
  4125. - The complexity is constant.
  4126. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  4127. @liveexample{The following code shows an example for `crend()`.,crend}
  4128. @sa @ref rend() -- returns a reverse iterator to the end
  4129. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  4130. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  4131. @since version 1.0.0
  4132. */
  4133. const_reverse_iterator crend() const noexcept
  4134. {
  4135. return const_reverse_iterator(cbegin());
  4136. }
  4137. private:
  4138. // forward declaration
  4139. template<typename IteratorType> class iteration_proxy;
  4140. public:
  4141. /*!
  4142. @brief wrapper to access iterator member functions in range-based for
  4143. This function allows to access @ref iterator::key() and @ref
  4144. iterator::value() during range-based for loops. In these loops, a
  4145. reference to the JSON values is returned, so there is no access to the
  4146. underlying iterator.
  4147. @note The name of this function is not yet final and may change in the
  4148. future.
  4149. */
  4150. static iteration_proxy<iterator> iterator_wrapper(reference cont)
  4151. {
  4152. return iteration_proxy<iterator>(cont);
  4153. }
  4154. /*!
  4155. @copydoc iterator_wrapper(reference)
  4156. */
  4157. static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
  4158. {
  4159. return iteration_proxy<const_iterator>(cont);
  4160. }
  4161. /// @}
  4162. //////////////
  4163. // capacity //
  4164. //////////////
  4165. /// @name capacity
  4166. /// @{
  4167. /*!
  4168. @brief checks whether the container is empty
  4169. Checks if a JSON value has no elements.
  4170. @return The return value depends on the different types and is
  4171. defined as follows:
  4172. Value type | return value
  4173. ----------- | -------------
  4174. null | `true`
  4175. boolean | `false`
  4176. string | `false`
  4177. number | `false`
  4178. object | result of function `object_t::empty()`
  4179. array | result of function `array_t::empty()`
  4180. @note This function does not return whether a string stored as JSON value
  4181. is empty - it returns whether the JSON container itself is empty which is
  4182. false in the case of a string.
  4183. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4184. the Container concept; that is, their `empty()` functions have constant
  4185. complexity.
  4186. @requirement This function helps `basic_json` satisfying the
  4187. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4188. requirements:
  4189. - The complexity is constant.
  4190. - Has the semantics of `begin() == end()`.
  4191. @liveexample{The following code uses `empty()` to check if a JSON
  4192. object contains any elements.,empty}
  4193. @sa @ref size() -- returns the number of elements
  4194. @since version 1.0.0
  4195. */
  4196. bool empty() const noexcept
  4197. {
  4198. switch (m_type)
  4199. {
  4200. case value_t::null:
  4201. {
  4202. // null values are empty
  4203. return true;
  4204. }
  4205. case value_t::array:
  4206. {
  4207. // delegate call to array_t::empty()
  4208. return m_value.array->empty();
  4209. }
  4210. case value_t::object:
  4211. {
  4212. // delegate call to object_t::empty()
  4213. return m_value.object->empty();
  4214. }
  4215. default:
  4216. {
  4217. // all other types are nonempty
  4218. return false;
  4219. }
  4220. }
  4221. }
  4222. /*!
  4223. @brief returns the number of elements
  4224. Returns the number of elements in a JSON value.
  4225. @return The return value depends on the different types and is
  4226. defined as follows:
  4227. Value type | return value
  4228. ----------- | -------------
  4229. null | `0`
  4230. boolean | `1`
  4231. string | `1`
  4232. number | `1`
  4233. object | result of function object_t::size()
  4234. array | result of function array_t::size()
  4235. @note This function does not return the length of a string stored as JSON
  4236. value - it returns the number of elements in the JSON value which is 1 in
  4237. the case of a string.
  4238. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4239. the Container concept; that is, their size() functions have constant
  4240. complexity.
  4241. @requirement This function helps `basic_json` satisfying the
  4242. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4243. requirements:
  4244. - The complexity is constant.
  4245. - Has the semantics of `std::distance(begin(), end())`.
  4246. @liveexample{The following code calls `size()` on the different value
  4247. types.,size}
  4248. @sa @ref empty() -- checks whether the container is empty
  4249. @sa @ref max_size() -- returns the maximal number of elements
  4250. @since version 1.0.0
  4251. */
  4252. size_type size() const noexcept
  4253. {
  4254. switch (m_type)
  4255. {
  4256. case value_t::null:
  4257. {
  4258. // null values are empty
  4259. return 0;
  4260. }
  4261. case value_t::array:
  4262. {
  4263. // delegate call to array_t::size()
  4264. return m_value.array->size();
  4265. }
  4266. case value_t::object:
  4267. {
  4268. // delegate call to object_t::size()
  4269. return m_value.object->size();
  4270. }
  4271. default:
  4272. {
  4273. // all other types have size 1
  4274. return 1;
  4275. }
  4276. }
  4277. }
  4278. /*!
  4279. @brief returns the maximum possible number of elements
  4280. Returns the maximum number of elements a JSON value is able to hold due to
  4281. system or library implementation limitations, i.e. `std::distance(begin(),
  4282. end())` for the JSON value.
  4283. @return The return value depends on the different types and is
  4284. defined as follows:
  4285. Value type | return value
  4286. ----------- | -------------
  4287. null | `0` (same as `size()`)
  4288. boolean | `1` (same as `size()`)
  4289. string | `1` (same as `size()`)
  4290. number | `1` (same as `size()`)
  4291. object | result of function `object_t::max_size()`
  4292. array | result of function `array_t::max_size()`
  4293. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  4294. the Container concept; that is, their `max_size()` functions have constant
  4295. complexity.
  4296. @requirement This function helps `basic_json` satisfying the
  4297. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  4298. requirements:
  4299. - The complexity is constant.
  4300. - Has the semantics of returning `b.size()` where `b` is the largest
  4301. possible JSON value.
  4302. @liveexample{The following code calls `max_size()` on the different value
  4303. types. Note the output is implementation specific.,max_size}
  4304. @sa @ref size() -- returns the number of elements
  4305. @since version 1.0.0
  4306. */
  4307. size_type max_size() const noexcept
  4308. {
  4309. switch (m_type)
  4310. {
  4311. case value_t::array:
  4312. {
  4313. // delegate call to array_t::max_size()
  4314. return m_value.array->max_size();
  4315. }
  4316. case value_t::object:
  4317. {
  4318. // delegate call to object_t::max_size()
  4319. return m_value.object->max_size();
  4320. }
  4321. default:
  4322. {
  4323. // all other types have max_size() == size()
  4324. return size();
  4325. }
  4326. }
  4327. }
  4328. /// @}
  4329. ///////////////
  4330. // modifiers //
  4331. ///////////////
  4332. /// @name modifiers
  4333. /// @{
  4334. /*!
  4335. @brief clears the contents
  4336. Clears the content of a JSON value and resets it to the default value as
  4337. if @ref basic_json(value_t) would have been called:
  4338. Value type | initial value
  4339. ----------- | -------------
  4340. null | `null`
  4341. boolean | `false`
  4342. string | `""`
  4343. number | `0`
  4344. object | `{}`
  4345. array | `[]`
  4346. @complexity Linear in the size of the JSON value.
  4347. @liveexample{The example below shows the effect of `clear()` to different
  4348. JSON types.,clear}
  4349. @since version 1.0.0
  4350. */
  4351. void clear() noexcept
  4352. {
  4353. switch (m_type)
  4354. {
  4355. case value_t::number_integer:
  4356. {
  4357. m_value.number_integer = 0;
  4358. break;
  4359. }
  4360. case value_t::number_unsigned:
  4361. {
  4362. m_value.number_unsigned = 0;
  4363. break;
  4364. }
  4365. case value_t::number_float:
  4366. {
  4367. m_value.number_float = 0.0;
  4368. break;
  4369. }
  4370. case value_t::boolean:
  4371. {
  4372. m_value.boolean = false;
  4373. break;
  4374. }
  4375. case value_t::string:
  4376. {
  4377. m_value.string->clear();
  4378. break;
  4379. }
  4380. case value_t::array:
  4381. {
  4382. m_value.array->clear();
  4383. break;
  4384. }
  4385. case value_t::object:
  4386. {
  4387. m_value.object->clear();
  4388. break;
  4389. }
  4390. default:
  4391. {
  4392. break;
  4393. }
  4394. }
  4395. }
  4396. /*!
  4397. @brief add an object to an array
  4398. Appends the given element @a val to the end of the JSON value. If the
  4399. function is called on a JSON null value, an empty array is created before
  4400. appending @a val.
  4401. @param[in] val the value to add to the JSON array
  4402. @throw type_error.308 when called on a type other than JSON array or
  4403. null; example: `"cannot use push_back() with number"`
  4404. @complexity Amortized constant.
  4405. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4406. add elements to a JSON array. Note how the `null` value was silently
  4407. converted to a JSON array.,push_back}
  4408. @since version 1.0.0
  4409. */
  4410. void push_back(basic_json&& val)
  4411. {
  4412. // push_back only works for null objects or arrays
  4413. if (not(is_null() or is_array()))
  4414. {
  4415. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4416. }
  4417. // transform null object into an array
  4418. if (is_null())
  4419. {
  4420. m_type = value_t::array;
  4421. m_value = value_t::array;
  4422. assert_invariant();
  4423. }
  4424. // add element to array (move semantics)
  4425. m_value.array->push_back(std::move(val));
  4426. // invalidate object
  4427. val.m_type = value_t::null;
  4428. }
  4429. /*!
  4430. @brief add an object to an array
  4431. @copydoc push_back(basic_json&&)
  4432. */
  4433. reference operator+=(basic_json&& val)
  4434. {
  4435. push_back(std::move(val));
  4436. return *this;
  4437. }
  4438. /*!
  4439. @brief add an object to an array
  4440. @copydoc push_back(basic_json&&)
  4441. */
  4442. void push_back(const basic_json& val)
  4443. {
  4444. // push_back only works for null objects or arrays
  4445. if (not(is_null() or is_array()))
  4446. {
  4447. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4448. }
  4449. // transform null object into an array
  4450. if (is_null())
  4451. {
  4452. m_type = value_t::array;
  4453. m_value = value_t::array;
  4454. assert_invariant();
  4455. }
  4456. // add element to array
  4457. m_value.array->push_back(val);
  4458. }
  4459. /*!
  4460. @brief add an object to an array
  4461. @copydoc push_back(basic_json&&)
  4462. */
  4463. reference operator+=(const basic_json& val)
  4464. {
  4465. push_back(val);
  4466. return *this;
  4467. }
  4468. /*!
  4469. @brief add an object to an object
  4470. Inserts the given element @a val to the JSON object. If the function is
  4471. called on a JSON null value, an empty object is created before inserting
  4472. @a val.
  4473. @param[in] val the value to add to the JSON object
  4474. @throw type_error.308 when called on a type other than JSON object or
  4475. null; example: `"cannot use push_back() with number"`
  4476. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4477. @liveexample{The example shows how `push_back()` and `+=` can be used to
  4478. add elements to a JSON object. Note how the `null` value was silently
  4479. converted to a JSON object.,push_back__object_t__value}
  4480. @since version 1.0.0
  4481. */
  4482. void push_back(const typename object_t::value_type& val)
  4483. {
  4484. // push_back only works for null objects or objects
  4485. if (not(is_null() or is_object()))
  4486. {
  4487. JSON_THROW(type_error::create(308, "cannot use push_back() with " + type_name()));
  4488. }
  4489. // transform null object into an object
  4490. if (is_null())
  4491. {
  4492. m_type = value_t::object;
  4493. m_value = value_t::object;
  4494. assert_invariant();
  4495. }
  4496. // add element to array
  4497. m_value.object->insert(val);
  4498. }
  4499. /*!
  4500. @brief add an object to an object
  4501. @copydoc push_back(const typename object_t::value_type&)
  4502. */
  4503. reference operator+=(const typename object_t::value_type& val)
  4504. {
  4505. push_back(val);
  4506. return *this;
  4507. }
  4508. /*!
  4509. @brief add an object to an object
  4510. This function allows to use `push_back` with an initializer list. In case
  4511. 1. the current value is an object,
  4512. 2. the initializer list @a init contains only two elements, and
  4513. 3. the first element of @a init is a string,
  4514. @a init is converted into an object element and added using
  4515. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  4516. is converted to a JSON value and added using @ref push_back(basic_json&&).
  4517. @param[in] init an initializer list
  4518. @complexity Linear in the size of the initializer list @a init.
  4519. @note This function is required to resolve an ambiguous overload error,
  4520. because pairs like `{"key", "value"}` can be both interpreted as
  4521. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  4522. https://github.com/nlohmann/json/issues/235 for more information.
  4523. @liveexample{The example shows how initializer lists are treated as
  4524. objects when possible.,push_back__initializer_list}
  4525. */
  4526. void push_back(std::initializer_list<basic_json> init)
  4527. {
  4528. if (is_object() and init.size() == 2 and init.begin()->is_string())
  4529. {
  4530. const string_t key = *init.begin();
  4531. push_back(typename object_t::value_type(key, *(init.begin() + 1)));
  4532. }
  4533. else
  4534. {
  4535. push_back(basic_json(init));
  4536. }
  4537. }
  4538. /*!
  4539. @brief add an object to an object
  4540. @copydoc push_back(std::initializer_list<basic_json>)
  4541. */
  4542. reference operator+=(std::initializer_list<basic_json> init)
  4543. {
  4544. push_back(init);
  4545. return *this;
  4546. }
  4547. /*!
  4548. @brief add an object to an array
  4549. Creates a JSON value from the passed parameters @a args to the end of the
  4550. JSON value. If the function is called on a JSON null value, an empty array
  4551. is created before appending the value created from @a args.
  4552. @param[in] args arguments to forward to a constructor of @ref basic_json
  4553. @tparam Args compatible types to create a @ref basic_json object
  4554. @throw type_error.311 when called on a type other than JSON array or
  4555. null; example: `"cannot use emplace_back() with number"`
  4556. @complexity Amortized constant.
  4557. @liveexample{The example shows how `push_back()` can be used to add
  4558. elements to a JSON array. Note how the `null` value was silently converted
  4559. to a JSON array.,emplace_back}
  4560. @since version 2.0.8
  4561. */
  4562. template<class... Args>
  4563. void emplace_back(Args&& ... args)
  4564. {
  4565. // emplace_back only works for null objects or arrays
  4566. if (not(is_null() or is_array()))
  4567. {
  4568. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + type_name()));
  4569. }
  4570. // transform null object into an array
  4571. if (is_null())
  4572. {
  4573. m_type = value_t::array;
  4574. m_value = value_t::array;
  4575. assert_invariant();
  4576. }
  4577. // add element to array (perfect forwarding)
  4578. m_value.array->emplace_back(std::forward<Args>(args)...);
  4579. }
  4580. /*!
  4581. @brief add an object to an object if key does not exist
  4582. Inserts a new element into a JSON object constructed in-place with the
  4583. given @a args if there is no element with the key in the container. If the
  4584. function is called on a JSON null value, an empty object is created before
  4585. appending the value created from @a args.
  4586. @param[in] args arguments to forward to a constructor of @ref basic_json
  4587. @tparam Args compatible types to create a @ref basic_json object
  4588. @return a pair consisting of an iterator to the inserted element, or the
  4589. already-existing element if no insertion happened, and a bool
  4590. denoting whether the insertion took place.
  4591. @throw type_error.311 when called on a type other than JSON object or
  4592. null; example: `"cannot use emplace() with number"`
  4593. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  4594. @liveexample{The example shows how `emplace()` can be used to add elements
  4595. to a JSON object. Note how the `null` value was silently converted to a
  4596. JSON object. Further note how no value is added if there was already one
  4597. value stored with the same key.,emplace}
  4598. @since version 2.0.8
  4599. */
  4600. template<class... Args>
  4601. std::pair<iterator, bool> emplace(Args&& ... args)
  4602. {
  4603. // emplace only works for null objects or arrays
  4604. if (not(is_null() or is_object()))
  4605. {
  4606. JSON_THROW(type_error::create(311, "cannot use emplace() with " + type_name()));
  4607. }
  4608. // transform null object into an object
  4609. if (is_null())
  4610. {
  4611. m_type = value_t::object;
  4612. m_value = value_t::object;
  4613. assert_invariant();
  4614. }
  4615. // add element to array (perfect forwarding)
  4616. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  4617. // create result iterator and set iterator to the result of emplace
  4618. auto it = begin();
  4619. it.m_it.object_iterator = res.first;
  4620. // return pair of iterator and boolean
  4621. return {it, res.second};
  4622. }
  4623. /*!
  4624. @brief inserts element
  4625. Inserts element @a val before iterator @a pos.
  4626. @param[in] pos iterator before which the content will be inserted; may be
  4627. the end() iterator
  4628. @param[in] val element to insert
  4629. @return iterator pointing to the inserted @a val.
  4630. @throw type_error.309 if called on JSON values other than arrays;
  4631. example: `"cannot use insert() with string"`
  4632. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4633. example: `"iterator does not fit current value"`
  4634. @complexity Constant plus linear in the distance between @a pos and end of
  4635. the container.
  4636. @liveexample{The example shows how `insert()` is used.,insert}
  4637. @since version 1.0.0
  4638. */
  4639. iterator insert(const_iterator pos, const basic_json& val)
  4640. {
  4641. // insert only works for arrays
  4642. if (is_array())
  4643. {
  4644. // check if iterator pos fits to this JSON value
  4645. if (pos.m_object != this)
  4646. {
  4647. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4648. }
  4649. // insert to array and return iterator
  4650. iterator result(this);
  4651. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  4652. return result;
  4653. }
  4654. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4655. }
  4656. /*!
  4657. @brief inserts element
  4658. @copydoc insert(const_iterator, const basic_json&)
  4659. */
  4660. iterator insert(const_iterator pos, basic_json&& val)
  4661. {
  4662. return insert(pos, val);
  4663. }
  4664. /*!
  4665. @brief inserts elements
  4666. Inserts @a cnt copies of @a val before iterator @a pos.
  4667. @param[in] pos iterator before which the content will be inserted; may be
  4668. the end() iterator
  4669. @param[in] cnt number of copies of @a val to insert
  4670. @param[in] val element to insert
  4671. @return iterator pointing to the first element inserted, or @a pos if
  4672. `cnt==0`
  4673. @throw type_error.309 if called on JSON values other than arrays; example:
  4674. `"cannot use insert() with string"`
  4675. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4676. example: `"iterator does not fit current value"`
  4677. @complexity Linear in @a cnt plus linear in the distance between @a pos
  4678. and end of the container.
  4679. @liveexample{The example shows how `insert()` is used.,insert__count}
  4680. @since version 1.0.0
  4681. */
  4682. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  4683. {
  4684. // insert only works for arrays
  4685. if (is_array())
  4686. {
  4687. // check if iterator pos fits to this JSON value
  4688. if (pos.m_object != this)
  4689. {
  4690. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4691. }
  4692. // insert to array and return iterator
  4693. iterator result(this);
  4694. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  4695. return result;
  4696. }
  4697. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4698. }
  4699. /*!
  4700. @brief inserts elements
  4701. Inserts elements from range `[first, last)` before iterator @a pos.
  4702. @param[in] pos iterator before which the content will be inserted; may be
  4703. the end() iterator
  4704. @param[in] first begin of the range of elements to insert
  4705. @param[in] last end of the range of elements to insert
  4706. @throw type_error.309 if called on JSON values other than arrays; example:
  4707. `"cannot use insert() with string"`
  4708. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4709. example: `"iterator does not fit current value"`
  4710. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4711. same JSON value; example: `"iterators do not fit"`
  4712. @throw invalid_iterator.211 if @a first or @a last are iterators into
  4713. container for which insert is called; example: `"passed iterators may not
  4714. belong to container"`
  4715. @return iterator pointing to the first element inserted, or @a pos if
  4716. `first==last`
  4717. @complexity Linear in `std::distance(first, last)` plus linear in the
  4718. distance between @a pos and end of the container.
  4719. @liveexample{The example shows how `insert()` is used.,insert__range}
  4720. @since version 1.0.0
  4721. */
  4722. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  4723. {
  4724. // insert only works for arrays
  4725. if (not is_array())
  4726. {
  4727. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4728. }
  4729. // check if iterator pos fits to this JSON value
  4730. if (pos.m_object != this)
  4731. {
  4732. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4733. }
  4734. // check if range iterators belong to the same JSON object
  4735. if (first.m_object != last.m_object)
  4736. {
  4737. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4738. }
  4739. if (first.m_object == this or last.m_object == this)
  4740. {
  4741. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  4742. }
  4743. // insert to array and return iterator
  4744. iterator result(this);
  4745. result.m_it.array_iterator = m_value.array->insert(
  4746. pos.m_it.array_iterator,
  4747. first.m_it.array_iterator,
  4748. last.m_it.array_iterator);
  4749. return result;
  4750. }
  4751. /*!
  4752. @brief inserts elements
  4753. Inserts elements from initializer list @a ilist before iterator @a pos.
  4754. @param[in] pos iterator before which the content will be inserted; may be
  4755. the end() iterator
  4756. @param[in] ilist initializer list to insert the values from
  4757. @throw type_error.309 if called on JSON values other than arrays; example:
  4758. `"cannot use insert() with string"`
  4759. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  4760. example: `"iterator does not fit current value"`
  4761. @return iterator pointing to the first element inserted, or @a pos if
  4762. `ilist` is empty
  4763. @complexity Linear in `ilist.size()` plus linear in the distance between
  4764. @a pos and end of the container.
  4765. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  4766. @since version 1.0.0
  4767. */
  4768. iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
  4769. {
  4770. // insert only works for arrays
  4771. if (not is_array())
  4772. {
  4773. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4774. }
  4775. // check if iterator pos fits to this JSON value
  4776. if (pos.m_object != this)
  4777. {
  4778. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  4779. }
  4780. // insert to array and return iterator
  4781. iterator result(this);
  4782. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
  4783. return result;
  4784. }
  4785. /*!
  4786. @brief inserts elements
  4787. Inserts elements from range `[first, last)`.
  4788. @param[in] first begin of the range of elements to insert
  4789. @param[in] last end of the range of elements to insert
  4790. @throw type_error.309 if called on JSON values other than objects; example:
  4791. `"cannot use insert() with string"`
  4792. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  4793. point to an object; example: `"iterators first and last must point to
  4794. objects"`
  4795. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  4796. same JSON value; example: `"iterators do not fit"`
  4797. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  4798. of elements to insert.
  4799. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  4800. @since version 3.0.0
  4801. */
  4802. void insert(const_iterator first, const_iterator last)
  4803. {
  4804. // insert only works for objects
  4805. if (not is_object())
  4806. {
  4807. JSON_THROW(type_error::create(309, "cannot use insert() with " + type_name()));
  4808. }
  4809. // check if range iterators belong to the same JSON object
  4810. if (first.m_object != last.m_object)
  4811. {
  4812. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  4813. }
  4814. // passed iterators must belong to objects
  4815. if (not first.m_object->is_object() or not first.m_object->is_object())
  4816. {
  4817. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  4818. }
  4819. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  4820. }
  4821. /*!
  4822. @brief exchanges the values
  4823. Exchanges the contents of the JSON value with those of @a other. Does not
  4824. invoke any move, copy, or swap operations on individual elements. All
  4825. iterators and references remain valid. The past-the-end iterator is
  4826. invalidated.
  4827. @param[in,out] other JSON value to exchange the contents with
  4828. @complexity Constant.
  4829. @liveexample{The example below shows how JSON values can be swapped with
  4830. `swap()`.,swap__reference}
  4831. @since version 1.0.0
  4832. */
  4833. void swap(reference other) noexcept (
  4834. std::is_nothrow_move_constructible<value_t>::value and
  4835. std::is_nothrow_move_assignable<value_t>::value and
  4836. std::is_nothrow_move_constructible<json_value>::value and
  4837. std::is_nothrow_move_assignable<json_value>::value
  4838. )
  4839. {
  4840. std::swap(m_type, other.m_type);
  4841. std::swap(m_value, other.m_value);
  4842. assert_invariant();
  4843. }
  4844. /*!
  4845. @brief exchanges the values
  4846. Exchanges the contents of a JSON array with those of @a other. Does not
  4847. invoke any move, copy, or swap operations on individual elements. All
  4848. iterators and references remain valid. The past-the-end iterator is
  4849. invalidated.
  4850. @param[in,out] other array to exchange the contents with
  4851. @throw type_error.310 when JSON value is not an array; example: `"cannot
  4852. use swap() with string"`
  4853. @complexity Constant.
  4854. @liveexample{The example below shows how arrays can be swapped with
  4855. `swap()`.,swap__array_t}
  4856. @since version 1.0.0
  4857. */
  4858. void swap(array_t& other)
  4859. {
  4860. // swap only works for arrays
  4861. if (is_array())
  4862. {
  4863. std::swap(*(m_value.array), other);
  4864. }
  4865. else
  4866. {
  4867. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4868. }
  4869. }
  4870. /*!
  4871. @brief exchanges the values
  4872. Exchanges the contents of a JSON object with those of @a other. Does not
  4873. invoke any move, copy, or swap operations on individual elements. All
  4874. iterators and references remain valid. The past-the-end iterator is
  4875. invalidated.
  4876. @param[in,out] other object to exchange the contents with
  4877. @throw type_error.310 when JSON value is not an object; example:
  4878. `"cannot use swap() with string"`
  4879. @complexity Constant.
  4880. @liveexample{The example below shows how objects can be swapped with
  4881. `swap()`.,swap__object_t}
  4882. @since version 1.0.0
  4883. */
  4884. void swap(object_t& other)
  4885. {
  4886. // swap only works for objects
  4887. if (is_object())
  4888. {
  4889. std::swap(*(m_value.object), other);
  4890. }
  4891. else
  4892. {
  4893. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4894. }
  4895. }
  4896. /*!
  4897. @brief exchanges the values
  4898. Exchanges the contents of a JSON string with those of @a other. Does not
  4899. invoke any move, copy, or swap operations on individual elements. All
  4900. iterators and references remain valid. The past-the-end iterator is
  4901. invalidated.
  4902. @param[in,out] other string to exchange the contents with
  4903. @throw type_error.310 when JSON value is not a string; example: `"cannot
  4904. use swap() with boolean"`
  4905. @complexity Constant.
  4906. @liveexample{The example below shows how strings can be swapped with
  4907. `swap()`.,swap__string_t}
  4908. @since version 1.0.0
  4909. */
  4910. void swap(string_t& other)
  4911. {
  4912. // swap only works for strings
  4913. if (is_string())
  4914. {
  4915. std::swap(*(m_value.string), other);
  4916. }
  4917. else
  4918. {
  4919. JSON_THROW(type_error::create(310, "cannot use swap() with " + type_name()));
  4920. }
  4921. }
  4922. /// @}
  4923. public:
  4924. //////////////////////////////////////////
  4925. // lexicographical comparison operators //
  4926. //////////////////////////////////////////
  4927. /// @name lexicographical comparison operators
  4928. /// @{
  4929. /*!
  4930. @brief comparison: equal
  4931. Compares two JSON values for equality according to the following rules:
  4932. - Two JSON values are equal if (1) they are from the same type and (2)
  4933. their stored values are the same according to their respective
  4934. `operator==`.
  4935. - Integer and floating-point numbers are automatically converted before
  4936. comparison. Floating-point numbers are compared indirectly: two
  4937. floating-point numbers `f1` and `f2` are considered equal if neither
  4938. `f1 > f2` nor `f2 > f1` holds. Note than two NaN values are always
  4939. treated as unequal.
  4940. - Two JSON null values are equal.
  4941. @note NaN values never compare equal to themselves or to other NaN values.
  4942. @param[in] lhs first JSON value to consider
  4943. @param[in] rhs second JSON value to consider
  4944. @return whether the values @a lhs and @a rhs are equal
  4945. @complexity Linear.
  4946. @liveexample{The example demonstrates comparing several JSON
  4947. types.,operator__equal}
  4948. @since version 1.0.0
  4949. */
  4950. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  4951. {
  4952. const auto lhs_type = lhs.type();
  4953. const auto rhs_type = rhs.type();
  4954. if (lhs_type == rhs_type)
  4955. {
  4956. switch (lhs_type)
  4957. {
  4958. case value_t::array:
  4959. {
  4960. return *lhs.m_value.array == *rhs.m_value.array;
  4961. }
  4962. case value_t::object:
  4963. {
  4964. return *lhs.m_value.object == *rhs.m_value.object;
  4965. }
  4966. case value_t::null:
  4967. {
  4968. return true;
  4969. }
  4970. case value_t::string:
  4971. {
  4972. return *lhs.m_value.string == *rhs.m_value.string;
  4973. }
  4974. case value_t::boolean:
  4975. {
  4976. return lhs.m_value.boolean == rhs.m_value.boolean;
  4977. }
  4978. case value_t::number_integer:
  4979. {
  4980. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  4981. }
  4982. case value_t::number_unsigned:
  4983. {
  4984. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  4985. }
  4986. case value_t::number_float:
  4987. {
  4988. return lhs.m_value.number_float == rhs.m_value.number_float;
  4989. }
  4990. default:
  4991. {
  4992. return false;
  4993. }
  4994. }
  4995. }
  4996. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4997. {
  4998. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  4999. }
  5000. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  5001. {
  5002. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  5003. }
  5004. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  5005. {
  5006. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  5007. }
  5008. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  5009. {
  5010. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  5011. }
  5012. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  5013. {
  5014. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  5015. }
  5016. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  5017. {
  5018. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  5019. }
  5020. return false;
  5021. }
  5022. /*!
  5023. @brief comparison: equal
  5024. @copydoc operator==(const_reference, const_reference)
  5025. */
  5026. template<typename ScalarType, typename std::enable_if<
  5027. std::is_scalar<ScalarType>::value, int>::type = 0>
  5028. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  5029. {
  5030. return (lhs == basic_json(rhs));
  5031. }
  5032. /*!
  5033. @brief comparison: equal
  5034. @copydoc operator==(const_reference, const_reference)
  5035. */
  5036. template<typename ScalarType, typename std::enable_if<
  5037. std::is_scalar<ScalarType>::value, int>::type = 0>
  5038. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  5039. {
  5040. return (basic_json(lhs) == rhs);
  5041. }
  5042. /*!
  5043. @brief comparison: not equal
  5044. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  5045. @param[in] lhs first JSON value to consider
  5046. @param[in] rhs second JSON value to consider
  5047. @return whether the values @a lhs and @a rhs are not equal
  5048. @complexity Linear.
  5049. @liveexample{The example demonstrates comparing several JSON
  5050. types.,operator__notequal}
  5051. @since version 1.0.0
  5052. */
  5053. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  5054. {
  5055. return not (lhs == rhs);
  5056. }
  5057. /*!
  5058. @brief comparison: not equal
  5059. @copydoc operator!=(const_reference, const_reference)
  5060. */
  5061. template<typename ScalarType, typename std::enable_if<
  5062. std::is_scalar<ScalarType>::value, int>::type = 0>
  5063. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  5064. {
  5065. return (lhs != basic_json(rhs));
  5066. }
  5067. /*!
  5068. @brief comparison: not equal
  5069. @copydoc operator!=(const_reference, const_reference)
  5070. */
  5071. template<typename ScalarType, typename std::enable_if<
  5072. std::is_scalar<ScalarType>::value, int>::type = 0>
  5073. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  5074. {
  5075. return (basic_json(lhs) != rhs);
  5076. }
  5077. /*!
  5078. @brief comparison: less than
  5079. Compares whether one JSON value @a lhs is less than another JSON value @a
  5080. rhs according to the following rules:
  5081. - If @a lhs and @a rhs have the same type, the values are compared using
  5082. the default `<` operator.
  5083. - Integer and floating-point numbers are automatically converted before
  5084. comparison
  5085. - In case @a lhs and @a rhs have different types, the values are ignored
  5086. and the order of the types is considered, see
  5087. @ref operator<(const value_t, const value_t).
  5088. @param[in] lhs first JSON value to consider
  5089. @param[in] rhs second JSON value to consider
  5090. @return whether @a lhs is less than @a rhs
  5091. @complexity Linear.
  5092. @liveexample{The example demonstrates comparing several JSON
  5093. types.,operator__less}
  5094. @since version 1.0.0
  5095. */
  5096. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  5097. {
  5098. const auto lhs_type = lhs.type();
  5099. const auto rhs_type = rhs.type();
  5100. if (lhs_type == rhs_type)
  5101. {
  5102. switch (lhs_type)
  5103. {
  5104. case value_t::array:
  5105. {
  5106. return *lhs.m_value.array < *rhs.m_value.array;
  5107. }
  5108. case value_t::object:
  5109. {
  5110. return *lhs.m_value.object < *rhs.m_value.object;
  5111. }
  5112. case value_t::null:
  5113. {
  5114. return false;
  5115. }
  5116. case value_t::string:
  5117. {
  5118. return *lhs.m_value.string < *rhs.m_value.string;
  5119. }
  5120. case value_t::boolean:
  5121. {
  5122. return lhs.m_value.boolean < rhs.m_value.boolean;
  5123. }
  5124. case value_t::number_integer:
  5125. {
  5126. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  5127. }
  5128. case value_t::number_unsigned:
  5129. {
  5130. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  5131. }
  5132. case value_t::number_float:
  5133. {
  5134. return lhs.m_value.number_float < rhs.m_value.number_float;
  5135. }
  5136. default:
  5137. {
  5138. return false;
  5139. }
  5140. }
  5141. }
  5142. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  5143. {
  5144. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  5145. }
  5146. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  5147. {
  5148. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  5149. }
  5150. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  5151. {
  5152. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  5153. }
  5154. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  5155. {
  5156. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  5157. }
  5158. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  5159. {
  5160. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  5161. }
  5162. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  5163. {
  5164. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  5165. }
  5166. // We only reach this line if we cannot compare values. In that case,
  5167. // we compare types. Note we have to call the operator explicitly,
  5168. // because MSVC has problems otherwise.
  5169. return operator<(lhs_type, rhs_type);
  5170. }
  5171. /*!
  5172. @brief comparison: less than
  5173. @copydoc operator<(const_reference, const_reference)
  5174. */
  5175. template<typename ScalarType, typename std::enable_if<
  5176. std::is_scalar<ScalarType>::value, int>::type = 0>
  5177. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  5178. {
  5179. return (lhs < basic_json(rhs));
  5180. }
  5181. /*!
  5182. @brief comparison: less than
  5183. @copydoc operator<(const_reference, const_reference)
  5184. */
  5185. template<typename ScalarType, typename std::enable_if<
  5186. std::is_scalar<ScalarType>::value, int>::type = 0>
  5187. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  5188. {
  5189. return (basic_json(lhs) < rhs);
  5190. }
  5191. /*!
  5192. @brief comparison: less than or equal
  5193. Compares whether one JSON value @a lhs is less than or equal to another
  5194. JSON value by calculating `not (rhs < lhs)`.
  5195. @param[in] lhs first JSON value to consider
  5196. @param[in] rhs second JSON value to consider
  5197. @return whether @a lhs is less than or equal to @a rhs
  5198. @complexity Linear.
  5199. @liveexample{The example demonstrates comparing several JSON
  5200. types.,operator__greater}
  5201. @since version 1.0.0
  5202. */
  5203. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  5204. {
  5205. return not (rhs < lhs);
  5206. }
  5207. /*!
  5208. @brief comparison: less than or equal
  5209. @copydoc operator<=(const_reference, const_reference)
  5210. */
  5211. template<typename ScalarType, typename std::enable_if<
  5212. std::is_scalar<ScalarType>::value, int>::type = 0>
  5213. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  5214. {
  5215. return (lhs <= basic_json(rhs));
  5216. }
  5217. /*!
  5218. @brief comparison: less than or equal
  5219. @copydoc operator<=(const_reference, const_reference)
  5220. */
  5221. template<typename ScalarType, typename std::enable_if<
  5222. std::is_scalar<ScalarType>::value, int>::type = 0>
  5223. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  5224. {
  5225. return (basic_json(lhs) <= rhs);
  5226. }
  5227. /*!
  5228. @brief comparison: greater than
  5229. Compares whether one JSON value @a lhs is greater than another
  5230. JSON value by calculating `not (lhs <= rhs)`.
  5231. @param[in] lhs first JSON value to consider
  5232. @param[in] rhs second JSON value to consider
  5233. @return whether @a lhs is greater than to @a rhs
  5234. @complexity Linear.
  5235. @liveexample{The example demonstrates comparing several JSON
  5236. types.,operator__lessequal}
  5237. @since version 1.0.0
  5238. */
  5239. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  5240. {
  5241. return not (lhs <= rhs);
  5242. }
  5243. /*!
  5244. @brief comparison: greater than
  5245. @copydoc operator>(const_reference, const_reference)
  5246. */
  5247. template<typename ScalarType, typename std::enable_if<
  5248. std::is_scalar<ScalarType>::value, int>::type = 0>
  5249. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  5250. {
  5251. return (lhs > basic_json(rhs));
  5252. }
  5253. /*!
  5254. @brief comparison: greater than
  5255. @copydoc operator>(const_reference, const_reference)
  5256. */
  5257. template<typename ScalarType, typename std::enable_if<
  5258. std::is_scalar<ScalarType>::value, int>::type = 0>
  5259. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  5260. {
  5261. return (basic_json(lhs) > rhs);
  5262. }
  5263. /*!
  5264. @brief comparison: greater than or equal
  5265. Compares whether one JSON value @a lhs is greater than or equal to another
  5266. JSON value by calculating `not (lhs < rhs)`.
  5267. @param[in] lhs first JSON value to consider
  5268. @param[in] rhs second JSON value to consider
  5269. @return whether @a lhs is greater than or equal to @a rhs
  5270. @complexity Linear.
  5271. @liveexample{The example demonstrates comparing several JSON
  5272. types.,operator__greaterequal}
  5273. @since version 1.0.0
  5274. */
  5275. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  5276. {
  5277. return not (lhs < rhs);
  5278. }
  5279. /*!
  5280. @brief comparison: greater than or equal
  5281. @copydoc operator>=(const_reference, const_reference)
  5282. */
  5283. template<typename ScalarType, typename std::enable_if<
  5284. std::is_scalar<ScalarType>::value, int>::type = 0>
  5285. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  5286. {
  5287. return (lhs >= basic_json(rhs));
  5288. }
  5289. /*!
  5290. @brief comparison: greater than or equal
  5291. @copydoc operator>=(const_reference, const_reference)
  5292. */
  5293. template<typename ScalarType, typename std::enable_if<
  5294. std::is_scalar<ScalarType>::value, int>::type = 0>
  5295. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  5296. {
  5297. return (basic_json(lhs) >= rhs);
  5298. }
  5299. /// @}
  5300. ///////////////////
  5301. // serialization //
  5302. ///////////////////
  5303. /// @name serialization
  5304. /// @{
  5305. private:
  5306. /*!
  5307. @brief wrapper around the serialization functions
  5308. */
  5309. class serializer
  5310. {
  5311. private:
  5312. serializer(const serializer&) = delete;
  5313. serializer& operator=(const serializer&) = delete;
  5314. public:
  5315. /*!
  5316. @param[in] s output stream to serialize to
  5317. */
  5318. serializer(std::ostream& s)
  5319. : o(s), loc(std::localeconv()),
  5320. thousands_sep(!loc->thousands_sep ? '\0' : loc->thousands_sep[0]),
  5321. decimal_point(!loc->decimal_point ? '\0' : loc->decimal_point[0])
  5322. {}
  5323. /*!
  5324. @brief internal implementation of the serialization function
  5325. This function is called by the public member function dump and
  5326. organizes the serialization internally. The indentation level is
  5327. propagated as additional parameter. In case of arrays and objects, the
  5328. function is called recursively.
  5329. - strings and object keys are escaped using `escape_string()`
  5330. - integer numbers are converted implicitly via `operator<<`
  5331. - floating-point numbers are converted to a string using `"%g"` format
  5332. @param[in] val value to serialize
  5333. @param[in] pretty_print whether the output shall be pretty-printed
  5334. @param[in] indent_step the indent level
  5335. @param[in] current_indent the current indent level (only used internally)
  5336. */
  5337. void dump(const basic_json& val,
  5338. const bool pretty_print,
  5339. const unsigned int indent_step,
  5340. const unsigned int current_indent = 0)
  5341. {
  5342. switch (val.m_type)
  5343. {
  5344. case value_t::object:
  5345. {
  5346. if (val.m_value.object->empty())
  5347. {
  5348. o.write("{}", 2);
  5349. return;
  5350. }
  5351. if (pretty_print)
  5352. {
  5353. o.write("{\n", 2);
  5354. // variable to hold indentation for recursive calls
  5355. const auto new_indent = current_indent + indent_step;
  5356. if (indent_string.size() < new_indent)
  5357. {
  5358. indent_string.resize(new_indent, ' ');
  5359. }
  5360. // first n-1 elements
  5361. auto i = val.m_value.object->cbegin();
  5362. for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5363. {
  5364. o.write(indent_string.c_str(), static_cast<std::streamsize>(new_indent));
  5365. o.put('\"');
  5366. dump_escaped(i->first);
  5367. o.write("\": ", 3);
  5368. dump(i->second, true, indent_step, new_indent);
  5369. o.write(",\n", 2);
  5370. }
  5371. // last element
  5372. assert(i != val.m_value.object->cend());
  5373. o.write(indent_string.c_str(), static_cast<std::streamsize>(new_indent));
  5374. o.put('\"');
  5375. dump_escaped(i->first);
  5376. o.write("\": ", 3);
  5377. dump(i->second, true, indent_step, new_indent);
  5378. o.put('\n');
  5379. o.write(indent_string.c_str(), static_cast<std::streamsize>(current_indent));
  5380. o.put('}');
  5381. }
  5382. else
  5383. {
  5384. o.put('{');
  5385. // first n-1 elements
  5386. auto i = val.m_value.object->cbegin();
  5387. for (size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5388. {
  5389. o.put('\"');
  5390. dump_escaped(i->first);
  5391. o.write("\":", 2);
  5392. dump(i->second, false, indent_step, current_indent);
  5393. o.put(',');
  5394. }
  5395. // last element
  5396. assert(i != val.m_value.object->cend());
  5397. o.put('\"');
  5398. dump_escaped(i->first);
  5399. o.write("\":", 2);
  5400. dump(i->second, false, indent_step, current_indent);
  5401. o.put('}');
  5402. }
  5403. return;
  5404. }
  5405. case value_t::array:
  5406. {
  5407. if (val.m_value.array->empty())
  5408. {
  5409. o.write("[]", 2);
  5410. return;
  5411. }
  5412. if (pretty_print)
  5413. {
  5414. o.write("[\n", 2);
  5415. // variable to hold indentation for recursive calls
  5416. const auto new_indent = current_indent + indent_step;
  5417. if (indent_string.size() < new_indent)
  5418. {
  5419. indent_string.resize(new_indent, ' ');
  5420. }
  5421. // first n-1 elements
  5422. for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i)
  5423. {
  5424. o.write(indent_string.c_str(), static_cast<std::streamsize>(new_indent));
  5425. dump(*i, true, indent_step, new_indent);
  5426. o.write(",\n", 2);
  5427. }
  5428. // last element
  5429. assert(not val.m_value.array->empty());
  5430. o.write(indent_string.c_str(), static_cast<std::streamsize>(new_indent));
  5431. dump(val.m_value.array->back(), true, indent_step, new_indent);
  5432. o.put('\n');
  5433. o.write(indent_string.c_str(), static_cast<std::streamsize>(current_indent));
  5434. o.put(']');
  5435. }
  5436. else
  5437. {
  5438. o.put('[');
  5439. // first n-1 elements
  5440. for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i)
  5441. {
  5442. dump(*i, false, indent_step, current_indent);
  5443. o.put(',');
  5444. }
  5445. // last element
  5446. assert(not val.m_value.array->empty());
  5447. dump(val.m_value.array->back(), false, indent_step, current_indent);
  5448. o.put(']');
  5449. }
  5450. return;
  5451. }
  5452. case value_t::string:
  5453. {
  5454. o.put('\"');
  5455. dump_escaped(*val.m_value.string);
  5456. o.put('\"');
  5457. return;
  5458. }
  5459. case value_t::boolean:
  5460. {
  5461. if (val.m_value.boolean)
  5462. {
  5463. o.write("true", 4);
  5464. }
  5465. else
  5466. {
  5467. o.write("false", 5);
  5468. }
  5469. return;
  5470. }
  5471. case value_t::number_integer:
  5472. {
  5473. dump_integer(val.m_value.number_integer);
  5474. return;
  5475. }
  5476. case value_t::number_unsigned:
  5477. {
  5478. dump_integer(val.m_value.number_unsigned);
  5479. return;
  5480. }
  5481. case value_t::number_float:
  5482. {
  5483. dump_float(val.m_value.number_float);
  5484. return;
  5485. }
  5486. case value_t::discarded:
  5487. {
  5488. o.write("<discarded>", 11);
  5489. return;
  5490. }
  5491. case value_t::null:
  5492. {
  5493. o.write("null", 4);
  5494. return;
  5495. }
  5496. }
  5497. }
  5498. private:
  5499. /*!
  5500. @brief calculates the extra space to escape a JSON string
  5501. @param[in] s the string to escape
  5502. @return the number of characters required to escape string @a s
  5503. @complexity Linear in the length of string @a s.
  5504. */
  5505. static std::size_t extra_space(const string_t& s) noexcept
  5506. {
  5507. return std::accumulate(s.begin(), s.end(), size_t{},
  5508. [](size_t res, typename string_t::value_type c)
  5509. {
  5510. switch (c)
  5511. {
  5512. case '"':
  5513. case '\\':
  5514. case '\b':
  5515. case '\f':
  5516. case '\n':
  5517. case '\r':
  5518. case '\t':
  5519. {
  5520. // from c (1 byte) to \x (2 bytes)
  5521. return res + 1;
  5522. }
  5523. case 0x00:
  5524. case 0x01:
  5525. case 0x02:
  5526. case 0x03:
  5527. case 0x04:
  5528. case 0x05:
  5529. case 0x06:
  5530. case 0x07:
  5531. case 0x0b:
  5532. case 0x0e:
  5533. case 0x0f:
  5534. case 0x10:
  5535. case 0x11:
  5536. case 0x12:
  5537. case 0x13:
  5538. case 0x14:
  5539. case 0x15:
  5540. case 0x16:
  5541. case 0x17:
  5542. case 0x18:
  5543. case 0x19:
  5544. case 0x1a:
  5545. case 0x1b:
  5546. case 0x1c:
  5547. case 0x1d:
  5548. case 0x1e:
  5549. case 0x1f:
  5550. {
  5551. // from c (1 byte) to \uxxxx (6 bytes)
  5552. return res + 5;
  5553. }
  5554. default:
  5555. {
  5556. return res;
  5557. }
  5558. }
  5559. });
  5560. }
  5561. /*!
  5562. @brief dump escaped string
  5563. Escape a string by replacing certain special characters by a sequence
  5564. of an escape character (backslash) and another character and other
  5565. control characters by a sequence of "\u" followed by a four-digit hex
  5566. representation. The escaped string is written to output stream @a o.
  5567. @param[in] s the string to escape
  5568. @complexity Linear in the length of string @a s.
  5569. */
  5570. void dump_escaped(const string_t& s) const
  5571. {
  5572. const auto space = extra_space(s);
  5573. if (space == 0)
  5574. {
  5575. o.write(s.c_str(), static_cast<std::streamsize>(s.size()));
  5576. return;
  5577. }
  5578. // create a result string of necessary size
  5579. string_t result(s.size() + space, '\\');
  5580. std::size_t pos = 0;
  5581. for (const auto& c : s)
  5582. {
  5583. switch (c)
  5584. {
  5585. // quotation mark (0x22)
  5586. case '"':
  5587. {
  5588. result[pos + 1] = '"';
  5589. pos += 2;
  5590. break;
  5591. }
  5592. // reverse solidus (0x5c)
  5593. case '\\':
  5594. {
  5595. // nothing to change
  5596. pos += 2;
  5597. break;
  5598. }
  5599. // backspace (0x08)
  5600. case '\b':
  5601. {
  5602. result[pos + 1] = 'b';
  5603. pos += 2;
  5604. break;
  5605. }
  5606. // formfeed (0x0c)
  5607. case '\f':
  5608. {
  5609. result[pos + 1] = 'f';
  5610. pos += 2;
  5611. break;
  5612. }
  5613. // newline (0x0a)
  5614. case '\n':
  5615. {
  5616. result[pos + 1] = 'n';
  5617. pos += 2;
  5618. break;
  5619. }
  5620. // carriage return (0x0d)
  5621. case '\r':
  5622. {
  5623. result[pos + 1] = 'r';
  5624. pos += 2;
  5625. break;
  5626. }
  5627. // horizontal tab (0x09)
  5628. case '\t':
  5629. {
  5630. result[pos + 1] = 't';
  5631. pos += 2;
  5632. break;
  5633. }
  5634. case 0x00:
  5635. case 0x01:
  5636. case 0x02:
  5637. case 0x03:
  5638. case 0x04:
  5639. case 0x05:
  5640. case 0x06:
  5641. case 0x07:
  5642. case 0x0b:
  5643. case 0x0e:
  5644. case 0x0f:
  5645. case 0x10:
  5646. case 0x11:
  5647. case 0x12:
  5648. case 0x13:
  5649. case 0x14:
  5650. case 0x15:
  5651. case 0x16:
  5652. case 0x17:
  5653. case 0x18:
  5654. case 0x19:
  5655. case 0x1a:
  5656. case 0x1b:
  5657. case 0x1c:
  5658. case 0x1d:
  5659. case 0x1e:
  5660. case 0x1f:
  5661. {
  5662. // convert a number 0..15 to its hex representation
  5663. // (0..f)
  5664. static const char hexify[16] =
  5665. {
  5666. '0', '1', '2', '3', '4', '5', '6', '7',
  5667. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  5668. };
  5669. // print character c as \uxxxx
  5670. for (const char m :
  5671. { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
  5672. })
  5673. {
  5674. result[++pos] = m;
  5675. }
  5676. ++pos;
  5677. break;
  5678. }
  5679. default:
  5680. {
  5681. // all other characters are added as-is
  5682. result[pos++] = c;
  5683. break;
  5684. }
  5685. }
  5686. }
  5687. assert(pos == s.size() + space);
  5688. o.write(result.c_str(), static_cast<std::streamsize>(result.size()));
  5689. }
  5690. /*!
  5691. @brief dump an integer
  5692. Dump a given integer to output stream @a o. Works internally with
  5693. @a number_buffer.
  5694. @param[in] x integer number (signed or unsigned) to dump
  5695. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  5696. */
  5697. template<typename NumberType, detail::enable_if_t <
  5698. std::is_same<NumberType, number_unsigned_t>::value or
  5699. std::is_same<NumberType, number_integer_t>::value, int> = 0>
  5700. void dump_integer(NumberType x)
  5701. {
  5702. // special case for "0"
  5703. if (x == 0)
  5704. {
  5705. o.put('0');
  5706. return;
  5707. }
  5708. const bool is_negative = x < 0;
  5709. size_t i = 0;
  5710. // spare 1 byte for '\0'
  5711. while (x != 0 and i < number_buffer.size() - 1)
  5712. {
  5713. const auto digit = std::labs(static_cast<long>(x % 10));
  5714. number_buffer[i++] = static_cast<char>('0' + digit);
  5715. x /= 10;
  5716. }
  5717. // make sure the number has been processed completely
  5718. assert(x == 0);
  5719. if (is_negative)
  5720. {
  5721. // make sure there is capacity for the '-'
  5722. assert(i < number_buffer.size() - 2);
  5723. number_buffer[i++] = '-';
  5724. }
  5725. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  5726. o.write(number_buffer.data(), static_cast<std::streamsize>(i));
  5727. }
  5728. /*!
  5729. @brief dump a floating-point number
  5730. Dump a given floating-point number to output stream @a o. Works
  5731. internally with @a number_buffer.
  5732. @param[in] x floating-point number to dump
  5733. */
  5734. void dump_float(number_float_t x)
  5735. {
  5736. // NaN / inf
  5737. if (not std::isfinite(x) or std::isnan(x))
  5738. {
  5739. o.write("null", 4);
  5740. return;
  5741. }
  5742. // special case for 0.0 and -0.0
  5743. if (x == 0)
  5744. {
  5745. if (std::signbit(x))
  5746. {
  5747. o.write("-0.0", 4);
  5748. }
  5749. else
  5750. {
  5751. o.write("0.0", 3);
  5752. }
  5753. return;
  5754. }
  5755. // get number of digits for a text -> float -> text round-trip
  5756. static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
  5757. // the actual conversion
  5758. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(),
  5759. "%.*g", d, x);
  5760. // negative value indicates an error
  5761. assert(len > 0);
  5762. // check if buffer was large enough
  5763. assert(static_cast<size_t>(len) < number_buffer.size());
  5764. // erase thousands separator
  5765. if (thousands_sep != '\0')
  5766. {
  5767. const auto end = std::remove(number_buffer.begin(),
  5768. number_buffer.begin() + len,
  5769. thousands_sep);
  5770. std::fill(end, number_buffer.end(), '\0');
  5771. assert((end - number_buffer.begin()) <= len);
  5772. len = (end - number_buffer.begin());
  5773. }
  5774. // convert decimal point to '.'
  5775. if (decimal_point != '\0' and decimal_point != '.')
  5776. {
  5777. for (auto& c : number_buffer)
  5778. {
  5779. if (c == decimal_point)
  5780. {
  5781. c = '.';
  5782. break;
  5783. }
  5784. }
  5785. }
  5786. o.write(number_buffer.data(), static_cast<std::streamsize>(len));
  5787. // determine if need to append ".0"
  5788. const bool value_is_int_like = std::none_of(number_buffer.begin(),
  5789. number_buffer.begin() + len + 1,
  5790. [](char c)
  5791. {
  5792. return c == '.' or c == 'e';
  5793. });
  5794. if (value_is_int_like)
  5795. {
  5796. o.write(".0", 2);
  5797. }
  5798. }
  5799. private:
  5800. /// the output of the serializer
  5801. std::ostream& o;
  5802. /// a (hopefully) large enough character buffer
  5803. std::array<char, 64> number_buffer{{}};
  5804. /// the locale
  5805. const std::lconv* loc = nullptr;
  5806. /// the locale's thousand separator character
  5807. const char thousands_sep = '\0';
  5808. /// the locale's decimal point character
  5809. const char decimal_point = '\0';
  5810. /// the indentation string
  5811. string_t indent_string = string_t(512, ' ');
  5812. };
  5813. public:
  5814. /*!
  5815. @brief serialize to stream
  5816. Serialize the given JSON value @a j to the output stream @a o. The JSON
  5817. value will be serialized using the @ref dump member function. The
  5818. indentation of the output can be controlled with the member variable
  5819. `width` of the output stream @a o. For instance, using the manipulator
  5820. `std::setw(4)` on @a o sets the indentation level to `4` and the
  5821. serialization result is the same as calling `dump(4)`.
  5822. @param[in,out] o stream to serialize to
  5823. @param[in] j JSON value to serialize
  5824. @return the stream @a o
  5825. @complexity Linear.
  5826. @liveexample{The example below shows the serialization with different
  5827. parameters to `width` to adjust the indentation level.,operator_serialize}
  5828. @since version 1.0.0
  5829. */
  5830. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  5831. {
  5832. // read width member and use it as indentation parameter if nonzero
  5833. const bool pretty_print = (o.width() > 0);
  5834. const auto indentation = (pretty_print ? o.width() : 0);
  5835. // reset width to 0 for subsequent calls to this stream
  5836. o.width(0);
  5837. // do the actual serialization
  5838. serializer s(o);
  5839. s.dump(j, pretty_print, static_cast<unsigned int>(indentation));
  5840. return o;
  5841. }
  5842. /*!
  5843. @brief serialize to stream
  5844. @deprecated This stream operator is deprecated and will be removed in a
  5845. future version of the library. Please use
  5846. @ref std::ostream& operator<<(std::ostream&, const basic_json&)
  5847. instead; that is, replace calls like `j >> o;` with `o << j;`.
  5848. */
  5849. JSON_DEPRECATED
  5850. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  5851. {
  5852. return o << j;
  5853. }
  5854. /// @}
  5855. /////////////////////
  5856. // deserialization //
  5857. /////////////////////
  5858. /// @name deserialization
  5859. /// @{
  5860. /*!
  5861. @brief deserialize from an array
  5862. This function reads from an array of 1-byte values.
  5863. @pre Each element of the container has a size of 1 byte. Violating this
  5864. precondition yields undefined behavior. **This precondition is enforced
  5865. with a static assertion.**
  5866. @param[in] array array to read from
  5867. @param[in] cb a parser callback function of type @ref parser_callback_t
  5868. which is used to control the deserialization by filtering unwanted values
  5869. (optional)
  5870. @return result of the deserialization
  5871. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  5872. of input; expected string literal""`
  5873. @throw parse_error.102 if to_unicode fails or surrogate error
  5874. @throw parse_error.103 if to_unicode fails
  5875. @complexity Linear in the length of the input. The parser is a predictive
  5876. LL(1) parser. The complexity can be higher if the parser callback function
  5877. @a cb has a super-linear complexity.
  5878. @note A UTF-8 byte order mark is silently ignored.
  5879. @liveexample{The example below demonstrates the `parse()` function reading
  5880. from an array.,parse__array__parser_callback_t}
  5881. @since version 2.0.3
  5882. */
  5883. template<class T, std::size_t N>
  5884. static basic_json parse(T (&array)[N],
  5885. const parser_callback_t cb = nullptr)
  5886. {
  5887. // delegate the call to the iterator-range parse overload
  5888. return parse(std::begin(array), std::end(array), cb);
  5889. }
  5890. /*!
  5891. @brief deserialize from string literal
  5892. @tparam CharT character/literal type with size of 1 byte
  5893. @param[in] s string literal to read a serialized JSON value from
  5894. @param[in] cb a parser callback function of type @ref parser_callback_t
  5895. which is used to control the deserialization by filtering unwanted values
  5896. (optional)
  5897. @return result of the deserialization
  5898. @throw parse_error.101 in case of an unexpected token
  5899. @throw parse_error.102 if to_unicode fails or surrogate error
  5900. @throw parse_error.103 if to_unicode fails
  5901. @complexity Linear in the length of the input. The parser is a predictive
  5902. LL(1) parser. The complexity can be higher if the parser callback function
  5903. @a cb has a super-linear complexity.
  5904. @note A UTF-8 byte order mark is silently ignored.
  5905. @note String containers like `std::string` or @ref string_t can be parsed
  5906. with @ref parse(const ContiguousContainer&, const parser_callback_t)
  5907. @liveexample{The example below demonstrates the `parse()` function with
  5908. and without callback function.,parse__string__parser_callback_t}
  5909. @sa @ref parse(std::istream&, const parser_callback_t) for a version that
  5910. reads from an input stream
  5911. @since version 1.0.0 (originally for @ref string_t)
  5912. */
  5913. template<typename CharT, typename std::enable_if<
  5914. std::is_pointer<CharT>::value and
  5915. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  5916. sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
  5917. static basic_json parse(const CharT s,
  5918. const parser_callback_t cb = nullptr)
  5919. {
  5920. return parser(reinterpret_cast<const char*>(s), cb).parse();
  5921. }
  5922. /*!
  5923. @brief deserialize from stream
  5924. @param[in,out] i stream to read a serialized JSON value from
  5925. @param[in] cb a parser callback function of type @ref parser_callback_t
  5926. which is used to control the deserialization by filtering unwanted values
  5927. (optional)
  5928. @return result of the deserialization
  5929. @throw parse_error.101 in case of an unexpected token
  5930. @throw parse_error.102 if to_unicode fails or surrogate error
  5931. @throw parse_error.103 if to_unicode fails
  5932. @throw parse_error.111 if input stream is in a bad state
  5933. @complexity Linear in the length of the input. The parser is a predictive
  5934. LL(1) parser. The complexity can be higher if the parser callback function
  5935. @a cb has a super-linear complexity.
  5936. @note A UTF-8 byte order mark is silently ignored.
  5937. @liveexample{The example below demonstrates the `parse()` function with
  5938. and without callback function.,parse__istream__parser_callback_t}
  5939. @sa @ref parse(const CharT, const parser_callback_t) for a version
  5940. that reads from a string
  5941. @since version 1.0.0
  5942. */
  5943. static basic_json parse(std::istream& i,
  5944. const parser_callback_t cb = nullptr)
  5945. {
  5946. return parser(i, cb).parse();
  5947. }
  5948. /*!
  5949. @copydoc parse(std::istream&, const parser_callback_t)
  5950. */
  5951. static basic_json parse(std::istream&& i,
  5952. const parser_callback_t cb = nullptr)
  5953. {
  5954. return parser(i, cb).parse();
  5955. }
  5956. /*!
  5957. @brief deserialize from an iterator range with contiguous storage
  5958. This function reads from an iterator range of a container with contiguous
  5959. storage of 1-byte values. Compatible container types include
  5960. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  5961. `std::initializer_list`. Furthermore, C-style arrays can be used with
  5962. `std::begin()`/`std::end()`. User-defined containers can be used as long
  5963. as they implement random-access iterators and a contiguous storage.
  5964. @pre The iterator range is contiguous. Violating this precondition yields
  5965. undefined behavior. **This precondition is enforced with an assertion.**
  5966. @pre Each element in the range has a size of 1 byte. Violating this
  5967. precondition yields undefined behavior. **This precondition is enforced
  5968. with a static assertion.**
  5969. @warning There is no way to enforce all preconditions at compile-time. If
  5970. the function is called with noncompliant iterators and with
  5971. assertions switched off, the behavior is undefined and will most
  5972. likely yield segmentation violation.
  5973. @tparam IteratorType iterator of container with contiguous storage
  5974. @param[in] first begin of the range to parse (included)
  5975. @param[in] last end of the range to parse (excluded)
  5976. @param[in] cb a parser callback function of type @ref parser_callback_t
  5977. which is used to control the deserialization by filtering unwanted values
  5978. (optional)
  5979. @return result of the deserialization
  5980. @throw parse_error.101 in case of an unexpected token
  5981. @throw parse_error.102 if to_unicode fails or surrogate error
  5982. @throw parse_error.103 if to_unicode fails
  5983. @complexity Linear in the length of the input. The parser is a predictive
  5984. LL(1) parser. The complexity can be higher if the parser callback function
  5985. @a cb has a super-linear complexity.
  5986. @note A UTF-8 byte order mark is silently ignored.
  5987. @liveexample{The example below demonstrates the `parse()` function reading
  5988. from an iterator range.,parse__iteratortype__parser_callback_t}
  5989. @since version 2.0.3
  5990. */
  5991. template<class IteratorType, typename std::enable_if<
  5992. std::is_base_of<
  5993. std::random_access_iterator_tag,
  5994. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  5995. static basic_json parse(IteratorType first, IteratorType last,
  5996. const parser_callback_t cb = nullptr)
  5997. {
  5998. // assertion to check that the iterator range is indeed contiguous,
  5999. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  6000. assert(std::accumulate(first, last, std::pair<bool, int>(true, 0),
  6001. [&first](std::pair<bool, int> res, decltype(*first) val)
  6002. {
  6003. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  6004. return res;
  6005. }).first);
  6006. // assertion to check that each element is 1 byte long
  6007. static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  6008. "each element in the iterator range must have the size of 1 byte");
  6009. // if iterator range is empty, create a parser with an empty string
  6010. // to generate "unexpected EOF" error message
  6011. if (std::distance(first, last) <= 0)
  6012. {
  6013. return parser("").parse();
  6014. }
  6015. return parser(first, last, cb).parse();
  6016. }
  6017. /*!
  6018. @brief deserialize from a container with contiguous storage
  6019. This function reads from a container with contiguous storage of 1-byte
  6020. values. Compatible container types include `std::vector`, `std::string`,
  6021. `std::array`, and `std::initializer_list`. User-defined containers can be
  6022. used as long as they implement random-access iterators and a contiguous
  6023. storage.
  6024. @pre The container storage is contiguous. Violating this precondition
  6025. yields undefined behavior. **This precondition is enforced with an
  6026. assertion.**
  6027. @pre Each element of the container has a size of 1 byte. Violating this
  6028. precondition yields undefined behavior. **This precondition is enforced
  6029. with a static assertion.**
  6030. @warning There is no way to enforce all preconditions at compile-time. If
  6031. the function is called with a noncompliant container and with
  6032. assertions switched off, the behavior is undefined and will most
  6033. likely yield segmentation violation.
  6034. @tparam ContiguousContainer container type with contiguous storage
  6035. @param[in] c container to read from
  6036. @param[in] cb a parser callback function of type @ref parser_callback_t
  6037. which is used to control the deserialization by filtering unwanted values
  6038. (optional)
  6039. @return result of the deserialization
  6040. @throw parse_error.101 in case of an unexpected token
  6041. @throw parse_error.102 if to_unicode fails or surrogate error
  6042. @throw parse_error.103 if to_unicode fails
  6043. @complexity Linear in the length of the input. The parser is a predictive
  6044. LL(1) parser. The complexity can be higher if the parser callback function
  6045. @a cb has a super-linear complexity.
  6046. @note A UTF-8 byte order mark is silently ignored.
  6047. @liveexample{The example below demonstrates the `parse()` function reading
  6048. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  6049. @since version 2.0.3
  6050. */
  6051. template<class ContiguousContainer, typename std::enable_if<
  6052. not std::is_pointer<ContiguousContainer>::value and
  6053. std::is_base_of<
  6054. std::random_access_iterator_tag,
  6055. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  6056. , int>::type = 0>
  6057. static basic_json parse(const ContiguousContainer& c,
  6058. const parser_callback_t cb = nullptr)
  6059. {
  6060. // delegate the call to the iterator-range parse overload
  6061. return parse(std::begin(c), std::end(c), cb);
  6062. }
  6063. /*!
  6064. @brief deserialize from stream
  6065. @deprecated This stream operator is deprecated and will be removed in a
  6066. future version of the library. Please use
  6067. @ref std::istream& operator>>(std::istream&, basic_json&)
  6068. instead; that is, replace calls like `j << i;` with `i >> j;`.
  6069. */
  6070. JSON_DEPRECATED
  6071. friend std::istream& operator<<(basic_json& j, std::istream& i)
  6072. {
  6073. j = parser(i).parse();
  6074. return i;
  6075. }
  6076. /*!
  6077. @brief deserialize from stream
  6078. Deserializes an input stream to a JSON value.
  6079. @param[in,out] i input stream to read a serialized JSON value from
  6080. @param[in,out] j JSON value to write the deserialized input to
  6081. @throw parse_error.101 in case of an unexpected token
  6082. @throw parse_error.102 if to_unicode fails or surrogate error
  6083. @throw parse_error.103 if to_unicode fails
  6084. @throw parse_error.111 if input stream is in a bad state
  6085. @complexity Linear in the length of the input. The parser is a predictive
  6086. LL(1) parser.
  6087. @note A UTF-8 byte order mark is silently ignored.
  6088. @liveexample{The example below shows how a JSON value is constructed by
  6089. reading a serialization from a stream.,operator_deserialize}
  6090. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  6091. parser callback function to filter values while parsing
  6092. @since version 1.0.0
  6093. */
  6094. friend std::istream& operator>>(std::istream& i, basic_json& j)
  6095. {
  6096. j = parser(i).parse();
  6097. return i;
  6098. }
  6099. /// @}
  6100. //////////////////////////////////////////
  6101. // binary serialization/deserialization //
  6102. //////////////////////////////////////////
  6103. /// @name binary serialization/deserialization support
  6104. /// @{
  6105. private:
  6106. /*!
  6107. @note Some code in the switch cases has been copied, because otherwise
  6108. copilers would complain about implicit fallthrough and there is no
  6109. portable attribute to mute such warnings.
  6110. */
  6111. template<typename T>
  6112. static void add_to_vector(std::vector<uint8_t>& vec, size_t bytes, const T number)
  6113. {
  6114. assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8);
  6115. switch (bytes)
  6116. {
  6117. case 8:
  6118. {
  6119. vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 070) & 0xff));
  6120. vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 060) & 0xff));
  6121. vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 050) & 0xff));
  6122. vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 040) & 0xff));
  6123. vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
  6124. vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
  6125. vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
  6126. vec.push_back(static_cast<uint8_t>(number & 0xff));
  6127. break;
  6128. }
  6129. case 4:
  6130. {
  6131. vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
  6132. vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
  6133. vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
  6134. vec.push_back(static_cast<uint8_t>(number & 0xff));
  6135. break;
  6136. }
  6137. case 2:
  6138. {
  6139. vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
  6140. vec.push_back(static_cast<uint8_t>(number & 0xff));
  6141. break;
  6142. }
  6143. case 1:
  6144. {
  6145. vec.push_back(static_cast<uint8_t>(number & 0xff));
  6146. break;
  6147. }
  6148. }
  6149. }
  6150. /*!
  6151. @brief take sufficient bytes from a vector to fill an integer variable
  6152. In the context of binary serialization formats, we need to read several
  6153. bytes from a byte vector and combine them to multi-byte integral data
  6154. types.
  6155. @param[in] vec byte vector to read from
  6156. @param[in] current_index the position in the vector after which to read
  6157. @return the next sizeof(T) bytes from @a vec, in reverse order as T
  6158. @tparam T the integral return type
  6159. @throw parse_error.110 if there are less than sizeof(T)+1 bytes in the
  6160. vector @a vec to read
  6161. In the for loop, the bytes from the vector are copied in reverse order into
  6162. the return value. In the figures below, let sizeof(T)=4 and `i` be the loop
  6163. variable.
  6164. Precondition:
  6165. vec: | | | a | b | c | d | T: | | | | |
  6166. ^ ^ ^ ^
  6167. current_index i ptr sizeof(T)
  6168. Postcondition:
  6169. vec: | | | a | b | c | d | T: | d | c | b | a |
  6170. ^ ^ ^
  6171. | i ptr
  6172. current_index
  6173. @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>.
  6174. */
  6175. template<typename T>
  6176. static T get_from_vector(const std::vector<uint8_t>& vec, const size_t current_index)
  6177. {
  6178. // check if we can read sizeof(T) bytes starting the next index
  6179. check_length(vec.size(), sizeof(T), current_index + 1);
  6180. T result;
  6181. auto* ptr = reinterpret_cast<uint8_t*>(&result);
  6182. for (size_t i = 0; i < sizeof(T); ++i)
  6183. {
  6184. *ptr++ = vec[current_index + sizeof(T) - i];
  6185. }
  6186. return result;
  6187. }
  6188. /*!
  6189. @brief create a MessagePack serialization of a given JSON value
  6190. This is a straightforward implementation of the MessagePack specification.
  6191. @param[in] j JSON value to serialize
  6192. @param[in,out] v byte vector to write the serialization to
  6193. @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  6194. */
  6195. static void to_msgpack_internal(const basic_json& j, std::vector<uint8_t>& v)
  6196. {
  6197. switch (j.type())
  6198. {
  6199. case value_t::null:
  6200. {
  6201. // nil
  6202. v.push_back(0xc0);
  6203. break;
  6204. }
  6205. case value_t::boolean:
  6206. {
  6207. // true and false
  6208. v.push_back(j.m_value.boolean ? 0xc3 : 0xc2);
  6209. break;
  6210. }
  6211. case value_t::number_integer:
  6212. {
  6213. if (j.m_value.number_integer >= 0)
  6214. {
  6215. // MessagePack does not differentiate between positive
  6216. // signed integers and unsigned integers. Therefore, we
  6217. // used the code from the value_t::number_unsigned case
  6218. // here.
  6219. if (j.m_value.number_unsigned < 128)
  6220. {
  6221. // positive fixnum
  6222. add_to_vector(v, 1, j.m_value.number_unsigned);
  6223. }
  6224. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6225. {
  6226. // uint 8
  6227. v.push_back(0xcc);
  6228. add_to_vector(v, 1, j.m_value.number_unsigned);
  6229. }
  6230. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  6231. {
  6232. // uint 16
  6233. v.push_back(0xcd);
  6234. add_to_vector(v, 2, j.m_value.number_unsigned);
  6235. }
  6236. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  6237. {
  6238. // uint 32
  6239. v.push_back(0xce);
  6240. add_to_vector(v, 4, j.m_value.number_unsigned);
  6241. }
  6242. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  6243. {
  6244. // uint 64
  6245. v.push_back(0xcf);
  6246. add_to_vector(v, 8, j.m_value.number_unsigned);
  6247. }
  6248. }
  6249. else
  6250. {
  6251. if (j.m_value.number_integer >= -32)
  6252. {
  6253. // negative fixnum
  6254. add_to_vector(v, 1, j.m_value.number_integer);
  6255. }
  6256. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  6257. {
  6258. // int 8
  6259. v.push_back(0xd0);
  6260. add_to_vector(v, 1, j.m_value.number_integer);
  6261. }
  6262. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  6263. {
  6264. // int 16
  6265. v.push_back(0xd1);
  6266. add_to_vector(v, 2, j.m_value.number_integer);
  6267. }
  6268. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  6269. {
  6270. // int 32
  6271. v.push_back(0xd2);
  6272. add_to_vector(v, 4, j.m_value.number_integer);
  6273. }
  6274. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  6275. {
  6276. // int 64
  6277. v.push_back(0xd3);
  6278. add_to_vector(v, 8, j.m_value.number_integer);
  6279. }
  6280. }
  6281. break;
  6282. }
  6283. case value_t::number_unsigned:
  6284. {
  6285. if (j.m_value.number_unsigned < 128)
  6286. {
  6287. // positive fixnum
  6288. add_to_vector(v, 1, j.m_value.number_unsigned);
  6289. }
  6290. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6291. {
  6292. // uint 8
  6293. v.push_back(0xcc);
  6294. add_to_vector(v, 1, j.m_value.number_unsigned);
  6295. }
  6296. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  6297. {
  6298. // uint 16
  6299. v.push_back(0xcd);
  6300. add_to_vector(v, 2, j.m_value.number_unsigned);
  6301. }
  6302. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  6303. {
  6304. // uint 32
  6305. v.push_back(0xce);
  6306. add_to_vector(v, 4, j.m_value.number_unsigned);
  6307. }
  6308. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  6309. {
  6310. // uint 64
  6311. v.push_back(0xcf);
  6312. add_to_vector(v, 8, j.m_value.number_unsigned);
  6313. }
  6314. break;
  6315. }
  6316. case value_t::number_float:
  6317. {
  6318. // float 64
  6319. v.push_back(0xcb);
  6320. const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
  6321. for (size_t i = 0; i < 8; ++i)
  6322. {
  6323. v.push_back(helper[7 - i]);
  6324. }
  6325. break;
  6326. }
  6327. case value_t::string:
  6328. {
  6329. const auto N = j.m_value.string->size();
  6330. if (N <= 31)
  6331. {
  6332. // fixstr
  6333. v.push_back(static_cast<uint8_t>(0xa0 | N));
  6334. }
  6335. else if (N <= 255)
  6336. {
  6337. // str 8
  6338. v.push_back(0xd9);
  6339. add_to_vector(v, 1, N);
  6340. }
  6341. else if (N <= 65535)
  6342. {
  6343. // str 16
  6344. v.push_back(0xda);
  6345. add_to_vector(v, 2, N);
  6346. }
  6347. else if (N <= 4294967295)
  6348. {
  6349. // str 32
  6350. v.push_back(0xdb);
  6351. add_to_vector(v, 4, N);
  6352. }
  6353. // append string
  6354. std::copy(j.m_value.string->begin(), j.m_value.string->end(),
  6355. std::back_inserter(v));
  6356. break;
  6357. }
  6358. case value_t::array:
  6359. {
  6360. const auto N = j.m_value.array->size();
  6361. if (N <= 15)
  6362. {
  6363. // fixarray
  6364. v.push_back(static_cast<uint8_t>(0x90 | N));
  6365. }
  6366. else if (N <= 0xffff)
  6367. {
  6368. // array 16
  6369. v.push_back(0xdc);
  6370. add_to_vector(v, 2, N);
  6371. }
  6372. else if (N <= 0xffffffff)
  6373. {
  6374. // array 32
  6375. v.push_back(0xdd);
  6376. add_to_vector(v, 4, N);
  6377. }
  6378. // append each element
  6379. for (const auto& el : *j.m_value.array)
  6380. {
  6381. to_msgpack_internal(el, v);
  6382. }
  6383. break;
  6384. }
  6385. case value_t::object:
  6386. {
  6387. const auto N = j.m_value.object->size();
  6388. if (N <= 15)
  6389. {
  6390. // fixmap
  6391. v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf)));
  6392. }
  6393. else if (N <= 65535)
  6394. {
  6395. // map 16
  6396. v.push_back(0xde);
  6397. add_to_vector(v, 2, N);
  6398. }
  6399. else if (N <= 4294967295)
  6400. {
  6401. // map 32
  6402. v.push_back(0xdf);
  6403. add_to_vector(v, 4, N);
  6404. }
  6405. // append each element
  6406. for (const auto& el : *j.m_value.object)
  6407. {
  6408. to_msgpack_internal(el.first, v);
  6409. to_msgpack_internal(el.second, v);
  6410. }
  6411. break;
  6412. }
  6413. default:
  6414. {
  6415. break;
  6416. }
  6417. }
  6418. }
  6419. /*!
  6420. @brief create a CBOR serialization of a given JSON value
  6421. This is a straightforward implementation of the CBOR specification.
  6422. @param[in] j JSON value to serialize
  6423. @param[in,out] v byte vector to write the serialization to
  6424. @sa https://tools.ietf.org/html/rfc7049
  6425. */
  6426. static void to_cbor_internal(const basic_json& j, std::vector<uint8_t>& v)
  6427. {
  6428. switch (j.type())
  6429. {
  6430. case value_t::null:
  6431. {
  6432. v.push_back(0xf6);
  6433. break;
  6434. }
  6435. case value_t::boolean:
  6436. {
  6437. v.push_back(j.m_value.boolean ? 0xf5 : 0xf4);
  6438. break;
  6439. }
  6440. case value_t::number_integer:
  6441. {
  6442. if (j.m_value.number_integer >= 0)
  6443. {
  6444. // CBOR does not differentiate between positive signed
  6445. // integers and unsigned integers. Therefore, we used the
  6446. // code from the value_t::number_unsigned case here.
  6447. if (j.m_value.number_integer <= 0x17)
  6448. {
  6449. add_to_vector(v, 1, j.m_value.number_integer);
  6450. }
  6451. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  6452. {
  6453. v.push_back(0x18);
  6454. // one-byte uint8_t
  6455. add_to_vector(v, 1, j.m_value.number_integer);
  6456. }
  6457. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  6458. {
  6459. v.push_back(0x19);
  6460. // two-byte uint16_t
  6461. add_to_vector(v, 2, j.m_value.number_integer);
  6462. }
  6463. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  6464. {
  6465. v.push_back(0x1a);
  6466. // four-byte uint32_t
  6467. add_to_vector(v, 4, j.m_value.number_integer);
  6468. }
  6469. else
  6470. {
  6471. v.push_back(0x1b);
  6472. // eight-byte uint64_t
  6473. add_to_vector(v, 8, j.m_value.number_integer);
  6474. }
  6475. }
  6476. else
  6477. {
  6478. // The conversions below encode the sign in the first
  6479. // byte, and the value is converted to a positive number.
  6480. const auto positive_number = -1 - j.m_value.number_integer;
  6481. if (j.m_value.number_integer >= -24)
  6482. {
  6483. v.push_back(static_cast<uint8_t>(0x20 + positive_number));
  6484. }
  6485. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  6486. {
  6487. // int 8
  6488. v.push_back(0x38);
  6489. add_to_vector(v, 1, positive_number);
  6490. }
  6491. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  6492. {
  6493. // int 16
  6494. v.push_back(0x39);
  6495. add_to_vector(v, 2, positive_number);
  6496. }
  6497. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  6498. {
  6499. // int 32
  6500. v.push_back(0x3a);
  6501. add_to_vector(v, 4, positive_number);
  6502. }
  6503. else
  6504. {
  6505. // int 64
  6506. v.push_back(0x3b);
  6507. add_to_vector(v, 8, positive_number);
  6508. }
  6509. }
  6510. break;
  6511. }
  6512. case value_t::number_unsigned:
  6513. {
  6514. if (j.m_value.number_unsigned <= 0x17)
  6515. {
  6516. v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned));
  6517. }
  6518. else if (j.m_value.number_unsigned <= 0xff)
  6519. {
  6520. v.push_back(0x18);
  6521. // one-byte uint8_t
  6522. add_to_vector(v, 1, j.m_value.number_unsigned);
  6523. }
  6524. else if (j.m_value.number_unsigned <= 0xffff)
  6525. {
  6526. v.push_back(0x19);
  6527. // two-byte uint16_t
  6528. add_to_vector(v, 2, j.m_value.number_unsigned);
  6529. }
  6530. else if (j.m_value.number_unsigned <= 0xffffffff)
  6531. {
  6532. v.push_back(0x1a);
  6533. // four-byte uint32_t
  6534. add_to_vector(v, 4, j.m_value.number_unsigned);
  6535. }
  6536. else if (j.m_value.number_unsigned <= 0xffffffffffffffff)
  6537. {
  6538. v.push_back(0x1b);
  6539. // eight-byte uint64_t
  6540. add_to_vector(v, 8, j.m_value.number_unsigned);
  6541. }
  6542. break;
  6543. }
  6544. case value_t::number_float:
  6545. {
  6546. // Double-Precision Float
  6547. v.push_back(0xfb);
  6548. const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
  6549. for (size_t i = 0; i < 8; ++i)
  6550. {
  6551. v.push_back(helper[7 - i]);
  6552. }
  6553. break;
  6554. }
  6555. case value_t::string:
  6556. {
  6557. const auto N = j.m_value.string->size();
  6558. if (N <= 0x17)
  6559. {
  6560. v.push_back(static_cast<uint8_t>(0x60 + N)); // 1 byte for string + size
  6561. }
  6562. else if (N <= 0xff)
  6563. {
  6564. v.push_back(0x78); // one-byte uint8_t for N
  6565. add_to_vector(v, 1, N);
  6566. }
  6567. else if (N <= 0xffff)
  6568. {
  6569. v.push_back(0x79); // two-byte uint16_t for N
  6570. add_to_vector(v, 2, N);
  6571. }
  6572. else if (N <= 0xffffffff)
  6573. {
  6574. v.push_back(0x7a); // four-byte uint32_t for N
  6575. add_to_vector(v, 4, N);
  6576. }
  6577. // LCOV_EXCL_START
  6578. else if (N <= 0xffffffffffffffff)
  6579. {
  6580. v.push_back(0x7b); // eight-byte uint64_t for N
  6581. add_to_vector(v, 8, N);
  6582. }
  6583. // LCOV_EXCL_STOP
  6584. // append string
  6585. std::copy(j.m_value.string->begin(), j.m_value.string->end(),
  6586. std::back_inserter(v));
  6587. break;
  6588. }
  6589. case value_t::array:
  6590. {
  6591. const auto N = j.m_value.array->size();
  6592. if (N <= 0x17)
  6593. {
  6594. v.push_back(static_cast<uint8_t>(0x80 + N)); // 1 byte for array + size
  6595. }
  6596. else if (N <= 0xff)
  6597. {
  6598. v.push_back(0x98); // one-byte uint8_t for N
  6599. add_to_vector(v, 1, N);
  6600. }
  6601. else if (N <= 0xffff)
  6602. {
  6603. v.push_back(0x99); // two-byte uint16_t for N
  6604. add_to_vector(v, 2, N);
  6605. }
  6606. else if (N <= 0xffffffff)
  6607. {
  6608. v.push_back(0x9a); // four-byte uint32_t for N
  6609. add_to_vector(v, 4, N);
  6610. }
  6611. // LCOV_EXCL_START
  6612. else if (N <= 0xffffffffffffffff)
  6613. {
  6614. v.push_back(0x9b); // eight-byte uint64_t for N
  6615. add_to_vector(v, 8, N);
  6616. }
  6617. // LCOV_EXCL_STOP
  6618. // append each element
  6619. for (const auto& el : *j.m_value.array)
  6620. {
  6621. to_cbor_internal(el, v);
  6622. }
  6623. break;
  6624. }
  6625. case value_t::object:
  6626. {
  6627. const auto N = j.m_value.object->size();
  6628. if (N <= 0x17)
  6629. {
  6630. v.push_back(static_cast<uint8_t>(0xa0 + N)); // 1 byte for object + size
  6631. }
  6632. else if (N <= 0xff)
  6633. {
  6634. v.push_back(0xb8);
  6635. add_to_vector(v, 1, N); // one-byte uint8_t for N
  6636. }
  6637. else if (N <= 0xffff)
  6638. {
  6639. v.push_back(0xb9);
  6640. add_to_vector(v, 2, N); // two-byte uint16_t for N
  6641. }
  6642. else if (N <= 0xffffffff)
  6643. {
  6644. v.push_back(0xba);
  6645. add_to_vector(v, 4, N); // four-byte uint32_t for N
  6646. }
  6647. // LCOV_EXCL_START
  6648. else if (N <= 0xffffffffffffffff)
  6649. {
  6650. v.push_back(0xbb);
  6651. add_to_vector(v, 8, N); // eight-byte uint64_t for N
  6652. }
  6653. // LCOV_EXCL_STOP
  6654. // append each element
  6655. for (const auto& el : *j.m_value.object)
  6656. {
  6657. to_cbor_internal(el.first, v);
  6658. to_cbor_internal(el.second, v);
  6659. }
  6660. break;
  6661. }
  6662. default:
  6663. {
  6664. break;
  6665. }
  6666. }
  6667. }
  6668. /*
  6669. @brief checks if given lengths do not exceed the size of a given vector
  6670. To secure the access to the byte vector during CBOR/MessagePack
  6671. deserialization, bytes are copied from the vector into buffers. This
  6672. function checks if the number of bytes to copy (@a len) does not exceed
  6673. the size @s size of the vector. Additionally, an @a offset is given from
  6674. where to start reading the bytes.
  6675. This function checks whether reading the bytes is safe; that is, offset is
  6676. a valid index in the vector, offset+len
  6677. @param[in] size size of the byte vector
  6678. @param[in] len number of bytes to read
  6679. @param[in] offset offset where to start reading
  6680. vec: x x x x x X X X X X
  6681. ^ ^ ^
  6682. 0 offset len
  6683. @throws out_of_range if `len > v.size()`
  6684. */
  6685. static void check_length(const size_t size, const size_t len, const size_t offset)
  6686. {
  6687. // simple case: requested length is greater than the vector's length
  6688. if (len > size or offset > size)
  6689. {
  6690. JSON_THROW(parse_error::create(110, offset + 1, "cannot read " + std::to_string(len) + " bytes from vector"));
  6691. }
  6692. // second case: adding offset would result in overflow
  6693. if ((size > ((std::numeric_limits<size_t>::max)() - offset)))
  6694. {
  6695. JSON_THROW(parse_error::create(110, offset + 1, "cannot read " + std::to_string(len) + " bytes from vector"));
  6696. }
  6697. // last case: reading past the end of the vector
  6698. if (len + offset > size)
  6699. {
  6700. JSON_THROW(parse_error::create(110, offset + 1, "cannot read " + std::to_string(len) + " bytes from vector"));
  6701. }
  6702. }
  6703. /*!
  6704. @brief check if the next byte belongs to a string
  6705. While parsing a map, the keys must be strings. This function checks if the
  6706. current byte is one of the start bytes for a string in MessagePack:
  6707. - 0xa0 - 0xbf: fixstr
  6708. - 0xd9: str 8
  6709. - 0xda: str 16
  6710. - 0xdb: str 32
  6711. @param[in] v MessagePack serialization
  6712. @param[in] idx byte index in @a v to check for a string
  6713. @throw parse_error.113 if `v[idx]` does not belong to a string
  6714. */
  6715. static void msgpack_expect_string(const std::vector<uint8_t>& v, size_t idx)
  6716. {
  6717. check_length(v.size(), 1, idx);
  6718. const auto byte = v[idx];
  6719. if ((byte >= 0xa0 and byte <= 0xbf) or (byte >= 0xd9 and byte <= 0xdb))
  6720. {
  6721. return;
  6722. }
  6723. std::stringstream ss;
  6724. ss << std::hex << static_cast<int>(v[idx]);
  6725. JSON_THROW(parse_error::create(113, idx + 1, "expected a MessagePack string; last byte: 0x" + ss.str()));
  6726. }
  6727. /*!
  6728. @brief check if the next byte belongs to a string
  6729. While parsing a map, the keys must be strings. This function checks if the
  6730. current byte is one of the start bytes for a string in CBOR:
  6731. - 0x60 - 0x77: fixed length
  6732. - 0x78 - 0x7b: variable length
  6733. - 0x7f: indefinity length
  6734. @param[in] v CBOR serialization
  6735. @param[in] idx byte index in @a v to check for a string
  6736. @throw parse_error.113 if `v[idx]` does not belong to a string
  6737. */
  6738. static void cbor_expect_string(const std::vector<uint8_t>& v, size_t idx)
  6739. {
  6740. check_length(v.size(), 1, idx);
  6741. const auto byte = v[idx];
  6742. if ((byte >= 0x60 and byte <= 0x7b) or byte == 0x7f)
  6743. {
  6744. return;
  6745. }
  6746. std::stringstream ss;
  6747. ss << std::hex << static_cast<int>(v[idx]);
  6748. JSON_THROW(parse_error::create(113, idx + 1, "expected a CBOR string; last byte: 0x" + ss.str()));
  6749. }
  6750. /*!
  6751. @brief create a JSON value from a given MessagePack vector
  6752. @param[in] v MessagePack serialization
  6753. @param[in] idx byte index to start reading from @a v
  6754. @return deserialized JSON value
  6755. @throw parse_error.110 if the given vector ends prematurely
  6756. @throw parse_error.112 if unsupported features from MessagePack were
  6757. used in the given vector @a v or if the input is not valid MessagePack
  6758. @throw parse_error.113 if a string was expected as map key, but not found
  6759. @sa https://github.com/msgpack/msgpack/blob/master/spec.md
  6760. */
  6761. static basic_json from_msgpack_internal(const std::vector<uint8_t>& v, size_t& idx)
  6762. {
  6763. // store and increment index
  6764. const size_t current_idx = idx++;
  6765. // make sure reading 1 byte is safe
  6766. check_length(v.size(), 1, current_idx);
  6767. if (v[current_idx] <= 0xbf)
  6768. {
  6769. if (v[current_idx] <= 0x7f) // positive fixint
  6770. {
  6771. return v[current_idx];
  6772. }
  6773. if (v[current_idx] <= 0x8f) // fixmap
  6774. {
  6775. basic_json result = value_t::object;
  6776. const size_t len = v[current_idx] & 0x0f;
  6777. for (size_t i = 0; i < len; ++i)
  6778. {
  6779. msgpack_expect_string(v, idx);
  6780. std::string key = from_msgpack_internal(v, idx);
  6781. result[key] = from_msgpack_internal(v, idx);
  6782. }
  6783. return result;
  6784. }
  6785. else if (v[current_idx] <= 0x9f) // fixarray
  6786. {
  6787. basic_json result = value_t::array;
  6788. const size_t len = v[current_idx] & 0x0f;
  6789. for (size_t i = 0; i < len; ++i)
  6790. {
  6791. result.push_back(from_msgpack_internal(v, idx));
  6792. }
  6793. return result;
  6794. }
  6795. else // fixstr
  6796. {
  6797. const size_t len = v[current_idx] & 0x1f;
  6798. const size_t offset = current_idx + 1;
  6799. idx += len; // skip content bytes
  6800. check_length(v.size(), len, offset);
  6801. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  6802. }
  6803. }
  6804. else if (v[current_idx] >= 0xe0) // negative fixint
  6805. {
  6806. return static_cast<int8_t>(v[current_idx]);
  6807. }
  6808. else
  6809. {
  6810. switch (v[current_idx])
  6811. {
  6812. case 0xc0: // nil
  6813. {
  6814. return value_t::null;
  6815. }
  6816. case 0xc2: // false
  6817. {
  6818. return false;
  6819. }
  6820. case 0xc3: // true
  6821. {
  6822. return true;
  6823. }
  6824. case 0xca: // float 32
  6825. {
  6826. // copy bytes in reverse order into the double variable
  6827. float res;
  6828. check_length(v.size(), sizeof(float), current_idx + 1);
  6829. for (size_t byte = 0; byte < sizeof(float); ++byte)
  6830. {
  6831. reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v[current_idx + 1 + byte];
  6832. }
  6833. idx += sizeof(float); // skip content bytes
  6834. return res;
  6835. }
  6836. case 0xcb: // float 64
  6837. {
  6838. // copy bytes in reverse order into the double variable
  6839. double res;
  6840. check_length(v.size(), sizeof(double), current_idx + 1);
  6841. for (size_t byte = 0; byte < sizeof(double); ++byte)
  6842. {
  6843. reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v[current_idx + 1 + byte];
  6844. }
  6845. idx += sizeof(double); // skip content bytes
  6846. return res;
  6847. }
  6848. case 0xcc: // uint 8
  6849. {
  6850. idx += 1; // skip content byte
  6851. return get_from_vector<uint8_t>(v, current_idx);
  6852. }
  6853. case 0xcd: // uint 16
  6854. {
  6855. idx += 2; // skip 2 content bytes
  6856. return get_from_vector<uint16_t>(v, current_idx);
  6857. }
  6858. case 0xce: // uint 32
  6859. {
  6860. idx += 4; // skip 4 content bytes
  6861. return get_from_vector<uint32_t>(v, current_idx);
  6862. }
  6863. case 0xcf: // uint 64
  6864. {
  6865. idx += 8; // skip 8 content bytes
  6866. return get_from_vector<uint64_t>(v, current_idx);
  6867. }
  6868. case 0xd0: // int 8
  6869. {
  6870. idx += 1; // skip content byte
  6871. return get_from_vector<int8_t>(v, current_idx);
  6872. }
  6873. case 0xd1: // int 16
  6874. {
  6875. idx += 2; // skip 2 content bytes
  6876. return get_from_vector<int16_t>(v, current_idx);
  6877. }
  6878. case 0xd2: // int 32
  6879. {
  6880. idx += 4; // skip 4 content bytes
  6881. return get_from_vector<int32_t>(v, current_idx);
  6882. }
  6883. case 0xd3: // int 64
  6884. {
  6885. idx += 8; // skip 8 content bytes
  6886. return get_from_vector<int64_t>(v, current_idx);
  6887. }
  6888. case 0xd9: // str 8
  6889. {
  6890. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  6891. const size_t offset = current_idx + 2;
  6892. idx += len + 1; // skip size byte + content bytes
  6893. check_length(v.size(), len, offset);
  6894. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  6895. }
  6896. case 0xda: // str 16
  6897. {
  6898. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  6899. const size_t offset = current_idx + 3;
  6900. idx += len + 2; // skip 2 size bytes + content bytes
  6901. check_length(v.size(), len, offset);
  6902. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  6903. }
  6904. case 0xdb: // str 32
  6905. {
  6906. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  6907. const size_t offset = current_idx + 5;
  6908. idx += len + 4; // skip 4 size bytes + content bytes
  6909. check_length(v.size(), len, offset);
  6910. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  6911. }
  6912. case 0xdc: // array 16
  6913. {
  6914. basic_json result = value_t::array;
  6915. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  6916. idx += 2; // skip 2 size bytes
  6917. for (size_t i = 0; i < len; ++i)
  6918. {
  6919. result.push_back(from_msgpack_internal(v, idx));
  6920. }
  6921. return result;
  6922. }
  6923. case 0xdd: // array 32
  6924. {
  6925. basic_json result = value_t::array;
  6926. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  6927. idx += 4; // skip 4 size bytes
  6928. for (size_t i = 0; i < len; ++i)
  6929. {
  6930. result.push_back(from_msgpack_internal(v, idx));
  6931. }
  6932. return result;
  6933. }
  6934. case 0xde: // map 16
  6935. {
  6936. basic_json result = value_t::object;
  6937. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  6938. idx += 2; // skip 2 size bytes
  6939. for (size_t i = 0; i < len; ++i)
  6940. {
  6941. msgpack_expect_string(v, idx);
  6942. std::string key = from_msgpack_internal(v, idx);
  6943. result[key] = from_msgpack_internal(v, idx);
  6944. }
  6945. return result;
  6946. }
  6947. case 0xdf: // map 32
  6948. {
  6949. basic_json result = value_t::object;
  6950. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  6951. idx += 4; // skip 4 size bytes
  6952. for (size_t i = 0; i < len; ++i)
  6953. {
  6954. msgpack_expect_string(v, idx);
  6955. std::string key = from_msgpack_internal(v, idx);
  6956. result[key] = from_msgpack_internal(v, idx);
  6957. }
  6958. return result;
  6959. }
  6960. default:
  6961. {
  6962. std::stringstream ss;
  6963. ss << std::hex << static_cast<int>(v[current_idx]);
  6964. JSON_THROW(parse_error::create(112, current_idx + 1, "error reading MessagePack; last byte: 0x" + ss.str()));
  6965. }
  6966. }
  6967. }
  6968. }
  6969. /*!
  6970. @brief create a JSON value from a given CBOR vector
  6971. @param[in] v CBOR serialization
  6972. @param[in] idx byte index to start reading from @a v
  6973. @return deserialized JSON value
  6974. @throw parse_error.110 if the given vector ends prematurely
  6975. @throw parse_error.112 if unsupported features from CBOR were
  6976. used in the given vector @a v or if the input is not valid CBOR
  6977. @throw parse_error.113 if a string was expected as map key, but not found
  6978. @sa https://tools.ietf.org/html/rfc7049
  6979. */
  6980. static basic_json from_cbor_internal(const std::vector<uint8_t>& v, size_t& idx)
  6981. {
  6982. // store and increment index
  6983. const size_t current_idx = idx++;
  6984. // make sure reading 1 byte is safe
  6985. check_length(v.size(), 1, current_idx);
  6986. switch (v[current_idx])
  6987. {
  6988. // Integer 0x00..0x17 (0..23)
  6989. case 0x00:
  6990. case 0x01:
  6991. case 0x02:
  6992. case 0x03:
  6993. case 0x04:
  6994. case 0x05:
  6995. case 0x06:
  6996. case 0x07:
  6997. case 0x08:
  6998. case 0x09:
  6999. case 0x0a:
  7000. case 0x0b:
  7001. case 0x0c:
  7002. case 0x0d:
  7003. case 0x0e:
  7004. case 0x0f:
  7005. case 0x10:
  7006. case 0x11:
  7007. case 0x12:
  7008. case 0x13:
  7009. case 0x14:
  7010. case 0x15:
  7011. case 0x16:
  7012. case 0x17:
  7013. {
  7014. return v[current_idx];
  7015. }
  7016. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  7017. {
  7018. idx += 1; // skip content byte
  7019. return get_from_vector<uint8_t>(v, current_idx);
  7020. }
  7021. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  7022. {
  7023. idx += 2; // skip 2 content bytes
  7024. return get_from_vector<uint16_t>(v, current_idx);
  7025. }
  7026. case 0x1a: // Unsigned integer (four-byte uint32_t follows)
  7027. {
  7028. idx += 4; // skip 4 content bytes
  7029. return get_from_vector<uint32_t>(v, current_idx);
  7030. }
  7031. case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
  7032. {
  7033. idx += 8; // skip 8 content bytes
  7034. return get_from_vector<uint64_t>(v, current_idx);
  7035. }
  7036. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  7037. case 0x20:
  7038. case 0x21:
  7039. case 0x22:
  7040. case 0x23:
  7041. case 0x24:
  7042. case 0x25:
  7043. case 0x26:
  7044. case 0x27:
  7045. case 0x28:
  7046. case 0x29:
  7047. case 0x2a:
  7048. case 0x2b:
  7049. case 0x2c:
  7050. case 0x2d:
  7051. case 0x2e:
  7052. case 0x2f:
  7053. case 0x30:
  7054. case 0x31:
  7055. case 0x32:
  7056. case 0x33:
  7057. case 0x34:
  7058. case 0x35:
  7059. case 0x36:
  7060. case 0x37:
  7061. {
  7062. return static_cast<int8_t>(0x20 - 1 - v[current_idx]);
  7063. }
  7064. case 0x38: // Negative integer (one-byte uint8_t follows)
  7065. {
  7066. idx += 1; // skip content byte
  7067. // must be uint8_t !
  7068. return static_cast<number_integer_t>(-1) - get_from_vector<uint8_t>(v, current_idx);
  7069. }
  7070. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  7071. {
  7072. idx += 2; // skip 2 content bytes
  7073. return static_cast<number_integer_t>(-1) - get_from_vector<uint16_t>(v, current_idx);
  7074. }
  7075. case 0x3a: // Negative integer -1-n (four-byte uint32_t follows)
  7076. {
  7077. idx += 4; // skip 4 content bytes
  7078. return static_cast<number_integer_t>(-1) - get_from_vector<uint32_t>(v, current_idx);
  7079. }
  7080. case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows)
  7081. {
  7082. idx += 8; // skip 8 content bytes
  7083. return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_from_vector<uint64_t>(v, current_idx));
  7084. }
  7085. // UTF-8 string (0x00..0x17 bytes follow)
  7086. case 0x60:
  7087. case 0x61:
  7088. case 0x62:
  7089. case 0x63:
  7090. case 0x64:
  7091. case 0x65:
  7092. case 0x66:
  7093. case 0x67:
  7094. case 0x68:
  7095. case 0x69:
  7096. case 0x6a:
  7097. case 0x6b:
  7098. case 0x6c:
  7099. case 0x6d:
  7100. case 0x6e:
  7101. case 0x6f:
  7102. case 0x70:
  7103. case 0x71:
  7104. case 0x72:
  7105. case 0x73:
  7106. case 0x74:
  7107. case 0x75:
  7108. case 0x76:
  7109. case 0x77:
  7110. {
  7111. const auto len = static_cast<size_t>(v[current_idx] - 0x60);
  7112. const size_t offset = current_idx + 1;
  7113. idx += len; // skip content bytes
  7114. check_length(v.size(), len, offset);
  7115. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  7116. }
  7117. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  7118. {
  7119. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  7120. const size_t offset = current_idx + 2;
  7121. idx += len + 1; // skip size byte + content bytes
  7122. check_length(v.size(), len, offset);
  7123. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  7124. }
  7125. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  7126. {
  7127. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  7128. const size_t offset = current_idx + 3;
  7129. idx += len + 2; // skip 2 size bytes + content bytes
  7130. check_length(v.size(), len, offset);
  7131. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  7132. }
  7133. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  7134. {
  7135. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  7136. const size_t offset = current_idx + 5;
  7137. idx += len + 4; // skip 4 size bytes + content bytes
  7138. check_length(v.size(), len, offset);
  7139. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  7140. }
  7141. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  7142. {
  7143. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  7144. const size_t offset = current_idx + 9;
  7145. idx += len + 8; // skip 8 size bytes + content bytes
  7146. check_length(v.size(), len, offset);
  7147. return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
  7148. }
  7149. case 0x7f: // UTF-8 string (indefinite length)
  7150. {
  7151. std::string result;
  7152. while (static_cast<void>(check_length(v.size(), 1, idx)), v[idx] != 0xff)
  7153. {
  7154. string_t s = from_cbor_internal(v, idx);
  7155. result += s;
  7156. }
  7157. // skip break byte (0xFF)
  7158. idx += 1;
  7159. return result;
  7160. }
  7161. // array (0x00..0x17 data items follow)
  7162. case 0x80:
  7163. case 0x81:
  7164. case 0x82:
  7165. case 0x83:
  7166. case 0x84:
  7167. case 0x85:
  7168. case 0x86:
  7169. case 0x87:
  7170. case 0x88:
  7171. case 0x89:
  7172. case 0x8a:
  7173. case 0x8b:
  7174. case 0x8c:
  7175. case 0x8d:
  7176. case 0x8e:
  7177. case 0x8f:
  7178. case 0x90:
  7179. case 0x91:
  7180. case 0x92:
  7181. case 0x93:
  7182. case 0x94:
  7183. case 0x95:
  7184. case 0x96:
  7185. case 0x97:
  7186. {
  7187. basic_json result = value_t::array;
  7188. const auto len = static_cast<size_t>(v[current_idx] - 0x80);
  7189. for (size_t i = 0; i < len; ++i)
  7190. {
  7191. result.push_back(from_cbor_internal(v, idx));
  7192. }
  7193. return result;
  7194. }
  7195. case 0x98: // array (one-byte uint8_t for n follows)
  7196. {
  7197. basic_json result = value_t::array;
  7198. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  7199. idx += 1; // skip 1 size byte
  7200. for (size_t i = 0; i < len; ++i)
  7201. {
  7202. result.push_back(from_cbor_internal(v, idx));
  7203. }
  7204. return result;
  7205. }
  7206. case 0x99: // array (two-byte uint16_t for n follow)
  7207. {
  7208. basic_json result = value_t::array;
  7209. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  7210. idx += 2; // skip 4 size bytes
  7211. for (size_t i = 0; i < len; ++i)
  7212. {
  7213. result.push_back(from_cbor_internal(v, idx));
  7214. }
  7215. return result;
  7216. }
  7217. case 0x9a: // array (four-byte uint32_t for n follow)
  7218. {
  7219. basic_json result = value_t::array;
  7220. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  7221. idx += 4; // skip 4 size bytes
  7222. for (size_t i = 0; i < len; ++i)
  7223. {
  7224. result.push_back(from_cbor_internal(v, idx));
  7225. }
  7226. return result;
  7227. }
  7228. case 0x9b: // array (eight-byte uint64_t for n follow)
  7229. {
  7230. basic_json result = value_t::array;
  7231. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  7232. idx += 8; // skip 8 size bytes
  7233. for (size_t i = 0; i < len; ++i)
  7234. {
  7235. result.push_back(from_cbor_internal(v, idx));
  7236. }
  7237. return result;
  7238. }
  7239. case 0x9f: // array (indefinite length)
  7240. {
  7241. basic_json result = value_t::array;
  7242. while (static_cast<void>(check_length(v.size(), 1, idx)), v[idx] != 0xff)
  7243. {
  7244. result.push_back(from_cbor_internal(v, idx));
  7245. }
  7246. // skip break byte (0xFF)
  7247. idx += 1;
  7248. return result;
  7249. }
  7250. // map (0x00..0x17 pairs of data items follow)
  7251. case 0xa0:
  7252. case 0xa1:
  7253. case 0xa2:
  7254. case 0xa3:
  7255. case 0xa4:
  7256. case 0xa5:
  7257. case 0xa6:
  7258. case 0xa7:
  7259. case 0xa8:
  7260. case 0xa9:
  7261. case 0xaa:
  7262. case 0xab:
  7263. case 0xac:
  7264. case 0xad:
  7265. case 0xae:
  7266. case 0xaf:
  7267. case 0xb0:
  7268. case 0xb1:
  7269. case 0xb2:
  7270. case 0xb3:
  7271. case 0xb4:
  7272. case 0xb5:
  7273. case 0xb6:
  7274. case 0xb7:
  7275. {
  7276. basic_json result = value_t::object;
  7277. const auto len = static_cast<size_t>(v[current_idx] - 0xa0);
  7278. for (size_t i = 0; i < len; ++i)
  7279. {
  7280. cbor_expect_string(v, idx);
  7281. std::string key = from_cbor_internal(v, idx);
  7282. result[key] = from_cbor_internal(v, idx);
  7283. }
  7284. return result;
  7285. }
  7286. case 0xb8: // map (one-byte uint8_t for n follows)
  7287. {
  7288. basic_json result = value_t::object;
  7289. const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
  7290. idx += 1; // skip 1 size byte
  7291. for (size_t i = 0; i < len; ++i)
  7292. {
  7293. cbor_expect_string(v, idx);
  7294. std::string key = from_cbor_internal(v, idx);
  7295. result[key] = from_cbor_internal(v, idx);
  7296. }
  7297. return result;
  7298. }
  7299. case 0xb9: // map (two-byte uint16_t for n follow)
  7300. {
  7301. basic_json result = value_t::object;
  7302. const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
  7303. idx += 2; // skip 2 size bytes
  7304. for (size_t i = 0; i < len; ++i)
  7305. {
  7306. cbor_expect_string(v, idx);
  7307. std::string key = from_cbor_internal(v, idx);
  7308. result[key] = from_cbor_internal(v, idx);
  7309. }
  7310. return result;
  7311. }
  7312. case 0xba: // map (four-byte uint32_t for n follow)
  7313. {
  7314. basic_json result = value_t::object;
  7315. const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
  7316. idx += 4; // skip 4 size bytes
  7317. for (size_t i = 0; i < len; ++i)
  7318. {
  7319. cbor_expect_string(v, idx);
  7320. std::string key = from_cbor_internal(v, idx);
  7321. result[key] = from_cbor_internal(v, idx);
  7322. }
  7323. return result;
  7324. }
  7325. case 0xbb: // map (eight-byte uint64_t for n follow)
  7326. {
  7327. basic_json result = value_t::object;
  7328. const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
  7329. idx += 8; // skip 8 size bytes
  7330. for (size_t i = 0; i < len; ++i)
  7331. {
  7332. cbor_expect_string(v, idx);
  7333. std::string key = from_cbor_internal(v, idx);
  7334. result[key] = from_cbor_internal(v, idx);
  7335. }
  7336. return result;
  7337. }
  7338. case 0xbf: // map (indefinite length)
  7339. {
  7340. basic_json result = value_t::object;
  7341. while (static_cast<void>(check_length(v.size(), 1, idx)), v[idx] != 0xff)
  7342. {
  7343. cbor_expect_string(v, idx);
  7344. std::string key = from_cbor_internal(v, idx);
  7345. result[key] = from_cbor_internal(v, idx);
  7346. }
  7347. // skip break byte (0xFF)
  7348. idx += 1;
  7349. return result;
  7350. }
  7351. case 0xf4: // false
  7352. {
  7353. return false;
  7354. }
  7355. case 0xf5: // true
  7356. {
  7357. return true;
  7358. }
  7359. case 0xf6: // null
  7360. {
  7361. return value_t::null;
  7362. }
  7363. case 0xf9: // Half-Precision Float (two-byte IEEE 754)
  7364. {
  7365. idx += 2; // skip two content bytes
  7366. // code from RFC 7049, Appendix D, Figure 3:
  7367. // As half-precision floating-point numbers were only added to
  7368. // IEEE 754 in 2008, today's programming platforms often still
  7369. // only have limited support for them. It is very easy to
  7370. // include at least decoding support for them even without such
  7371. // support. An example of a small decoder for half-precision
  7372. // floating-point numbers in the C language is shown in Fig. 3.
  7373. check_length(v.size(), 2, current_idx + 1);
  7374. const int half = (v[current_idx + 1] << 8) + v[current_idx + 2];
  7375. const int exp = (half >> 10) & 0x1f;
  7376. const int mant = half & 0x3ff;
  7377. double val;
  7378. if (exp == 0)
  7379. {
  7380. val = std::ldexp(mant, -24);
  7381. }
  7382. else if (exp != 31)
  7383. {
  7384. val = std::ldexp(mant + 1024, exp - 25);
  7385. }
  7386. else
  7387. {
  7388. val = mant == 0
  7389. ? std::numeric_limits<double>::infinity()
  7390. : std::numeric_limits<double>::quiet_NaN();
  7391. }
  7392. return (half & 0x8000) != 0 ? -val : val;
  7393. }
  7394. case 0xfa: // Single-Precision Float (four-byte IEEE 754)
  7395. {
  7396. // copy bytes in reverse order into the float variable
  7397. float res;
  7398. check_length(v.size(), sizeof(float), current_idx + 1);
  7399. for (size_t byte = 0; byte < sizeof(float); ++byte)
  7400. {
  7401. reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v[current_idx + 1 + byte];
  7402. }
  7403. idx += sizeof(float); // skip content bytes
  7404. return res;
  7405. }
  7406. case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
  7407. {
  7408. // copy bytes in reverse order into the double variable
  7409. double res;
  7410. check_length(v.size(), sizeof(double), current_idx + 1);
  7411. for (size_t byte = 0; byte < sizeof(double); ++byte)
  7412. {
  7413. reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v[current_idx + 1 + byte];
  7414. }
  7415. idx += sizeof(double); // skip content bytes
  7416. return res;
  7417. }
  7418. default: // anything else (0xFF is handled inside the other types)
  7419. {
  7420. std::stringstream ss;
  7421. ss << std::hex << static_cast<int>(v[current_idx]);
  7422. JSON_THROW(parse_error::create(112, current_idx + 1, "error reading CBOR; last byte: 0x" + ss.str()));
  7423. }
  7424. }
  7425. }
  7426. public:
  7427. /*!
  7428. @brief create a MessagePack serialization of a given JSON value
  7429. Serializes a given JSON value @a j to a byte vector using the MessagePack
  7430. serialization format. MessagePack is a binary serialization format which
  7431. aims to be more compact than JSON itself, yet more efficient to parse.
  7432. The library uses the following mapping from JSON values types to
  7433. MessagePack types according to the MessagePack specification:
  7434. JSON value type | value/range | MessagePack type | first byte
  7435. --------------- | --------------------------------- | ---------------- | ----------
  7436. null | `null` | nil | 0xc0
  7437. boolean | `true` | true | 0xc3
  7438. boolean | `false` | false | 0xc2
  7439. number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3
  7440. number_integer | -2147483648..-32769 | int32 | 0xd2
  7441. number_integer | -32768..-129 | int16 | 0xd1
  7442. number_integer | -128..-33 | int8 | 0xd0
  7443. number_integer | -32..-1 | negative fixint | 0xe0..0xff
  7444. number_integer | 0..127 | positive fixint | 0x00..0x7f
  7445. number_integer | 128..255 | uint 8 | 0xcc
  7446. number_integer | 256..65535 | uint 16 | 0xcd
  7447. number_integer | 65536..4294967295 | uint 32 | 0xce
  7448. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf
  7449. number_unsigned | 0..127 | positive fixint | 0x00..0x7f
  7450. number_unsigned | 128..255 | uint 8 | 0xcc
  7451. number_unsigned | 256..65535 | uint 16 | 0xcd
  7452. number_unsigned | 65536..4294967295 | uint 32 | 0xce
  7453. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf
  7454. number_float | *any value* | float 64 | 0xcb
  7455. string | *length*: 0..31 | fixstr | 0xa0..0xbf
  7456. string | *length*: 32..255 | str 8 | 0xd9
  7457. string | *length*: 256..65535 | str 16 | 0xda
  7458. string | *length*: 65536..4294967295 | str 32 | 0xdb
  7459. array | *size*: 0..15 | fixarray | 0x90..0x9f
  7460. array | *size*: 16..65535 | array 16 | 0xdc
  7461. array | *size*: 65536..4294967295 | array 32 | 0xdd
  7462. object | *size*: 0..15 | fix map | 0x80..0x8f
  7463. object | *size*: 16..65535 | map 16 | 0xde
  7464. object | *size*: 65536..4294967295 | map 32 | 0xdf
  7465. @note The mapping is **complete** in the sense that any JSON value type
  7466. can be converted to a MessagePack value.
  7467. @note The following values can **not** be converted to a MessagePack value:
  7468. - strings with more than 4294967295 bytes
  7469. - arrays with more than 4294967295 elements
  7470. - objects with more than 4294967295 elements
  7471. @note The following MessagePack types are not used in the conversion:
  7472. - bin 8 - bin 32 (0xc4..0xc6)
  7473. - ext 8 - ext 32 (0xc7..0xc9)
  7474. - float 32 (0xca)
  7475. - fixext 1 - fixext 16 (0xd4..0xd8)
  7476. @note Any MessagePack output created @ref to_msgpack can be successfully
  7477. parsed by @ref from_msgpack.
  7478. @param[in] j JSON value to serialize
  7479. @return MessagePack serialization as byte vector
  7480. @complexity Linear in the size of the JSON value @a j.
  7481. @liveexample{The example shows the serialization of a JSON value to a byte
  7482. vector in MessagePack format.,to_msgpack}
  7483. @sa http://msgpack.org
  7484. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  7485. analogous deserialization
  7486. @sa @ref to_cbor(const basic_json& for the related CBOR format
  7487. @since version 2.0.9
  7488. */
  7489. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  7490. {
  7491. std::vector<uint8_t> result;
  7492. to_msgpack_internal(j, result);
  7493. return result;
  7494. }
  7495. /*!
  7496. @brief create a JSON value from a byte vector in MessagePack format
  7497. Deserializes a given byte vector @a v to a JSON value using the MessagePack
  7498. serialization format.
  7499. The library maps MessagePack types to JSON value types as follows:
  7500. MessagePack type | JSON value type | first byte
  7501. ---------------- | --------------- | ----------
  7502. positive fixint | number_unsigned | 0x00..0x7f
  7503. fixmap | object | 0x80..0x8f
  7504. fixarray | array | 0x90..0x9f
  7505. fixstr | string | 0xa0..0xbf
  7506. nil | `null` | 0xc0
  7507. false | `false` | 0xc2
  7508. true | `true` | 0xc3
  7509. float 32 | number_float | 0xca
  7510. float 64 | number_float | 0xcb
  7511. uint 8 | number_unsigned | 0xcc
  7512. uint 16 | number_unsigned | 0xcd
  7513. uint 32 | number_unsigned | 0xce
  7514. uint 64 | number_unsigned | 0xcf
  7515. int 8 | number_integer | 0xd0
  7516. int 16 | number_integer | 0xd1
  7517. int 32 | number_integer | 0xd2
  7518. int 64 | number_integer | 0xd3
  7519. str 8 | string | 0xd9
  7520. str 16 | string | 0xda
  7521. str 32 | string | 0xdb
  7522. array 16 | array | 0xdc
  7523. array 32 | array | 0xdd
  7524. map 16 | object | 0xde
  7525. map 32 | object | 0xdf
  7526. negative fixint | number_integer | 0xe0-0xff
  7527. @warning The mapping is **incomplete** in the sense that not all
  7528. MessagePack types can be converted to a JSON value. The following
  7529. MessagePack types are not supported and will yield parse errors:
  7530. - bin 8 - bin 32 (0xc4..0xc6)
  7531. - ext 8 - ext 32 (0xc7..0xc9)
  7532. - fixext 1 - fixext 16 (0xd4..0xd8)
  7533. @note Any MessagePack output created @ref to_msgpack can be successfully
  7534. parsed by @ref from_msgpack.
  7535. @param[in] v a byte vector in MessagePack format
  7536. @param[in] start_index the index to start reading from @a v (0 by default)
  7537. @return deserialized JSON value
  7538. @throw parse_error.110 if the given vector ends prematurely
  7539. @throw parse_error.112 if unsupported features from MessagePack were
  7540. used in the given vector @a v or if the input is not valid MessagePack
  7541. @throw parse_error.113 if a string was expected as map key, but not found
  7542. @complexity Linear in the size of the byte vector @a v.
  7543. @liveexample{The example shows the deserialization of a byte vector in
  7544. MessagePack format to a JSON value.,from_msgpack}
  7545. @sa http://msgpack.org
  7546. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  7547. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  7548. related CBOR format
  7549. @since version 2.0.9, parameter @a start_index since 2.1.1
  7550. */
  7551. static basic_json from_msgpack(const std::vector<uint8_t>& v,
  7552. const size_t start_index = 0)
  7553. {
  7554. size_t i = start_index;
  7555. return from_msgpack_internal(v, i);
  7556. }
  7557. /*!
  7558. @brief create a MessagePack serialization of a given JSON value
  7559. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  7560. Binary Object Representation) serialization format. CBOR is a binary
  7561. serialization format which aims to be more compact than JSON itself, yet
  7562. more efficient to parse.
  7563. The library uses the following mapping from JSON values types to
  7564. CBOR types according to the CBOR specification (RFC 7049):
  7565. JSON value type | value/range | CBOR type | first byte
  7566. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  7567. null | `null` | Null | 0xf6
  7568. boolean | `true` | True | 0xf5
  7569. boolean | `false` | False | 0xf4
  7570. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b
  7571. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a
  7572. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  7573. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  7574. number_integer | -24..-1 | Negative integer | 0x20..0x37
  7575. number_integer | 0..23 | Integer | 0x00..0x17
  7576. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  7577. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  7578. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  7579. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  7580. number_unsigned | 0..23 | Integer | 0x00..0x17
  7581. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  7582. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  7583. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  7584. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  7585. number_float | *any value* | Double-Precision Float | 0xfb
  7586. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  7587. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  7588. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  7589. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a
  7590. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b
  7591. array | *size*: 0..23 | array | 0x80..0x97
  7592. array | *size*: 23..255 | array (1 byte follow) | 0x98
  7593. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  7594. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a
  7595. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b
  7596. object | *size*: 0..23 | map | 0xa0..0xb7
  7597. object | *size*: 23..255 | map (1 byte follow) | 0xb8
  7598. object | *size*: 256..65535 | map (2 bytes follow) | 0xb9
  7599. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba
  7600. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb
  7601. @note The mapping is **complete** in the sense that any JSON value type
  7602. can be converted to a CBOR value.
  7603. @note The following CBOR types are not used in the conversion:
  7604. - byte strings (0x40..0x5f)
  7605. - UTF-8 strings terminated by "break" (0x7f)
  7606. - arrays terminated by "break" (0x9f)
  7607. - maps terminated by "break" (0xbf)
  7608. - date/time (0xc0..0xc1)
  7609. - bignum (0xc2..0xc3)
  7610. - decimal fraction (0xc4)
  7611. - bigfloat (0xc5)
  7612. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  7613. - expected conversions (0xd5..0xd7)
  7614. - simple values (0xe0..0xf3, 0xf8)
  7615. - undefined (0xf7)
  7616. - half and single-precision floats (0xf9-0xfa)
  7617. - break (0xff)
  7618. @param[in] j JSON value to serialize
  7619. @return MessagePack serialization as byte vector
  7620. @complexity Linear in the size of the JSON value @a j.
  7621. @liveexample{The example shows the serialization of a JSON value to a byte
  7622. vector in CBOR format.,to_cbor}
  7623. @sa http://cbor.io
  7624. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  7625. analogous deserialization
  7626. @sa @ref to_msgpack(const basic_json& for the related MessagePack format
  7627. @since version 2.0.9
  7628. */
  7629. static std::vector<uint8_t> to_cbor(const basic_json& j)
  7630. {
  7631. std::vector<uint8_t> result;
  7632. to_cbor_internal(j, result);
  7633. return result;
  7634. }
  7635. /*!
  7636. @brief create a JSON value from a byte vector in CBOR format
  7637. Deserializes a given byte vector @a v to a JSON value using the CBOR
  7638. (Concise Binary Object Representation) serialization format.
  7639. The library maps CBOR types to JSON value types as follows:
  7640. CBOR type | JSON value type | first byte
  7641. ---------------------- | --------------- | ----------
  7642. Integer | number_unsigned | 0x00..0x17
  7643. Unsigned integer | number_unsigned | 0x18
  7644. Unsigned integer | number_unsigned | 0x19
  7645. Unsigned integer | number_unsigned | 0x1a
  7646. Unsigned integer | number_unsigned | 0x1b
  7647. Negative integer | number_integer | 0x20..0x37
  7648. Negative integer | number_integer | 0x38
  7649. Negative integer | number_integer | 0x39
  7650. Negative integer | number_integer | 0x3a
  7651. Negative integer | number_integer | 0x3b
  7652. Negative integer | number_integer | 0x40..0x57
  7653. UTF-8 string | string | 0x60..0x77
  7654. UTF-8 string | string | 0x78
  7655. UTF-8 string | string | 0x79
  7656. UTF-8 string | string | 0x7a
  7657. UTF-8 string | string | 0x7b
  7658. UTF-8 string | string | 0x7f
  7659. array | array | 0x80..0x97
  7660. array | array | 0x98
  7661. array | array | 0x99
  7662. array | array | 0x9a
  7663. array | array | 0x9b
  7664. array | array | 0x9f
  7665. map | object | 0xa0..0xb7
  7666. map | object | 0xb8
  7667. map | object | 0xb9
  7668. map | object | 0xba
  7669. map | object | 0xbb
  7670. map | object | 0xbf
  7671. False | `false` | 0xf4
  7672. True | `true` | 0xf5
  7673. Nill | `null` | 0xf6
  7674. Half-Precision Float | number_float | 0xf9
  7675. Single-Precision Float | number_float | 0xfa
  7676. Double-Precision Float | number_float | 0xfb
  7677. @warning The mapping is **incomplete** in the sense that not all CBOR
  7678. types can be converted to a JSON value. The following CBOR types
  7679. are not supported and will yield parse errors (parse_error.112):
  7680. - byte strings (0x40..0x5f)
  7681. - date/time (0xc0..0xc1)
  7682. - bignum (0xc2..0xc3)
  7683. - decimal fraction (0xc4)
  7684. - bigfloat (0xc5)
  7685. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  7686. - expected conversions (0xd5..0xd7)
  7687. - simple values (0xe0..0xf3, 0xf8)
  7688. - undefined (0xf7)
  7689. @warning CBOR allows map keys of any type, whereas JSON only allows
  7690. strings as keys in object values. Therefore, CBOR maps with keys
  7691. other than UTF-8 strings are rejected (parse_error.113).
  7692. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  7693. @ref from_cbor.
  7694. @param[in] v a byte vector in CBOR format
  7695. @param[in] start_index the index to start reading from @a v (0 by default)
  7696. @return deserialized JSON value
  7697. @throw parse_error.110 if the given vector ends prematurely
  7698. @throw parse_error.112 if unsupported features from CBOR were
  7699. used in the given vector @a v or if the input is not valid CBOR
  7700. @throw parse_error.113 if a string was expected as map key, but not found
  7701. @complexity Linear in the size of the byte vector @a v.
  7702. @liveexample{The example shows the deserialization of a byte vector in CBOR
  7703. format to a JSON value.,from_cbor}
  7704. @sa http://cbor.io
  7705. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  7706. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  7707. related MessagePack format
  7708. @since version 2.0.9, parameter @a start_index since 2.1.1
  7709. */
  7710. static basic_json from_cbor(const std::vector<uint8_t>& v,
  7711. const size_t start_index = 0)
  7712. {
  7713. size_t i = start_index;
  7714. return from_cbor_internal(v, i);
  7715. }
  7716. /// @}
  7717. ///////////////////////////
  7718. // convenience functions //
  7719. ///////////////////////////
  7720. /*!
  7721. @brief return the type as string
  7722. Returns the type name as string to be used in error messages - usually to
  7723. indicate that a function was called on a wrong JSON type.
  7724. @return basically a string representation of a the @a m_type member
  7725. @complexity Constant.
  7726. @liveexample{The following code exemplifies `type_name()` for all JSON
  7727. types.,type_name}
  7728. @since version 1.0.0, public since 2.1.0
  7729. */
  7730. std::string type_name() const
  7731. {
  7732. {
  7733. switch (m_type)
  7734. {
  7735. case value_t::null:
  7736. return "null";
  7737. case value_t::object:
  7738. return "object";
  7739. case value_t::array:
  7740. return "array";
  7741. case value_t::string:
  7742. return "string";
  7743. case value_t::boolean:
  7744. return "boolean";
  7745. case value_t::discarded:
  7746. return "discarded";
  7747. default:
  7748. return "number";
  7749. }
  7750. }
  7751. }
  7752. private:
  7753. //////////////////////
  7754. // member variables //
  7755. //////////////////////
  7756. /// the type of the current element
  7757. value_t m_type = value_t::null;
  7758. /// the value of the current element
  7759. json_value m_value = {};
  7760. private:
  7761. ///////////////
  7762. // iterators //
  7763. ///////////////
  7764. /*!
  7765. @brief an iterator for primitive JSON types
  7766. This class models an iterator for primitive JSON types (boolean, number,
  7767. string). It's only purpose is to allow the iterator/const_iterator classes
  7768. to "iterate" over primitive values. Internally, the iterator is modeled by
  7769. a `difference_type` variable. Value begin_value (`0`) models the begin,
  7770. end_value (`1`) models past the end.
  7771. */
  7772. class primitive_iterator_t
  7773. {
  7774. public:
  7775. difference_type get_value() const noexcept
  7776. {
  7777. return m_it;
  7778. }
  7779. /// set iterator to a defined beginning
  7780. void set_begin() noexcept
  7781. {
  7782. m_it = begin_value;
  7783. }
  7784. /// set iterator to a defined past the end
  7785. void set_end() noexcept
  7786. {
  7787. m_it = end_value;
  7788. }
  7789. /// return whether the iterator can be dereferenced
  7790. constexpr bool is_begin() const noexcept
  7791. {
  7792. return (m_it == begin_value);
  7793. }
  7794. /// return whether the iterator is at end
  7795. constexpr bool is_end() const noexcept
  7796. {
  7797. return (m_it == end_value);
  7798. }
  7799. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7800. {
  7801. return lhs.m_it == rhs.m_it;
  7802. }
  7803. friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7804. {
  7805. return !(lhs == rhs);
  7806. }
  7807. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7808. {
  7809. return lhs.m_it < rhs.m_it;
  7810. }
  7811. friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7812. {
  7813. return lhs.m_it <= rhs.m_it;
  7814. }
  7815. friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7816. {
  7817. return lhs.m_it > rhs.m_it;
  7818. }
  7819. friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7820. {
  7821. return lhs.m_it >= rhs.m_it;
  7822. }
  7823. primitive_iterator_t operator+(difference_type i)
  7824. {
  7825. auto result = *this;
  7826. result += i;
  7827. return result;
  7828. }
  7829. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  7830. {
  7831. return lhs.m_it - rhs.m_it;
  7832. }
  7833. friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
  7834. {
  7835. return os << it.m_it;
  7836. }
  7837. primitive_iterator_t& operator++()
  7838. {
  7839. ++m_it;
  7840. return *this;
  7841. }
  7842. primitive_iterator_t operator++(int)
  7843. {
  7844. auto result = *this;
  7845. m_it++;
  7846. return result;
  7847. }
  7848. primitive_iterator_t& operator--()
  7849. {
  7850. --m_it;
  7851. return *this;
  7852. }
  7853. primitive_iterator_t operator--(int)
  7854. {
  7855. auto result = *this;
  7856. m_it--;
  7857. return result;
  7858. }
  7859. primitive_iterator_t& operator+=(difference_type n)
  7860. {
  7861. m_it += n;
  7862. return *this;
  7863. }
  7864. primitive_iterator_t& operator-=(difference_type n)
  7865. {
  7866. m_it -= n;
  7867. return *this;
  7868. }
  7869. private:
  7870. static constexpr difference_type begin_value = 0;
  7871. static constexpr difference_type end_value = begin_value + 1;
  7872. /// iterator as signed integer type
  7873. difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
  7874. };
  7875. /*!
  7876. @brief an iterator value
  7877. @note This structure could easily be a union, but MSVC currently does not
  7878. allow unions members with complex constructors, see
  7879. https://github.com/nlohmann/json/pull/105.
  7880. */
  7881. struct internal_iterator
  7882. {
  7883. /// iterator for JSON objects
  7884. typename object_t::iterator object_iterator;
  7885. /// iterator for JSON arrays
  7886. typename array_t::iterator array_iterator;
  7887. /// generic iterator for all other types
  7888. primitive_iterator_t primitive_iterator;
  7889. /// create an uninitialized internal_iterator
  7890. internal_iterator() noexcept
  7891. : object_iterator(), array_iterator(), primitive_iterator()
  7892. {}
  7893. };
  7894. /// proxy class for the iterator_wrapper functions
  7895. template<typename IteratorType>
  7896. class iteration_proxy
  7897. {
  7898. private:
  7899. /// helper class for iteration
  7900. class iteration_proxy_internal
  7901. {
  7902. private:
  7903. /// the iterator
  7904. IteratorType anchor;
  7905. /// an index for arrays (used to create key names)
  7906. size_t array_index = 0;
  7907. public:
  7908. explicit iteration_proxy_internal(IteratorType it) noexcept
  7909. : anchor(it)
  7910. {}
  7911. /// dereference operator (needed for range-based for)
  7912. iteration_proxy_internal& operator*()
  7913. {
  7914. return *this;
  7915. }
  7916. /// increment operator (needed for range-based for)
  7917. iteration_proxy_internal& operator++()
  7918. {
  7919. ++anchor;
  7920. ++array_index;
  7921. return *this;
  7922. }
  7923. /// inequality operator (needed for range-based for)
  7924. bool operator!= (const iteration_proxy_internal& o) const
  7925. {
  7926. return anchor != o.anchor;
  7927. }
  7928. /// return key of the iterator
  7929. typename basic_json::string_t key() const
  7930. {
  7931. assert(anchor.m_object != nullptr);
  7932. switch (anchor.m_object->type())
  7933. {
  7934. // use integer array index as key
  7935. case value_t::array:
  7936. {
  7937. return std::to_string(array_index);
  7938. }
  7939. // use key from the object
  7940. case value_t::object:
  7941. {
  7942. return anchor.key();
  7943. }
  7944. // use an empty key for all primitive types
  7945. default:
  7946. {
  7947. return "";
  7948. }
  7949. }
  7950. }
  7951. /// return value of the iterator
  7952. typename IteratorType::reference value() const
  7953. {
  7954. return anchor.value();
  7955. }
  7956. };
  7957. /// the container to iterate
  7958. typename IteratorType::reference container;
  7959. public:
  7960. /// construct iteration proxy from a container
  7961. explicit iteration_proxy(typename IteratorType::reference cont)
  7962. : container(cont)
  7963. {}
  7964. /// return iterator begin (needed for range-based for)
  7965. iteration_proxy_internal begin() noexcept
  7966. {
  7967. return iteration_proxy_internal(container.begin());
  7968. }
  7969. /// return iterator end (needed for range-based for)
  7970. iteration_proxy_internal end() noexcept
  7971. {
  7972. return iteration_proxy_internal(container.end());
  7973. }
  7974. };
  7975. public:
  7976. /*!
  7977. @brief a template for a random access iterator for the @ref basic_json class
  7978. This class implements a both iterators (iterator and const_iterator) for the
  7979. @ref basic_json class.
  7980. @note An iterator is called *initialized* when a pointer to a JSON value
  7981. has been set (e.g., by a constructor or a copy assignment). If the
  7982. iterator is default-constructed, it is *uninitialized* and most
  7983. methods are undefined. **The library uses assertions to detect calls
  7984. on uninitialized iterators.**
  7985. @requirement The class satisfies the following concept requirements:
  7986. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  7987. The iterator that can be moved to point (forward and backward) to any
  7988. element in constant time.
  7989. @since version 1.0.0, simplified in version 2.0.9
  7990. */
  7991. template<typename U>
  7992. class iter_impl : public std::iterator<std::random_access_iterator_tag, U>
  7993. {
  7994. /// allow basic_json to access private members
  7995. friend class basic_json;
  7996. // make sure U is basic_json or const basic_json
  7997. static_assert(std::is_same<U, basic_json>::value
  7998. or std::is_same<U, const basic_json>::value,
  7999. "iter_impl only accepts (const) basic_json");
  8000. public:
  8001. /// the type of the values when the iterator is dereferenced
  8002. using value_type = typename basic_json::value_type;
  8003. /// a type to represent differences between iterators
  8004. using difference_type = typename basic_json::difference_type;
  8005. /// defines a pointer to the type iterated over (value_type)
  8006. using pointer = typename std::conditional<std::is_const<U>::value,
  8007. typename basic_json::const_pointer,
  8008. typename basic_json::pointer>::type;
  8009. /// defines a reference to the type iterated over (value_type)
  8010. using reference = typename std::conditional<std::is_const<U>::value,
  8011. typename basic_json::const_reference,
  8012. typename basic_json::reference>::type;
  8013. /// the category of the iterator
  8014. using iterator_category = std::bidirectional_iterator_tag;
  8015. /// default constructor
  8016. iter_impl() = default;
  8017. /*!
  8018. @brief constructor for a given JSON instance
  8019. @param[in] object pointer to a JSON object for this iterator
  8020. @pre object != nullptr
  8021. @post The iterator is initialized; i.e. `m_object != nullptr`.
  8022. */
  8023. explicit iter_impl(pointer object) noexcept
  8024. : m_object(object)
  8025. {
  8026. assert(m_object != nullptr);
  8027. switch (m_object->m_type)
  8028. {
  8029. case basic_json::value_t::object:
  8030. {
  8031. m_it.object_iterator = typename object_t::iterator();
  8032. break;
  8033. }
  8034. case basic_json::value_t::array:
  8035. {
  8036. m_it.array_iterator = typename array_t::iterator();
  8037. break;
  8038. }
  8039. default:
  8040. {
  8041. m_it.primitive_iterator = primitive_iterator_t();
  8042. break;
  8043. }
  8044. }
  8045. }
  8046. /*
  8047. Use operator `const_iterator` instead of `const_iterator(const iterator&
  8048. other) noexcept` to avoid two class definitions for @ref iterator and
  8049. @ref const_iterator.
  8050. This function is only called if this class is an @ref iterator. If this
  8051. class is a @ref const_iterator this function is not called.
  8052. */
  8053. operator const_iterator() const
  8054. {
  8055. const_iterator ret;
  8056. if (m_object)
  8057. {
  8058. ret.m_object = m_object;
  8059. ret.m_it = m_it;
  8060. }
  8061. return ret;
  8062. }
  8063. /*!
  8064. @brief copy constructor
  8065. @param[in] other iterator to copy from
  8066. @note It is not checked whether @a other is initialized.
  8067. */
  8068. iter_impl(const iter_impl& other) noexcept
  8069. : m_object(other.m_object), m_it(other.m_it)
  8070. {}
  8071. /*!
  8072. @brief copy assignment
  8073. @param[in,out] other iterator to copy from
  8074. @note It is not checked whether @a other is initialized.
  8075. */
  8076. iter_impl& operator=(iter_impl other) noexcept(
  8077. std::is_nothrow_move_constructible<pointer>::value and
  8078. std::is_nothrow_move_assignable<pointer>::value and
  8079. std::is_nothrow_move_constructible<internal_iterator>::value and
  8080. std::is_nothrow_move_assignable<internal_iterator>::value
  8081. )
  8082. {
  8083. std::swap(m_object, other.m_object);
  8084. std::swap(m_it, other.m_it);
  8085. return *this;
  8086. }
  8087. private:
  8088. /*!
  8089. @brief set the iterator to the first value
  8090. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8091. */
  8092. void set_begin() noexcept
  8093. {
  8094. assert(m_object != nullptr);
  8095. switch (m_object->m_type)
  8096. {
  8097. case basic_json::value_t::object:
  8098. {
  8099. m_it.object_iterator = m_object->m_value.object->begin();
  8100. break;
  8101. }
  8102. case basic_json::value_t::array:
  8103. {
  8104. m_it.array_iterator = m_object->m_value.array->begin();
  8105. break;
  8106. }
  8107. case basic_json::value_t::null:
  8108. {
  8109. // set to end so begin()==end() is true: null is empty
  8110. m_it.primitive_iterator.set_end();
  8111. break;
  8112. }
  8113. default:
  8114. {
  8115. m_it.primitive_iterator.set_begin();
  8116. break;
  8117. }
  8118. }
  8119. }
  8120. /*!
  8121. @brief set the iterator past the last value
  8122. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8123. */
  8124. void set_end() noexcept
  8125. {
  8126. assert(m_object != nullptr);
  8127. switch (m_object->m_type)
  8128. {
  8129. case basic_json::value_t::object:
  8130. {
  8131. m_it.object_iterator = m_object->m_value.object->end();
  8132. break;
  8133. }
  8134. case basic_json::value_t::array:
  8135. {
  8136. m_it.array_iterator = m_object->m_value.array->end();
  8137. break;
  8138. }
  8139. default:
  8140. {
  8141. m_it.primitive_iterator.set_end();
  8142. break;
  8143. }
  8144. }
  8145. }
  8146. public:
  8147. /*!
  8148. @brief return a reference to the value pointed to by the iterator
  8149. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8150. */
  8151. reference operator*() const
  8152. {
  8153. assert(m_object != nullptr);
  8154. switch (m_object->m_type)
  8155. {
  8156. case basic_json::value_t::object:
  8157. {
  8158. assert(m_it.object_iterator != m_object->m_value.object->end());
  8159. return m_it.object_iterator->second;
  8160. }
  8161. case basic_json::value_t::array:
  8162. {
  8163. assert(m_it.array_iterator != m_object->m_value.array->end());
  8164. return *m_it.array_iterator;
  8165. }
  8166. case basic_json::value_t::null:
  8167. {
  8168. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8169. }
  8170. default:
  8171. {
  8172. if (m_it.primitive_iterator.is_begin())
  8173. {
  8174. return *m_object;
  8175. }
  8176. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8177. }
  8178. }
  8179. }
  8180. /*!
  8181. @brief dereference the iterator
  8182. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8183. */
  8184. pointer operator->() const
  8185. {
  8186. assert(m_object != nullptr);
  8187. switch (m_object->m_type)
  8188. {
  8189. case basic_json::value_t::object:
  8190. {
  8191. assert(m_it.object_iterator != m_object->m_value.object->end());
  8192. return &(m_it.object_iterator->second);
  8193. }
  8194. case basic_json::value_t::array:
  8195. {
  8196. assert(m_it.array_iterator != m_object->m_value.array->end());
  8197. return &*m_it.array_iterator;
  8198. }
  8199. default:
  8200. {
  8201. if (m_it.primitive_iterator.is_begin())
  8202. {
  8203. return m_object;
  8204. }
  8205. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8206. }
  8207. }
  8208. }
  8209. /*!
  8210. @brief post-increment (it++)
  8211. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8212. */
  8213. iter_impl operator++(int)
  8214. {
  8215. auto result = *this;
  8216. ++(*this);
  8217. return result;
  8218. }
  8219. /*!
  8220. @brief pre-increment (++it)
  8221. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8222. */
  8223. iter_impl& operator++()
  8224. {
  8225. assert(m_object != nullptr);
  8226. switch (m_object->m_type)
  8227. {
  8228. case basic_json::value_t::object:
  8229. {
  8230. std::advance(m_it.object_iterator, 1);
  8231. break;
  8232. }
  8233. case basic_json::value_t::array:
  8234. {
  8235. std::advance(m_it.array_iterator, 1);
  8236. break;
  8237. }
  8238. default:
  8239. {
  8240. ++m_it.primitive_iterator;
  8241. break;
  8242. }
  8243. }
  8244. return *this;
  8245. }
  8246. /*!
  8247. @brief post-decrement (it--)
  8248. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8249. */
  8250. iter_impl operator--(int)
  8251. {
  8252. auto result = *this;
  8253. --(*this);
  8254. return result;
  8255. }
  8256. /*!
  8257. @brief pre-decrement (--it)
  8258. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8259. */
  8260. iter_impl& operator--()
  8261. {
  8262. assert(m_object != nullptr);
  8263. switch (m_object->m_type)
  8264. {
  8265. case basic_json::value_t::object:
  8266. {
  8267. std::advance(m_it.object_iterator, -1);
  8268. break;
  8269. }
  8270. case basic_json::value_t::array:
  8271. {
  8272. std::advance(m_it.array_iterator, -1);
  8273. break;
  8274. }
  8275. default:
  8276. {
  8277. --m_it.primitive_iterator;
  8278. break;
  8279. }
  8280. }
  8281. return *this;
  8282. }
  8283. /*!
  8284. @brief comparison: equal
  8285. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8286. */
  8287. bool operator==(const iter_impl& other) const
  8288. {
  8289. // if objects are not the same, the comparison is undefined
  8290. if (m_object != other.m_object)
  8291. {
  8292. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8293. }
  8294. assert(m_object != nullptr);
  8295. switch (m_object->m_type)
  8296. {
  8297. case basic_json::value_t::object:
  8298. {
  8299. return (m_it.object_iterator == other.m_it.object_iterator);
  8300. }
  8301. case basic_json::value_t::array:
  8302. {
  8303. return (m_it.array_iterator == other.m_it.array_iterator);
  8304. }
  8305. default:
  8306. {
  8307. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  8308. }
  8309. }
  8310. }
  8311. /*!
  8312. @brief comparison: not equal
  8313. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8314. */
  8315. bool operator!=(const iter_impl& other) const
  8316. {
  8317. return not operator==(other);
  8318. }
  8319. /*!
  8320. @brief comparison: smaller
  8321. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8322. */
  8323. bool operator<(const iter_impl& other) const
  8324. {
  8325. // if objects are not the same, the comparison is undefined
  8326. if (m_object != other.m_object)
  8327. {
  8328. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  8329. }
  8330. assert(m_object != nullptr);
  8331. switch (m_object->m_type)
  8332. {
  8333. case basic_json::value_t::object:
  8334. {
  8335. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  8336. }
  8337. case basic_json::value_t::array:
  8338. {
  8339. return (m_it.array_iterator < other.m_it.array_iterator);
  8340. }
  8341. default:
  8342. {
  8343. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  8344. }
  8345. }
  8346. }
  8347. /*!
  8348. @brief comparison: less than or equal
  8349. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8350. */
  8351. bool operator<=(const iter_impl& other) const
  8352. {
  8353. return not other.operator < (*this);
  8354. }
  8355. /*!
  8356. @brief comparison: greater than
  8357. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8358. */
  8359. bool operator>(const iter_impl& other) const
  8360. {
  8361. return not operator<=(other);
  8362. }
  8363. /*!
  8364. @brief comparison: greater than or equal
  8365. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8366. */
  8367. bool operator>=(const iter_impl& other) const
  8368. {
  8369. return not operator<(other);
  8370. }
  8371. /*!
  8372. @brief add to iterator
  8373. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8374. */
  8375. iter_impl& operator+=(difference_type i)
  8376. {
  8377. assert(m_object != nullptr);
  8378. switch (m_object->m_type)
  8379. {
  8380. case basic_json::value_t::object:
  8381. {
  8382. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8383. }
  8384. case basic_json::value_t::array:
  8385. {
  8386. std::advance(m_it.array_iterator, i);
  8387. break;
  8388. }
  8389. default:
  8390. {
  8391. m_it.primitive_iterator += i;
  8392. break;
  8393. }
  8394. }
  8395. return *this;
  8396. }
  8397. /*!
  8398. @brief subtract from iterator
  8399. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8400. */
  8401. iter_impl& operator-=(difference_type i)
  8402. {
  8403. return operator+=(-i);
  8404. }
  8405. /*!
  8406. @brief add to iterator
  8407. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8408. */
  8409. iter_impl operator+(difference_type i)
  8410. {
  8411. auto result = *this;
  8412. result += i;
  8413. return result;
  8414. }
  8415. /*!
  8416. @brief subtract from iterator
  8417. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8418. */
  8419. iter_impl operator-(difference_type i)
  8420. {
  8421. auto result = *this;
  8422. result -= i;
  8423. return result;
  8424. }
  8425. /*!
  8426. @brief return difference
  8427. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8428. */
  8429. difference_type operator-(const iter_impl& other) const
  8430. {
  8431. assert(m_object != nullptr);
  8432. switch (m_object->m_type)
  8433. {
  8434. case basic_json::value_t::object:
  8435. {
  8436. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  8437. }
  8438. case basic_json::value_t::array:
  8439. {
  8440. return m_it.array_iterator - other.m_it.array_iterator;
  8441. }
  8442. default:
  8443. {
  8444. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  8445. }
  8446. }
  8447. }
  8448. /*!
  8449. @brief access to successor
  8450. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8451. */
  8452. reference operator[](difference_type n) const
  8453. {
  8454. assert(m_object != nullptr);
  8455. switch (m_object->m_type)
  8456. {
  8457. case basic_json::value_t::object:
  8458. {
  8459. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  8460. }
  8461. case basic_json::value_t::array:
  8462. {
  8463. return *std::next(m_it.array_iterator, n);
  8464. }
  8465. case basic_json::value_t::null:
  8466. {
  8467. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8468. }
  8469. default:
  8470. {
  8471. if (m_it.primitive_iterator.get_value() == -n)
  8472. {
  8473. return *m_object;
  8474. }
  8475. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  8476. }
  8477. }
  8478. }
  8479. /*!
  8480. @brief return the key of an object iterator
  8481. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8482. */
  8483. typename object_t::key_type key() const
  8484. {
  8485. assert(m_object != nullptr);
  8486. if (m_object->is_object())
  8487. {
  8488. return m_it.object_iterator->first;
  8489. }
  8490. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  8491. }
  8492. /*!
  8493. @brief return the value of an iterator
  8494. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  8495. */
  8496. reference value() const
  8497. {
  8498. return operator*();
  8499. }
  8500. private:
  8501. /// associated JSON instance
  8502. pointer m_object = nullptr;
  8503. /// the actual iterator of the associated instance
  8504. internal_iterator m_it = internal_iterator();
  8505. };
  8506. /*!
  8507. @brief a template for a reverse iterator class
  8508. @tparam Base the base iterator type to reverse. Valid types are @ref
  8509. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  8510. create @ref const_reverse_iterator).
  8511. @requirement The class satisfies the following concept requirements:
  8512. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  8513. The iterator that can be moved to point (forward and backward) to any
  8514. element in constant time.
  8515. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  8516. It is possible to write to the pointed-to element (only if @a Base is
  8517. @ref iterator).
  8518. @since version 1.0.0
  8519. */
  8520. template<typename Base>
  8521. class json_reverse_iterator : public std::reverse_iterator<Base>
  8522. {
  8523. public:
  8524. /// shortcut to the reverse iterator adaptor
  8525. using base_iterator = std::reverse_iterator<Base>;
  8526. /// the reference type for the pointed-to element
  8527. using reference = typename Base::reference;
  8528. /// create reverse iterator from iterator
  8529. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  8530. : base_iterator(it)
  8531. {}
  8532. /// create reverse iterator from base class
  8533. json_reverse_iterator(const base_iterator& it) noexcept
  8534. : base_iterator(it)
  8535. {}
  8536. /// post-increment (it++)
  8537. json_reverse_iterator operator++(int)
  8538. {
  8539. return base_iterator::operator++(1);
  8540. }
  8541. /// pre-increment (++it)
  8542. json_reverse_iterator& operator++()
  8543. {
  8544. base_iterator::operator++();
  8545. return *this;
  8546. }
  8547. /// post-decrement (it--)
  8548. json_reverse_iterator operator--(int)
  8549. {
  8550. return base_iterator::operator--(1);
  8551. }
  8552. /// pre-decrement (--it)
  8553. json_reverse_iterator& operator--()
  8554. {
  8555. base_iterator::operator--();
  8556. return *this;
  8557. }
  8558. /// add to iterator
  8559. json_reverse_iterator& operator+=(difference_type i)
  8560. {
  8561. base_iterator::operator+=(i);
  8562. return *this;
  8563. }
  8564. /// add to iterator
  8565. json_reverse_iterator operator+(difference_type i) const
  8566. {
  8567. auto result = *this;
  8568. result += i;
  8569. return result;
  8570. }
  8571. /// subtract from iterator
  8572. json_reverse_iterator operator-(difference_type i) const
  8573. {
  8574. auto result = *this;
  8575. result -= i;
  8576. return result;
  8577. }
  8578. /// return difference
  8579. difference_type operator-(const json_reverse_iterator& other) const
  8580. {
  8581. return this->base() - other.base();
  8582. }
  8583. /// access to successor
  8584. reference operator[](difference_type n) const
  8585. {
  8586. return *(this->operator+(n));
  8587. }
  8588. /// return the key of an object iterator
  8589. typename object_t::key_type key() const
  8590. {
  8591. auto it = --this->base();
  8592. return it.key();
  8593. }
  8594. /// return the value of an iterator
  8595. reference value() const
  8596. {
  8597. auto it = --this->base();
  8598. return it.operator * ();
  8599. }
  8600. };
  8601. private:
  8602. //////////////////////
  8603. // lexer and parser //
  8604. //////////////////////
  8605. /*!
  8606. @brief lexical analysis
  8607. This class organizes the lexical analysis during JSON deserialization. The
  8608. core of it is a scanner generated by [re2c](http://re2c.org) that
  8609. processes a buffer and recognizes tokens according to RFC 7159.
  8610. */
  8611. class lexer
  8612. {
  8613. public:
  8614. /// token types for the parser
  8615. enum class token_type
  8616. {
  8617. uninitialized, ///< indicating the scanner is uninitialized
  8618. literal_true, ///< the `true` literal
  8619. literal_false, ///< the `false` literal
  8620. literal_null, ///< the `null` literal
  8621. value_string, ///< a string -- use get_string() for actual value
  8622. value_unsigned, ///< an unsigned integer -- use get_number() for actual value
  8623. value_integer, ///< a signed integer -- use get_number() for actual value
  8624. value_float, ///< an floating point number -- use get_number() for actual value
  8625. begin_array, ///< the character for array begin `[`
  8626. begin_object, ///< the character for object begin `{`
  8627. end_array, ///< the character for array end `]`
  8628. end_object, ///< the character for object end `}`
  8629. name_separator, ///< the name separator `:`
  8630. value_separator, ///< the value separator `,`
  8631. parse_error, ///< indicating a parse error
  8632. end_of_input ///< indicating the end of the input buffer
  8633. };
  8634. /// the char type to use in the lexer
  8635. using lexer_char_t = unsigned char;
  8636. /// a lexer from a buffer with given length
  8637. lexer(const lexer_char_t* buff, const size_t len) noexcept
  8638. : m_content(buff)
  8639. {
  8640. assert(m_content != nullptr);
  8641. m_start = m_cursor = m_content;
  8642. m_limit = m_content + len;
  8643. }
  8644. /*!
  8645. @brief a lexer from an input stream
  8646. @throw parse_error.111 if input stream is in a bad state
  8647. */
  8648. explicit lexer(std::istream& s)
  8649. : m_stream(&s), m_line_buffer()
  8650. {
  8651. // immediately abort if stream is erroneous
  8652. if (s.fail())
  8653. {
  8654. JSON_THROW(parse_error::create(111, 0, "bad input stream"));
  8655. }
  8656. // fill buffer
  8657. fill_line_buffer();
  8658. // skip UTF-8 byte-order mark
  8659. if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF")
  8660. {
  8661. m_line_buffer[0] = ' ';
  8662. m_line_buffer[1] = ' ';
  8663. m_line_buffer[2] = ' ';
  8664. }
  8665. }
  8666. // switch off unwanted functions (due to pointer members)
  8667. lexer() = delete;
  8668. lexer(const lexer&) = delete;
  8669. lexer operator=(const lexer&) = delete;
  8670. /*!
  8671. @brief create a string from one or two Unicode code points
  8672. There are two cases: (1) @a codepoint1 is in the Basic Multilingual
  8673. Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2)
  8674. @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to
  8675. represent a code point above U+FFFF.
  8676. @param[in] codepoint1 the code point (can be high surrogate)
  8677. @param[in] codepoint2 the code point (can be low surrogate or 0)
  8678. @return string representation of the code point; the length of the
  8679. result string is between 1 and 4 characters.
  8680. @throw parse_error.102 if the low surrogate is invalid; example:
  8681. `""missing or wrong low surrogate""`
  8682. @throw parse_error.103 if code point is > 0x10ffff; example: `"code
  8683. points above 0x10FFFF are invalid"`
  8684. @complexity Constant.
  8685. @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
  8686. */
  8687. string_t to_unicode(const std::size_t codepoint1,
  8688. const std::size_t codepoint2 = 0) const
  8689. {
  8690. // calculate the code point from the given code points
  8691. std::size_t codepoint = codepoint1;
  8692. // check if codepoint1 is a high surrogate
  8693. if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
  8694. {
  8695. // check if codepoint2 is a low surrogate
  8696. if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
  8697. {
  8698. codepoint =
  8699. // high surrogate occupies the most significant 22 bits
  8700. (codepoint1 << 10)
  8701. // low surrogate occupies the least significant 15 bits
  8702. + codepoint2
  8703. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  8704. // in the result so we have to subtract with:
  8705. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  8706. - 0x35FDC00;
  8707. }
  8708. else
  8709. {
  8710. JSON_THROW(parse_error::create(102, get_position(), "missing or wrong low surrogate"));
  8711. }
  8712. }
  8713. string_t result;
  8714. if (codepoint < 0x80)
  8715. {
  8716. // 1-byte characters: 0xxxxxxx (ASCII)
  8717. result.append(1, static_cast<typename string_t::value_type>(codepoint));
  8718. }
  8719. else if (codepoint <= 0x7ff)
  8720. {
  8721. // 2-byte characters: 110xxxxx 10xxxxxx
  8722. result.append(1, static_cast<typename string_t::value_type>(0xC0 | (codepoint >> 6)));
  8723. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  8724. }
  8725. else if (codepoint <= 0xffff)
  8726. {
  8727. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  8728. result.append(1, static_cast<typename string_t::value_type>(0xE0 | (codepoint >> 12)));
  8729. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  8730. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  8731. }
  8732. else if (codepoint <= 0x10ffff)
  8733. {
  8734. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  8735. result.append(1, static_cast<typename string_t::value_type>(0xF0 | (codepoint >> 18)));
  8736. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
  8737. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  8738. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  8739. }
  8740. else
  8741. {
  8742. JSON_THROW(parse_error::create(103, get_position(), "code points above 0x10FFFF are invalid"));
  8743. }
  8744. return result;
  8745. }
  8746. /// return name of values of type token_type (only used for errors)
  8747. static std::string token_type_name(const token_type t)
  8748. {
  8749. switch (t)
  8750. {
  8751. case token_type::uninitialized:
  8752. return "<uninitialized>";
  8753. case token_type::literal_true:
  8754. return "true literal";
  8755. case token_type::literal_false:
  8756. return "false literal";
  8757. case token_type::literal_null:
  8758. return "null literal";
  8759. case token_type::value_string:
  8760. return "string literal";
  8761. case lexer::token_type::value_unsigned:
  8762. case lexer::token_type::value_integer:
  8763. case lexer::token_type::value_float:
  8764. return "number literal";
  8765. case token_type::begin_array:
  8766. return "'['";
  8767. case token_type::begin_object:
  8768. return "'{'";
  8769. case token_type::end_array:
  8770. return "']'";
  8771. case token_type::end_object:
  8772. return "'}'";
  8773. case token_type::name_separator:
  8774. return "':'";
  8775. case token_type::value_separator:
  8776. return "','";
  8777. case token_type::parse_error:
  8778. return "<parse error>";
  8779. case token_type::end_of_input:
  8780. return "end of input";
  8781. default:
  8782. {
  8783. // catch non-enum values
  8784. return "unknown token"; // LCOV_EXCL_LINE
  8785. }
  8786. }
  8787. }
  8788. /*!
  8789. This function implements a scanner for JSON. It is specified using
  8790. regular expressions that try to follow RFC 7159 as close as possible.
  8791. These regular expressions are then translated into a minimized
  8792. deterministic finite automaton (DFA) by the tool
  8793. [re2c](http://re2c.org). As a result, the translated code for this
  8794. function consists of a large block of code with `goto` jumps.
  8795. @return the class of the next token read from the buffer
  8796. @complexity Linear in the length of the input.\n
  8797. Proposition: The loop below will always terminate for finite input.\n
  8798. Proof (by contradiction): Assume a finite input. To loop forever, the
  8799. loop must never hit code with a `break` statement. The only code
  8800. snippets without a `break` statement is the continue statement for
  8801. whitespace. To loop forever, the input must be an infinite sequence
  8802. whitespace. This contradicts the assumption of finite input, q.e.d.
  8803. */
  8804. token_type scan()
  8805. {
  8806. while (true)
  8807. {
  8808. // pointer for backtracking information
  8809. m_marker = nullptr;
  8810. // remember the begin of the token
  8811. m_start = m_cursor;
  8812. assert(m_start != nullptr);
  8813. {
  8814. lexer_char_t yych;
  8815. unsigned int yyaccept = 0;
  8816. static const unsigned char yybm[] =
  8817. {
  8818. 0, 0, 0, 0, 0, 0, 0, 0,
  8819. 0, 32, 32, 0, 0, 32, 0, 0,
  8820. 0, 0, 0, 0, 0, 0, 0, 0,
  8821. 0, 0, 0, 0, 0, 0, 0, 0,
  8822. 160, 128, 0, 128, 128, 128, 128, 128,
  8823. 128, 128, 128, 128, 128, 128, 128, 128,
  8824. 192, 192, 192, 192, 192, 192, 192, 192,
  8825. 192, 192, 128, 128, 128, 128, 128, 128,
  8826. 128, 128, 128, 128, 128, 128, 128, 128,
  8827. 128, 128, 128, 128, 128, 128, 128, 128,
  8828. 128, 128, 128, 128, 128, 128, 128, 128,
  8829. 128, 128, 128, 128, 0, 128, 128, 128,
  8830. 128, 128, 128, 128, 128, 128, 128, 128,
  8831. 128, 128, 128, 128, 128, 128, 128, 128,
  8832. 128, 128, 128, 128, 128, 128, 128, 128,
  8833. 128, 128, 128, 128, 128, 128, 128, 128,
  8834. 0, 0, 0, 0, 0, 0, 0, 0,
  8835. 0, 0, 0, 0, 0, 0, 0, 0,
  8836. 0, 0, 0, 0, 0, 0, 0, 0,
  8837. 0, 0, 0, 0, 0, 0, 0, 0,
  8838. 0, 0, 0, 0, 0, 0, 0, 0,
  8839. 0, 0, 0, 0, 0, 0, 0, 0,
  8840. 0, 0, 0, 0, 0, 0, 0, 0,
  8841. 0, 0, 0, 0, 0, 0, 0, 0,
  8842. 0, 0, 0, 0, 0, 0, 0, 0,
  8843. 0, 0, 0, 0, 0, 0, 0, 0,
  8844. 0, 0, 0, 0, 0, 0, 0, 0,
  8845. 0, 0, 0, 0, 0, 0, 0, 0,
  8846. 0, 0, 0, 0, 0, 0, 0, 0,
  8847. 0, 0, 0, 0, 0, 0, 0, 0,
  8848. 0, 0, 0, 0, 0, 0, 0, 0,
  8849. 0, 0, 0, 0, 0, 0, 0, 0,
  8850. };
  8851. if ((m_limit - m_cursor) < 5)
  8852. {
  8853. fill_line_buffer(5); // LCOV_EXCL_LINE
  8854. }
  8855. yych = *m_cursor;
  8856. if (yybm[0 + yych] & 32)
  8857. {
  8858. goto basic_json_parser_6;
  8859. }
  8860. if (yych <= '[')
  8861. {
  8862. if (yych <= '-')
  8863. {
  8864. if (yych <= '"')
  8865. {
  8866. if (yych <= 0x00)
  8867. {
  8868. goto basic_json_parser_2;
  8869. }
  8870. if (yych <= '!')
  8871. {
  8872. goto basic_json_parser_4;
  8873. }
  8874. goto basic_json_parser_9;
  8875. }
  8876. else
  8877. {
  8878. if (yych <= '+')
  8879. {
  8880. goto basic_json_parser_4;
  8881. }
  8882. if (yych <= ',')
  8883. {
  8884. goto basic_json_parser_10;
  8885. }
  8886. goto basic_json_parser_12;
  8887. }
  8888. }
  8889. else
  8890. {
  8891. if (yych <= '9')
  8892. {
  8893. if (yych <= '/')
  8894. {
  8895. goto basic_json_parser_4;
  8896. }
  8897. if (yych <= '0')
  8898. {
  8899. goto basic_json_parser_13;
  8900. }
  8901. goto basic_json_parser_15;
  8902. }
  8903. else
  8904. {
  8905. if (yych <= ':')
  8906. {
  8907. goto basic_json_parser_17;
  8908. }
  8909. if (yych <= 'Z')
  8910. {
  8911. goto basic_json_parser_4;
  8912. }
  8913. goto basic_json_parser_19;
  8914. }
  8915. }
  8916. }
  8917. else
  8918. {
  8919. if (yych <= 'n')
  8920. {
  8921. if (yych <= 'e')
  8922. {
  8923. if (yych == ']')
  8924. {
  8925. goto basic_json_parser_21;
  8926. }
  8927. goto basic_json_parser_4;
  8928. }
  8929. else
  8930. {
  8931. if (yych <= 'f')
  8932. {
  8933. goto basic_json_parser_23;
  8934. }
  8935. if (yych <= 'm')
  8936. {
  8937. goto basic_json_parser_4;
  8938. }
  8939. goto basic_json_parser_24;
  8940. }
  8941. }
  8942. else
  8943. {
  8944. if (yych <= 'z')
  8945. {
  8946. if (yych == 't')
  8947. {
  8948. goto basic_json_parser_25;
  8949. }
  8950. goto basic_json_parser_4;
  8951. }
  8952. else
  8953. {
  8954. if (yych <= '{')
  8955. {
  8956. goto basic_json_parser_26;
  8957. }
  8958. if (yych == '}')
  8959. {
  8960. goto basic_json_parser_28;
  8961. }
  8962. goto basic_json_parser_4;
  8963. }
  8964. }
  8965. }
  8966. basic_json_parser_2:
  8967. ++m_cursor;
  8968. {
  8969. last_token_type = token_type::end_of_input;
  8970. break;
  8971. }
  8972. basic_json_parser_4:
  8973. ++m_cursor;
  8974. basic_json_parser_5:
  8975. {
  8976. last_token_type = token_type::parse_error;
  8977. break;
  8978. }
  8979. basic_json_parser_6:
  8980. ++m_cursor;
  8981. if (m_limit <= m_cursor)
  8982. {
  8983. fill_line_buffer(1); // LCOV_EXCL_LINE
  8984. }
  8985. yych = *m_cursor;
  8986. if (yybm[0 + yych] & 32)
  8987. {
  8988. goto basic_json_parser_6;
  8989. }
  8990. {
  8991. position += static_cast<size_t>((m_cursor - m_start));
  8992. continue;
  8993. }
  8994. basic_json_parser_9:
  8995. yyaccept = 0;
  8996. yych = *(m_marker = ++m_cursor);
  8997. if (yych <= 0x1F)
  8998. {
  8999. goto basic_json_parser_5;
  9000. }
  9001. if (yych <= 0x7F)
  9002. {
  9003. goto basic_json_parser_31;
  9004. }
  9005. if (yych <= 0xC1)
  9006. {
  9007. goto basic_json_parser_5;
  9008. }
  9009. if (yych <= 0xF4)
  9010. {
  9011. goto basic_json_parser_31;
  9012. }
  9013. goto basic_json_parser_5;
  9014. basic_json_parser_10:
  9015. ++m_cursor;
  9016. {
  9017. last_token_type = token_type::value_separator;
  9018. break;
  9019. }
  9020. basic_json_parser_12:
  9021. yych = *++m_cursor;
  9022. if (yych <= '/')
  9023. {
  9024. goto basic_json_parser_5;
  9025. }
  9026. if (yych <= '0')
  9027. {
  9028. goto basic_json_parser_43;
  9029. }
  9030. if (yych <= '9')
  9031. {
  9032. goto basic_json_parser_45;
  9033. }
  9034. goto basic_json_parser_5;
  9035. basic_json_parser_13:
  9036. yyaccept = 1;
  9037. yych = *(m_marker = ++m_cursor);
  9038. if (yych <= '9')
  9039. {
  9040. if (yych == '.')
  9041. {
  9042. goto basic_json_parser_47;
  9043. }
  9044. if (yych >= '0')
  9045. {
  9046. goto basic_json_parser_48;
  9047. }
  9048. }
  9049. else
  9050. {
  9051. if (yych <= 'E')
  9052. {
  9053. if (yych >= 'E')
  9054. {
  9055. goto basic_json_parser_51;
  9056. }
  9057. }
  9058. else
  9059. {
  9060. if (yych == 'e')
  9061. {
  9062. goto basic_json_parser_51;
  9063. }
  9064. }
  9065. }
  9066. basic_json_parser_14:
  9067. {
  9068. last_token_type = token_type::value_unsigned;
  9069. break;
  9070. }
  9071. basic_json_parser_15:
  9072. yyaccept = 1;
  9073. m_marker = ++m_cursor;
  9074. if ((m_limit - m_cursor) < 3)
  9075. {
  9076. fill_line_buffer(3); // LCOV_EXCL_LINE
  9077. }
  9078. yych = *m_cursor;
  9079. if (yybm[0 + yych] & 64)
  9080. {
  9081. goto basic_json_parser_15;
  9082. }
  9083. if (yych <= 'D')
  9084. {
  9085. if (yych == '.')
  9086. {
  9087. goto basic_json_parser_47;
  9088. }
  9089. goto basic_json_parser_14;
  9090. }
  9091. else
  9092. {
  9093. if (yych <= 'E')
  9094. {
  9095. goto basic_json_parser_51;
  9096. }
  9097. if (yych == 'e')
  9098. {
  9099. goto basic_json_parser_51;
  9100. }
  9101. goto basic_json_parser_14;
  9102. }
  9103. basic_json_parser_17:
  9104. ++m_cursor;
  9105. {
  9106. last_token_type = token_type::name_separator;
  9107. break;
  9108. }
  9109. basic_json_parser_19:
  9110. ++m_cursor;
  9111. {
  9112. last_token_type = token_type::begin_array;
  9113. break;
  9114. }
  9115. basic_json_parser_21:
  9116. ++m_cursor;
  9117. {
  9118. last_token_type = token_type::end_array;
  9119. break;
  9120. }
  9121. basic_json_parser_23:
  9122. yyaccept = 0;
  9123. yych = *(m_marker = ++m_cursor);
  9124. if (yych == 'a')
  9125. {
  9126. goto basic_json_parser_52;
  9127. }
  9128. goto basic_json_parser_5;
  9129. basic_json_parser_24:
  9130. yyaccept = 0;
  9131. yych = *(m_marker = ++m_cursor);
  9132. if (yych == 'u')
  9133. {
  9134. goto basic_json_parser_53;
  9135. }
  9136. goto basic_json_parser_5;
  9137. basic_json_parser_25:
  9138. yyaccept = 0;
  9139. yych = *(m_marker = ++m_cursor);
  9140. if (yych == 'r')
  9141. {
  9142. goto basic_json_parser_54;
  9143. }
  9144. goto basic_json_parser_5;
  9145. basic_json_parser_26:
  9146. ++m_cursor;
  9147. {
  9148. last_token_type = token_type::begin_object;
  9149. break;
  9150. }
  9151. basic_json_parser_28:
  9152. ++m_cursor;
  9153. {
  9154. last_token_type = token_type::end_object;
  9155. break;
  9156. }
  9157. basic_json_parser_30:
  9158. ++m_cursor;
  9159. if (m_limit <= m_cursor)
  9160. {
  9161. fill_line_buffer(1); // LCOV_EXCL_LINE
  9162. }
  9163. yych = *m_cursor;
  9164. basic_json_parser_31:
  9165. if (yybm[0 + yych] & 128)
  9166. {
  9167. goto basic_json_parser_30;
  9168. }
  9169. if (yych <= 0xE0)
  9170. {
  9171. if (yych <= '\\')
  9172. {
  9173. if (yych <= 0x1F)
  9174. {
  9175. goto basic_json_parser_32;
  9176. }
  9177. if (yych <= '"')
  9178. {
  9179. goto basic_json_parser_33;
  9180. }
  9181. goto basic_json_parser_35;
  9182. }
  9183. else
  9184. {
  9185. if (yych <= 0xC1)
  9186. {
  9187. goto basic_json_parser_32;
  9188. }
  9189. if (yych <= 0xDF)
  9190. {
  9191. goto basic_json_parser_36;
  9192. }
  9193. goto basic_json_parser_37;
  9194. }
  9195. }
  9196. else
  9197. {
  9198. if (yych <= 0xEF)
  9199. {
  9200. if (yych == 0xED)
  9201. {
  9202. goto basic_json_parser_39;
  9203. }
  9204. goto basic_json_parser_38;
  9205. }
  9206. else
  9207. {
  9208. if (yych <= 0xF0)
  9209. {
  9210. goto basic_json_parser_40;
  9211. }
  9212. if (yych <= 0xF3)
  9213. {
  9214. goto basic_json_parser_41;
  9215. }
  9216. if (yych <= 0xF4)
  9217. {
  9218. goto basic_json_parser_42;
  9219. }
  9220. }
  9221. }
  9222. basic_json_parser_32:
  9223. m_cursor = m_marker;
  9224. if (yyaccept <= 1)
  9225. {
  9226. if (yyaccept == 0)
  9227. {
  9228. goto basic_json_parser_5;
  9229. }
  9230. else
  9231. {
  9232. goto basic_json_parser_14;
  9233. }
  9234. }
  9235. else
  9236. {
  9237. if (yyaccept == 2)
  9238. {
  9239. goto basic_json_parser_44;
  9240. }
  9241. else
  9242. {
  9243. goto basic_json_parser_58;
  9244. }
  9245. }
  9246. basic_json_parser_33:
  9247. ++m_cursor;
  9248. {
  9249. last_token_type = token_type::value_string;
  9250. break;
  9251. }
  9252. basic_json_parser_35:
  9253. ++m_cursor;
  9254. if (m_limit <= m_cursor)
  9255. {
  9256. fill_line_buffer(1); // LCOV_EXCL_LINE
  9257. }
  9258. yych = *m_cursor;
  9259. if (yych <= 'e')
  9260. {
  9261. if (yych <= '/')
  9262. {
  9263. if (yych == '"')
  9264. {
  9265. goto basic_json_parser_30;
  9266. }
  9267. if (yych <= '.')
  9268. {
  9269. goto basic_json_parser_32;
  9270. }
  9271. goto basic_json_parser_30;
  9272. }
  9273. else
  9274. {
  9275. if (yych <= '\\')
  9276. {
  9277. if (yych <= '[')
  9278. {
  9279. goto basic_json_parser_32;
  9280. }
  9281. goto basic_json_parser_30;
  9282. }
  9283. else
  9284. {
  9285. if (yych == 'b')
  9286. {
  9287. goto basic_json_parser_30;
  9288. }
  9289. goto basic_json_parser_32;
  9290. }
  9291. }
  9292. }
  9293. else
  9294. {
  9295. if (yych <= 'q')
  9296. {
  9297. if (yych <= 'f')
  9298. {
  9299. goto basic_json_parser_30;
  9300. }
  9301. if (yych == 'n')
  9302. {
  9303. goto basic_json_parser_30;
  9304. }
  9305. goto basic_json_parser_32;
  9306. }
  9307. else
  9308. {
  9309. if (yych <= 's')
  9310. {
  9311. if (yych <= 'r')
  9312. {
  9313. goto basic_json_parser_30;
  9314. }
  9315. goto basic_json_parser_32;
  9316. }
  9317. else
  9318. {
  9319. if (yych <= 't')
  9320. {
  9321. goto basic_json_parser_30;
  9322. }
  9323. if (yych <= 'u')
  9324. {
  9325. goto basic_json_parser_55;
  9326. }
  9327. goto basic_json_parser_32;
  9328. }
  9329. }
  9330. }
  9331. basic_json_parser_36:
  9332. ++m_cursor;
  9333. if (m_limit <= m_cursor)
  9334. {
  9335. fill_line_buffer(1); // LCOV_EXCL_LINE
  9336. }
  9337. yych = *m_cursor;
  9338. if (yych <= 0x7F)
  9339. {
  9340. goto basic_json_parser_32;
  9341. }
  9342. if (yych <= 0xBF)
  9343. {
  9344. goto basic_json_parser_30;
  9345. }
  9346. goto basic_json_parser_32;
  9347. basic_json_parser_37:
  9348. ++m_cursor;
  9349. if (m_limit <= m_cursor)
  9350. {
  9351. fill_line_buffer(1); // LCOV_EXCL_LINE
  9352. }
  9353. yych = *m_cursor;
  9354. if (yych <= 0x9F)
  9355. {
  9356. goto basic_json_parser_32;
  9357. }
  9358. if (yych <= 0xBF)
  9359. {
  9360. goto basic_json_parser_36;
  9361. }
  9362. goto basic_json_parser_32;
  9363. basic_json_parser_38:
  9364. ++m_cursor;
  9365. if (m_limit <= m_cursor)
  9366. {
  9367. fill_line_buffer(1); // LCOV_EXCL_LINE
  9368. }
  9369. yych = *m_cursor;
  9370. if (yych <= 0x7F)
  9371. {
  9372. goto basic_json_parser_32;
  9373. }
  9374. if (yych <= 0xBF)
  9375. {
  9376. goto basic_json_parser_36;
  9377. }
  9378. goto basic_json_parser_32;
  9379. basic_json_parser_39:
  9380. ++m_cursor;
  9381. if (m_limit <= m_cursor)
  9382. {
  9383. fill_line_buffer(1); // LCOV_EXCL_LINE
  9384. }
  9385. yych = *m_cursor;
  9386. if (yych <= 0x7F)
  9387. {
  9388. goto basic_json_parser_32;
  9389. }
  9390. if (yych <= 0x9F)
  9391. {
  9392. goto basic_json_parser_36;
  9393. }
  9394. goto basic_json_parser_32;
  9395. basic_json_parser_40:
  9396. ++m_cursor;
  9397. if (m_limit <= m_cursor)
  9398. {
  9399. fill_line_buffer(1); // LCOV_EXCL_LINE
  9400. }
  9401. yych = *m_cursor;
  9402. if (yych <= 0x8F)
  9403. {
  9404. goto basic_json_parser_32;
  9405. }
  9406. if (yych <= 0xBF)
  9407. {
  9408. goto basic_json_parser_38;
  9409. }
  9410. goto basic_json_parser_32;
  9411. basic_json_parser_41:
  9412. ++m_cursor;
  9413. if (m_limit <= m_cursor)
  9414. {
  9415. fill_line_buffer(1); // LCOV_EXCL_LINE
  9416. }
  9417. yych = *m_cursor;
  9418. if (yych <= 0x7F)
  9419. {
  9420. goto basic_json_parser_32;
  9421. }
  9422. if (yych <= 0xBF)
  9423. {
  9424. goto basic_json_parser_38;
  9425. }
  9426. goto basic_json_parser_32;
  9427. basic_json_parser_42:
  9428. ++m_cursor;
  9429. if (m_limit <= m_cursor)
  9430. {
  9431. fill_line_buffer(1); // LCOV_EXCL_LINE
  9432. }
  9433. yych = *m_cursor;
  9434. if (yych <= 0x7F)
  9435. {
  9436. goto basic_json_parser_32;
  9437. }
  9438. if (yych <= 0x8F)
  9439. {
  9440. goto basic_json_parser_38;
  9441. }
  9442. goto basic_json_parser_32;
  9443. basic_json_parser_43:
  9444. yyaccept = 2;
  9445. yych = *(m_marker = ++m_cursor);
  9446. if (yych <= '9')
  9447. {
  9448. if (yych == '.')
  9449. {
  9450. goto basic_json_parser_47;
  9451. }
  9452. if (yych >= '0')
  9453. {
  9454. goto basic_json_parser_48;
  9455. }
  9456. }
  9457. else
  9458. {
  9459. if (yych <= 'E')
  9460. {
  9461. if (yych >= 'E')
  9462. {
  9463. goto basic_json_parser_51;
  9464. }
  9465. }
  9466. else
  9467. {
  9468. if (yych == 'e')
  9469. {
  9470. goto basic_json_parser_51;
  9471. }
  9472. }
  9473. }
  9474. basic_json_parser_44:
  9475. {
  9476. last_token_type = token_type::value_integer;
  9477. break;
  9478. }
  9479. basic_json_parser_45:
  9480. yyaccept = 2;
  9481. m_marker = ++m_cursor;
  9482. if ((m_limit - m_cursor) < 3)
  9483. {
  9484. fill_line_buffer(3); // LCOV_EXCL_LINE
  9485. }
  9486. yych = *m_cursor;
  9487. if (yych <= '9')
  9488. {
  9489. if (yych == '.')
  9490. {
  9491. goto basic_json_parser_47;
  9492. }
  9493. if (yych <= '/')
  9494. {
  9495. goto basic_json_parser_44;
  9496. }
  9497. goto basic_json_parser_45;
  9498. }
  9499. else
  9500. {
  9501. if (yych <= 'E')
  9502. {
  9503. if (yych <= 'D')
  9504. {
  9505. goto basic_json_parser_44;
  9506. }
  9507. goto basic_json_parser_51;
  9508. }
  9509. else
  9510. {
  9511. if (yych == 'e')
  9512. {
  9513. goto basic_json_parser_51;
  9514. }
  9515. goto basic_json_parser_44;
  9516. }
  9517. }
  9518. basic_json_parser_47:
  9519. yych = *++m_cursor;
  9520. if (yych <= '/')
  9521. {
  9522. goto basic_json_parser_32;
  9523. }
  9524. if (yych <= '9')
  9525. {
  9526. goto basic_json_parser_56;
  9527. }
  9528. goto basic_json_parser_32;
  9529. basic_json_parser_48:
  9530. ++m_cursor;
  9531. if (m_limit <= m_cursor)
  9532. {
  9533. fill_line_buffer(1); // LCOV_EXCL_LINE
  9534. }
  9535. yych = *m_cursor;
  9536. if (yych <= '/')
  9537. {
  9538. goto basic_json_parser_50;
  9539. }
  9540. if (yych <= '9')
  9541. {
  9542. goto basic_json_parser_48;
  9543. }
  9544. basic_json_parser_50:
  9545. {
  9546. last_token_type = token_type::parse_error;
  9547. break;
  9548. }
  9549. basic_json_parser_51:
  9550. yych = *++m_cursor;
  9551. if (yych <= ',')
  9552. {
  9553. if (yych == '+')
  9554. {
  9555. goto basic_json_parser_59;
  9556. }
  9557. goto basic_json_parser_32;
  9558. }
  9559. else
  9560. {
  9561. if (yych <= '-')
  9562. {
  9563. goto basic_json_parser_59;
  9564. }
  9565. if (yych <= '/')
  9566. {
  9567. goto basic_json_parser_32;
  9568. }
  9569. if (yych <= '9')
  9570. {
  9571. goto basic_json_parser_60;
  9572. }
  9573. goto basic_json_parser_32;
  9574. }
  9575. basic_json_parser_52:
  9576. yych = *++m_cursor;
  9577. if (yych == 'l')
  9578. {
  9579. goto basic_json_parser_62;
  9580. }
  9581. goto basic_json_parser_32;
  9582. basic_json_parser_53:
  9583. yych = *++m_cursor;
  9584. if (yych == 'l')
  9585. {
  9586. goto basic_json_parser_63;
  9587. }
  9588. goto basic_json_parser_32;
  9589. basic_json_parser_54:
  9590. yych = *++m_cursor;
  9591. if (yych == 'u')
  9592. {
  9593. goto basic_json_parser_64;
  9594. }
  9595. goto basic_json_parser_32;
  9596. basic_json_parser_55:
  9597. ++m_cursor;
  9598. if (m_limit <= m_cursor)
  9599. {
  9600. fill_line_buffer(1); // LCOV_EXCL_LINE
  9601. }
  9602. yych = *m_cursor;
  9603. if (yych <= '@')
  9604. {
  9605. if (yych <= '/')
  9606. {
  9607. goto basic_json_parser_32;
  9608. }
  9609. if (yych <= '9')
  9610. {
  9611. goto basic_json_parser_65;
  9612. }
  9613. goto basic_json_parser_32;
  9614. }
  9615. else
  9616. {
  9617. if (yych <= 'F')
  9618. {
  9619. goto basic_json_parser_65;
  9620. }
  9621. if (yych <= '`')
  9622. {
  9623. goto basic_json_parser_32;
  9624. }
  9625. if (yych <= 'f')
  9626. {
  9627. goto basic_json_parser_65;
  9628. }
  9629. goto basic_json_parser_32;
  9630. }
  9631. basic_json_parser_56:
  9632. yyaccept = 3;
  9633. m_marker = ++m_cursor;
  9634. if ((m_limit - m_cursor) < 3)
  9635. {
  9636. fill_line_buffer(3); // LCOV_EXCL_LINE
  9637. }
  9638. yych = *m_cursor;
  9639. if (yych <= 'D')
  9640. {
  9641. if (yych <= '/')
  9642. {
  9643. goto basic_json_parser_58;
  9644. }
  9645. if (yych <= '9')
  9646. {
  9647. goto basic_json_parser_56;
  9648. }
  9649. }
  9650. else
  9651. {
  9652. if (yych <= 'E')
  9653. {
  9654. goto basic_json_parser_51;
  9655. }
  9656. if (yych == 'e')
  9657. {
  9658. goto basic_json_parser_51;
  9659. }
  9660. }
  9661. basic_json_parser_58:
  9662. {
  9663. last_token_type = token_type::value_float;
  9664. break;
  9665. }
  9666. basic_json_parser_59:
  9667. yych = *++m_cursor;
  9668. if (yych <= '/')
  9669. {
  9670. goto basic_json_parser_32;
  9671. }
  9672. if (yych >= ':')
  9673. {
  9674. goto basic_json_parser_32;
  9675. }
  9676. basic_json_parser_60:
  9677. ++m_cursor;
  9678. if (m_limit <= m_cursor)
  9679. {
  9680. fill_line_buffer(1); // LCOV_EXCL_LINE
  9681. }
  9682. yych = *m_cursor;
  9683. if (yych <= '/')
  9684. {
  9685. goto basic_json_parser_58;
  9686. }
  9687. if (yych <= '9')
  9688. {
  9689. goto basic_json_parser_60;
  9690. }
  9691. goto basic_json_parser_58;
  9692. basic_json_parser_62:
  9693. yych = *++m_cursor;
  9694. if (yych == 's')
  9695. {
  9696. goto basic_json_parser_66;
  9697. }
  9698. goto basic_json_parser_32;
  9699. basic_json_parser_63:
  9700. yych = *++m_cursor;
  9701. if (yych == 'l')
  9702. {
  9703. goto basic_json_parser_67;
  9704. }
  9705. goto basic_json_parser_32;
  9706. basic_json_parser_64:
  9707. yych = *++m_cursor;
  9708. if (yych == 'e')
  9709. {
  9710. goto basic_json_parser_69;
  9711. }
  9712. goto basic_json_parser_32;
  9713. basic_json_parser_65:
  9714. ++m_cursor;
  9715. if (m_limit <= m_cursor)
  9716. {
  9717. fill_line_buffer(1); // LCOV_EXCL_LINE
  9718. }
  9719. yych = *m_cursor;
  9720. if (yych <= '@')
  9721. {
  9722. if (yych <= '/')
  9723. {
  9724. goto basic_json_parser_32;
  9725. }
  9726. if (yych <= '9')
  9727. {
  9728. goto basic_json_parser_71;
  9729. }
  9730. goto basic_json_parser_32;
  9731. }
  9732. else
  9733. {
  9734. if (yych <= 'F')
  9735. {
  9736. goto basic_json_parser_71;
  9737. }
  9738. if (yych <= '`')
  9739. {
  9740. goto basic_json_parser_32;
  9741. }
  9742. if (yych <= 'f')
  9743. {
  9744. goto basic_json_parser_71;
  9745. }
  9746. goto basic_json_parser_32;
  9747. }
  9748. basic_json_parser_66:
  9749. yych = *++m_cursor;
  9750. if (yych == 'e')
  9751. {
  9752. goto basic_json_parser_72;
  9753. }
  9754. goto basic_json_parser_32;
  9755. basic_json_parser_67:
  9756. ++m_cursor;
  9757. {
  9758. last_token_type = token_type::literal_null;
  9759. break;
  9760. }
  9761. basic_json_parser_69:
  9762. ++m_cursor;
  9763. {
  9764. last_token_type = token_type::literal_true;
  9765. break;
  9766. }
  9767. basic_json_parser_71:
  9768. ++m_cursor;
  9769. if (m_limit <= m_cursor)
  9770. {
  9771. fill_line_buffer(1); // LCOV_EXCL_LINE
  9772. }
  9773. yych = *m_cursor;
  9774. if (yych <= '@')
  9775. {
  9776. if (yych <= '/')
  9777. {
  9778. goto basic_json_parser_32;
  9779. }
  9780. if (yych <= '9')
  9781. {
  9782. goto basic_json_parser_74;
  9783. }
  9784. goto basic_json_parser_32;
  9785. }
  9786. else
  9787. {
  9788. if (yych <= 'F')
  9789. {
  9790. goto basic_json_parser_74;
  9791. }
  9792. if (yych <= '`')
  9793. {
  9794. goto basic_json_parser_32;
  9795. }
  9796. if (yych <= 'f')
  9797. {
  9798. goto basic_json_parser_74;
  9799. }
  9800. goto basic_json_parser_32;
  9801. }
  9802. basic_json_parser_72:
  9803. ++m_cursor;
  9804. {
  9805. last_token_type = token_type::literal_false;
  9806. break;
  9807. }
  9808. basic_json_parser_74:
  9809. ++m_cursor;
  9810. if (m_limit <= m_cursor)
  9811. {
  9812. fill_line_buffer(1); // LCOV_EXCL_LINE
  9813. }
  9814. yych = *m_cursor;
  9815. if (yych <= '@')
  9816. {
  9817. if (yych <= '/')
  9818. {
  9819. goto basic_json_parser_32;
  9820. }
  9821. if (yych <= '9')
  9822. {
  9823. goto basic_json_parser_30;
  9824. }
  9825. goto basic_json_parser_32;
  9826. }
  9827. else
  9828. {
  9829. if (yych <= 'F')
  9830. {
  9831. goto basic_json_parser_30;
  9832. }
  9833. if (yych <= '`')
  9834. {
  9835. goto basic_json_parser_32;
  9836. }
  9837. if (yych <= 'f')
  9838. {
  9839. goto basic_json_parser_30;
  9840. }
  9841. goto basic_json_parser_32;
  9842. }
  9843. }
  9844. }
  9845. position += static_cast<size_t>((m_cursor - m_start));
  9846. return last_token_type;
  9847. }
  9848. /*!
  9849. @brief append data from the stream to the line buffer
  9850. This function is called by the scan() function when the end of the
  9851. buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be
  9852. incremented without leaving the limits of the line buffer. Note re2c
  9853. decides when to call this function.
  9854. If the lexer reads from contiguous storage, there is no trailing null
  9855. byte. Therefore, this function must make sure to add these padding
  9856. null bytes.
  9857. If the lexer reads from an input stream, this function reads the next
  9858. line of the input.
  9859. @pre
  9860. p p p p p p u u u u u x . . . . . .
  9861. ^ ^ ^ ^
  9862. m_content m_start | m_limit
  9863. m_cursor
  9864. @post
  9865. u u u u u x x x x x x x . . . . . .
  9866. ^ ^ ^
  9867. | m_cursor m_limit
  9868. m_start
  9869. m_content
  9870. */
  9871. void fill_line_buffer(size_t n = 0)
  9872. {
  9873. // if line buffer is used, m_content points to its data
  9874. assert(m_line_buffer.empty()
  9875. or m_content == reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()));
  9876. // if line buffer is used, m_limit is set past the end of its data
  9877. assert(m_line_buffer.empty()
  9878. or m_limit == m_content + m_line_buffer.size());
  9879. // pointer relationships
  9880. assert(m_content <= m_start);
  9881. assert(m_start <= m_cursor);
  9882. assert(m_cursor <= m_limit);
  9883. assert(m_marker == nullptr or m_marker <= m_limit);
  9884. // number of processed characters (p)
  9885. const auto num_processed_chars = static_cast<size_t>(m_start - m_content);
  9886. // offset for m_marker wrt. to m_start
  9887. const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start;
  9888. // number of unprocessed characters (u)
  9889. const auto offset_cursor = m_cursor - m_start;
  9890. // no stream is used or end of file is reached
  9891. if (m_stream == nullptr or m_stream->eof())
  9892. {
  9893. // m_start may or may not be pointing into m_line_buffer at
  9894. // this point. We trust the standard library to do the right
  9895. // thing. See http://stackoverflow.com/q/28142011/266378
  9896. m_line_buffer.assign(m_start, m_limit);
  9897. // append n characters to make sure that there is sufficient
  9898. // space between m_cursor and m_limit
  9899. m_line_buffer.append(1, '\x00');
  9900. if (n > 0)
  9901. {
  9902. m_line_buffer.append(n - 1, '\x01');
  9903. }
  9904. }
  9905. else
  9906. {
  9907. // delete processed characters from line buffer
  9908. m_line_buffer.erase(0, num_processed_chars);
  9909. // read next line from input stream
  9910. m_line_buffer_tmp.clear();
  9911. // check if stream is still good
  9912. if (m_stream->fail())
  9913. {
  9914. JSON_THROW(parse_error::create(111, 0, "bad input stream"));
  9915. }
  9916. std::getline(*m_stream, m_line_buffer_tmp, '\n');
  9917. // add line with newline symbol to the line buffer
  9918. m_line_buffer += m_line_buffer_tmp;
  9919. m_line_buffer.push_back('\n');
  9920. }
  9921. // set pointers
  9922. m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.data());
  9923. assert(m_content != nullptr);
  9924. m_start = m_content;
  9925. m_marker = m_start + offset_marker;
  9926. m_cursor = m_start + offset_cursor;
  9927. m_limit = m_start + m_line_buffer.size();
  9928. }
  9929. /// return string representation of last read token
  9930. string_t get_token_string() const
  9931. {
  9932. assert(m_start != nullptr);
  9933. return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
  9934. static_cast<size_t>(m_cursor - m_start));
  9935. }
  9936. /*!
  9937. @brief return string value for string tokens
  9938. The function iterates the characters between the opening and closing
  9939. quotes of the string value. The complete string is the range
  9940. [m_start,m_cursor). Consequently, we iterate from m_start+1 to
  9941. m_cursor-1.
  9942. We differentiate two cases:
  9943. 1. Escaped characters. In this case, a new character is constructed
  9944. according to the nature of the escape. Some escapes create new
  9945. characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied
  9946. as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape
  9947. `"\\uxxxx"` need special care. In this case, to_unicode takes care
  9948. of the construction of the values.
  9949. 2. Unescaped characters are copied as is.
  9950. @pre `m_cursor - m_start >= 2`, meaning the length of the last token
  9951. is at least 2 bytes which is trivially true for any string (which
  9952. consists of at least two quotes).
  9953. " c1 c2 c3 ... "
  9954. ^ ^
  9955. m_start m_cursor
  9956. @complexity Linear in the length of the string.\n
  9957. Lemma: The loop body will always terminate.\n
  9958. Proof (by contradiction): Assume the loop body does not terminate. As
  9959. the loop body does not contain another loop, one of the called
  9960. functions must never return. The called functions are `std::strtoul`
  9961. and to_unicode. Neither function can loop forever, so the loop body
  9962. will never loop forever which contradicts the assumption that the loop
  9963. body does not terminate, q.e.d.\n
  9964. Lemma: The loop condition for the for loop is eventually false.\n
  9965. Proof (by contradiction): Assume the loop does not terminate. Due to
  9966. the above lemma, this can only be due to a tautological loop
  9967. condition; that is, the loop condition i < m_cursor - 1 must always be
  9968. true. Let x be the change of i for any loop iteration. Then
  9969. m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This
  9970. can be rephrased to m_cursor - m_start - 2 > x. With the
  9971. precondition, we x <= 0, meaning that the loop condition holds
  9972. indefinitely if i is always decreased. However, observe that the value
  9973. of i is strictly increasing with each iteration, as it is incremented
  9974. by 1 in the iteration expression and never decremented inside the loop
  9975. body. Hence, the loop condition will eventually be false which
  9976. contradicts the assumption that the loop condition is a tautology,
  9977. q.e.d.
  9978. @return string value of current token without opening and closing
  9979. quotes
  9980. @throw parse_error.102 if to_unicode fails or surrogate error
  9981. @throw parse_error.103 if to_unicode fails
  9982. */
  9983. string_t get_string() const
  9984. {
  9985. assert(m_cursor - m_start >= 2);
  9986. string_t result;
  9987. result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
  9988. // iterate the result between the quotes
  9989. for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
  9990. {
  9991. // find next escape character
  9992. auto e = std::find(i, m_cursor - 1, '\\');
  9993. if (e != i)
  9994. {
  9995. // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705
  9996. for (auto k = i; k < e; k++)
  9997. {
  9998. result.push_back(static_cast<typename string_t::value_type>(*k));
  9999. }
  10000. i = e - 1; // -1 because of ++i
  10001. }
  10002. else
  10003. {
  10004. // processing escaped character
  10005. // read next character
  10006. ++i;
  10007. switch (*i)
  10008. {
  10009. // the default escapes
  10010. case 't':
  10011. {
  10012. result += "\t";
  10013. break;
  10014. }
  10015. case 'b':
  10016. {
  10017. result += "\b";
  10018. break;
  10019. }
  10020. case 'f':
  10021. {
  10022. result += "\f";
  10023. break;
  10024. }
  10025. case 'n':
  10026. {
  10027. result += "\n";
  10028. break;
  10029. }
  10030. case 'r':
  10031. {
  10032. result += "\r";
  10033. break;
  10034. }
  10035. case '\\':
  10036. {
  10037. result += "\\";
  10038. break;
  10039. }
  10040. case '/':
  10041. {
  10042. result += "/";
  10043. break;
  10044. }
  10045. case '"':
  10046. {
  10047. result += "\"";
  10048. break;
  10049. }
  10050. // unicode
  10051. case 'u':
  10052. {
  10053. // get code xxxx from uxxxx
  10054. auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
  10055. 4).c_str(), nullptr, 16);
  10056. // check if codepoint is a high surrogate
  10057. if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
  10058. {
  10059. // make sure there is a subsequent unicode
  10060. if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
  10061. {
  10062. JSON_THROW(parse_error::create(102, get_position(), "missing low surrogate"));
  10063. }
  10064. // get code yyyy from uxxxx\uyyyy
  10065. auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
  10066. (i + 7), 4).c_str(), nullptr, 16);
  10067. result += to_unicode(codepoint, codepoint2);
  10068. // skip the next 10 characters (xxxx\uyyyy)
  10069. i += 10;
  10070. }
  10071. else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF)
  10072. {
  10073. // we found a lone low surrogate
  10074. JSON_THROW(parse_error::create(102, get_position(), "missing high surrogate"));
  10075. }
  10076. else
  10077. {
  10078. // add unicode character(s)
  10079. result += to_unicode(codepoint);
  10080. // skip the next four characters (xxxx)
  10081. i += 4;
  10082. }
  10083. break;
  10084. }
  10085. }
  10086. }
  10087. }
  10088. return result;
  10089. }
  10090. /*!
  10091. @brief parse string into a built-in arithmetic type as if the current
  10092. locale is POSIX.
  10093. @note in floating-point case strtod may parse past the token's end -
  10094. this is not an error
  10095. @note any leading blanks are not handled
  10096. */
  10097. struct strtonum
  10098. {
  10099. public:
  10100. strtonum(const char* start, const char* end)
  10101. : m_start(start), m_end(end)
  10102. {}
  10103. /*!
  10104. @return true iff parsed successfully as number of type T
  10105. @param[in,out] val shall contain parsed value, or undefined value
  10106. if could not parse
  10107. */
  10108. template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type>
  10109. bool to(T& val) const
  10110. {
  10111. return parse(val, std::is_integral<T>());
  10112. }
  10113. private:
  10114. const char* const m_start = nullptr;
  10115. const char* const m_end = nullptr;
  10116. // floating-point conversion
  10117. // overloaded wrappers for strtod/strtof/strtold
  10118. // that will be called from parse<floating_point_t>
  10119. static void strtof(float& f, const char* str, char** endptr)
  10120. {
  10121. f = std::strtof(str, endptr);
  10122. }
  10123. static void strtof(double& f, const char* str, char** endptr)
  10124. {
  10125. f = std::strtod(str, endptr);
  10126. }
  10127. static void strtof(long double& f, const char* str, char** endptr)
  10128. {
  10129. f = std::strtold(str, endptr);
  10130. }
  10131. template<typename T>
  10132. bool parse(T& value, /*is_integral=*/std::false_type) const
  10133. {
  10134. // replace decimal separator with locale-specific version,
  10135. // when necessary; data will point to either the original
  10136. // string, or buf, or tempstr containing the fixed string.
  10137. std::string tempstr;
  10138. std::array<char, 64> buf;
  10139. const size_t len = static_cast<size_t>(m_end - m_start);
  10140. // lexer will reject empty numbers
  10141. assert(len > 0);
  10142. // since dealing with strtod family of functions, we're
  10143. // getting the decimal point char from the C locale facilities
  10144. // instead of C++'s numpunct facet of the current std::locale
  10145. const auto loc = localeconv();
  10146. assert(loc != nullptr);
  10147. const char decimal_point_char = (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0];
  10148. const char* data = m_start;
  10149. if (decimal_point_char != '.')
  10150. {
  10151. const size_t ds_pos = static_cast<size_t>(std::find(m_start, m_end, '.') - m_start);
  10152. if (ds_pos != len)
  10153. {
  10154. // copy the data into the local buffer or tempstr, if
  10155. // buffer is too small; replace decimal separator, and
  10156. // update data to point to the modified bytes
  10157. if ((len + 1) < buf.size())
  10158. {
  10159. std::copy(m_start, m_end, buf.begin());
  10160. buf[len] = 0;
  10161. buf[ds_pos] = decimal_point_char;
  10162. data = buf.data();
  10163. }
  10164. else
  10165. {
  10166. tempstr.assign(m_start, m_end);
  10167. tempstr[ds_pos] = decimal_point_char;
  10168. data = tempstr.c_str();
  10169. }
  10170. }
  10171. }
  10172. char* endptr = nullptr;
  10173. value = 0;
  10174. // this calls appropriate overload depending on T
  10175. strtof(value, data, &endptr);
  10176. // parsing was successful iff strtof parsed exactly the number
  10177. // of characters determined by the lexer (len)
  10178. const bool ok = (endptr == (data + len));
  10179. if (ok and (value == static_cast<T>(0.0)) and (*data == '-'))
  10180. {
  10181. // some implementations forget to negate the zero
  10182. value = -0.0;
  10183. }
  10184. return ok;
  10185. }
  10186. // integral conversion
  10187. signed long long parse_integral(char** endptr, /*is_signed*/std::true_type) const
  10188. {
  10189. return std::strtoll(m_start, endptr, 10);
  10190. }
  10191. unsigned long long parse_integral(char** endptr, /*is_signed*/std::false_type) const
  10192. {
  10193. return std::strtoull(m_start, endptr, 10);
  10194. }
  10195. template<typename T>
  10196. bool parse(T& value, /*is_integral=*/std::true_type) const
  10197. {
  10198. char* endptr = nullptr;
  10199. errno = 0; // these are thread-local
  10200. const auto x = parse_integral(&endptr, std::is_signed<T>());
  10201. // called right overload?
  10202. static_assert(std::is_signed<T>() == std::is_signed<decltype(x)>(), "");
  10203. value = static_cast<T>(x);
  10204. return (x == static_cast<decltype(x)>(value)) // x fits into destination T
  10205. and (x < 0) == (value < 0) // preserved sign
  10206. //and ((x != 0) or is_integral()) // strto[u]ll did nto fail
  10207. and (errno == 0) // strto[u]ll did not overflow
  10208. and (m_start < m_end) // token was not empty
  10209. and (endptr == m_end); // parsed entire token exactly
  10210. }
  10211. };
  10212. /*!
  10213. @brief return number value for number tokens
  10214. This function translates the last token into the most appropriate
  10215. number type (either integer, unsigned integer or floating point),
  10216. which is passed back to the caller via the result parameter.
  10217. integral numbers that don't fit into the the range of the respective
  10218. type are parsed as number_float_t
  10219. floating-point values do not satisfy std::isfinite predicate
  10220. are converted to value_t::null
  10221. throws if the entire string [m_start .. m_cursor) cannot be
  10222. interpreted as a number
  10223. @param[out] result @ref basic_json object to receive the number.
  10224. @param[in] token the type of the number token
  10225. */
  10226. bool get_number(basic_json& result, const token_type token) const
  10227. {
  10228. assert(m_start != nullptr);
  10229. assert(m_start < m_cursor);
  10230. assert((token == token_type::value_unsigned) or
  10231. (token == token_type::value_integer) or
  10232. (token == token_type::value_float));
  10233. strtonum num_converter(reinterpret_cast<const char*>(m_start),
  10234. reinterpret_cast<const char*>(m_cursor));
  10235. switch (token)
  10236. {
  10237. case lexer::token_type::value_unsigned:
  10238. {
  10239. number_unsigned_t val;
  10240. if (num_converter.to(val))
  10241. {
  10242. // parsing successful
  10243. result.m_type = value_t::number_unsigned;
  10244. result.m_value = val;
  10245. return true;
  10246. }
  10247. break;
  10248. }
  10249. case lexer::token_type::value_integer:
  10250. {
  10251. number_integer_t val;
  10252. if (num_converter.to(val))
  10253. {
  10254. // parsing successful
  10255. result.m_type = value_t::number_integer;
  10256. result.m_value = val;
  10257. return true;
  10258. }
  10259. break;
  10260. }
  10261. default:
  10262. {
  10263. break;
  10264. }
  10265. }
  10266. // parse float (either explicitly or because a previous conversion
  10267. // failed)
  10268. number_float_t val;
  10269. if (num_converter.to(val))
  10270. {
  10271. // parsing successful
  10272. result.m_type = value_t::number_float;
  10273. result.m_value = val;
  10274. // throw in case of infinity or NAN
  10275. if (not std::isfinite(result.m_value.number_float))
  10276. {
  10277. JSON_THROW(out_of_range::create(406, "number overflow parsing '" + get_token_string() + "'"));
  10278. }
  10279. return true;
  10280. }
  10281. // couldn't parse number in any format
  10282. return false;
  10283. }
  10284. constexpr size_t get_position() const
  10285. {
  10286. return position;
  10287. }
  10288. private:
  10289. /// optional input stream
  10290. std::istream* m_stream = nullptr;
  10291. /// line buffer buffer for m_stream
  10292. string_t m_line_buffer {};
  10293. /// used for filling m_line_buffer
  10294. string_t m_line_buffer_tmp {};
  10295. /// the buffer pointer
  10296. const lexer_char_t* m_content = nullptr;
  10297. /// pointer to the beginning of the current symbol
  10298. const lexer_char_t* m_start = nullptr;
  10299. /// pointer for backtracking information
  10300. const lexer_char_t* m_marker = nullptr;
  10301. /// pointer to the current symbol
  10302. const lexer_char_t* m_cursor = nullptr;
  10303. /// pointer to the end of the buffer
  10304. const lexer_char_t* m_limit = nullptr;
  10305. /// the last token type
  10306. token_type last_token_type = token_type::end_of_input;
  10307. /// current position in the input (read bytes)
  10308. size_t position = 0;
  10309. };
  10310. /*!
  10311. @brief syntax analysis
  10312. This class implements a recursive decent parser.
  10313. */
  10314. class parser
  10315. {
  10316. public:
  10317. /// a parser reading from a string literal
  10318. parser(const char* buff, const parser_callback_t cb = nullptr)
  10319. : callback(cb),
  10320. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff))
  10321. {}
  10322. /*!
  10323. @brief a parser reading from an input stream
  10324. @throw parse_error.111 if input stream is in a bad state
  10325. */
  10326. parser(std::istream& is, const parser_callback_t cb = nullptr)
  10327. : callback(cb), m_lexer(is)
  10328. {}
  10329. /// a parser reading from an iterator range with contiguous storage
  10330. template<class IteratorType, typename std::enable_if<
  10331. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value
  10332. , int>::type
  10333. = 0>
  10334. parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr)
  10335. : callback(cb),
  10336. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)),
  10337. static_cast<size_t>(std::distance(first, last)))
  10338. {}
  10339. /*!
  10340. @brief public parser interface
  10341. @throw parse_error.101 in case of an unexpected token
  10342. @throw parse_error.102 if to_unicode fails or surrogate error
  10343. @throw parse_error.103 if to_unicode fails
  10344. */
  10345. basic_json parse()
  10346. {
  10347. // read first token
  10348. get_token();
  10349. basic_json result = parse_internal(true);
  10350. result.assert_invariant();
  10351. expect(lexer::token_type::end_of_input);
  10352. // return parser result and replace it with null in case the
  10353. // top-level value was discarded by the callback function
  10354. return result.is_discarded() ? basic_json() : std::move(result);
  10355. }
  10356. private:
  10357. /*!
  10358. @brief the actual parser
  10359. @throw parse_error.101 in case of an unexpected token
  10360. @throw parse_error.102 if to_unicode fails or surrogate error
  10361. @throw parse_error.103 if to_unicode fails
  10362. */
  10363. basic_json parse_internal(bool keep)
  10364. {
  10365. auto result = basic_json(value_t::discarded);
  10366. switch (last_token)
  10367. {
  10368. case lexer::token_type::begin_object:
  10369. {
  10370. if (keep and (not callback
  10371. or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0)))
  10372. {
  10373. // explicitly set result to object to cope with {}
  10374. result.m_type = value_t::object;
  10375. result.m_value = value_t::object;
  10376. }
  10377. // read next token
  10378. get_token();
  10379. // closing } -> we are done
  10380. if (last_token == lexer::token_type::end_object)
  10381. {
  10382. get_token();
  10383. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  10384. {
  10385. result = basic_json(value_t::discarded);
  10386. }
  10387. return result;
  10388. }
  10389. // no comma is expected here
  10390. unexpect(lexer::token_type::value_separator);
  10391. // otherwise: parse key-value pairs
  10392. do
  10393. {
  10394. // ugly, but could be fixed with loop reorganization
  10395. if (last_token == lexer::token_type::value_separator)
  10396. {
  10397. get_token();
  10398. }
  10399. // store key
  10400. expect(lexer::token_type::value_string);
  10401. const auto key = m_lexer.get_string();
  10402. bool keep_tag = false;
  10403. if (keep)
  10404. {
  10405. if (callback)
  10406. {
  10407. basic_json k(key);
  10408. keep_tag = callback(depth, parse_event_t::key, k);
  10409. }
  10410. else
  10411. {
  10412. keep_tag = true;
  10413. }
  10414. }
  10415. // parse separator (:)
  10416. get_token();
  10417. expect(lexer::token_type::name_separator);
  10418. // parse and add value
  10419. get_token();
  10420. auto value = parse_internal(keep);
  10421. if (keep and keep_tag and not value.is_discarded())
  10422. {
  10423. result[key] = std::move(value);
  10424. }
  10425. }
  10426. while (last_token == lexer::token_type::value_separator);
  10427. // closing }
  10428. expect(lexer::token_type::end_object);
  10429. get_token();
  10430. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  10431. {
  10432. result = basic_json(value_t::discarded);
  10433. }
  10434. return result;
  10435. }
  10436. case lexer::token_type::begin_array:
  10437. {
  10438. if (keep and (not callback
  10439. or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0)))
  10440. {
  10441. // explicitly set result to object to cope with []
  10442. result.m_type = value_t::array;
  10443. result.m_value = value_t::array;
  10444. }
  10445. // read next token
  10446. get_token();
  10447. // closing ] -> we are done
  10448. if (last_token == lexer::token_type::end_array)
  10449. {
  10450. get_token();
  10451. if (callback and not callback(--depth, parse_event_t::array_end, result))
  10452. {
  10453. result = basic_json(value_t::discarded);
  10454. }
  10455. return result;
  10456. }
  10457. // no comma is expected here
  10458. unexpect(lexer::token_type::value_separator);
  10459. // otherwise: parse values
  10460. do
  10461. {
  10462. // ugly, but could be fixed with loop reorganization
  10463. if (last_token == lexer::token_type::value_separator)
  10464. {
  10465. get_token();
  10466. }
  10467. // parse value
  10468. auto value = parse_internal(keep);
  10469. if (keep and not value.is_discarded())
  10470. {
  10471. result.push_back(std::move(value));
  10472. }
  10473. }
  10474. while (last_token == lexer::token_type::value_separator);
  10475. // closing ]
  10476. expect(lexer::token_type::end_array);
  10477. get_token();
  10478. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  10479. {
  10480. result = basic_json(value_t::discarded);
  10481. }
  10482. return result;
  10483. }
  10484. case lexer::token_type::literal_null:
  10485. {
  10486. get_token();
  10487. result.m_type = value_t::null;
  10488. break;
  10489. }
  10490. case lexer::token_type::value_string:
  10491. {
  10492. const auto s = m_lexer.get_string();
  10493. get_token();
  10494. result = basic_json(s);
  10495. break;
  10496. }
  10497. case lexer::token_type::literal_true:
  10498. {
  10499. get_token();
  10500. result.m_type = value_t::boolean;
  10501. result.m_value = true;
  10502. break;
  10503. }
  10504. case lexer::token_type::literal_false:
  10505. {
  10506. get_token();
  10507. result.m_type = value_t::boolean;
  10508. result.m_value = false;
  10509. break;
  10510. }
  10511. case lexer::token_type::value_unsigned:
  10512. case lexer::token_type::value_integer:
  10513. case lexer::token_type::value_float:
  10514. {
  10515. m_lexer.get_number(result, last_token);
  10516. get_token();
  10517. break;
  10518. }
  10519. default:
  10520. {
  10521. // the last token was unexpected
  10522. unexpect(last_token);
  10523. }
  10524. }
  10525. if (keep and callback and not callback(depth, parse_event_t::value, result))
  10526. {
  10527. result = basic_json(value_t::discarded);
  10528. }
  10529. return result;
  10530. }
  10531. /// get next token from lexer
  10532. typename lexer::token_type get_token()
  10533. {
  10534. last_token = m_lexer.scan();
  10535. return last_token;
  10536. }
  10537. /*!
  10538. @throw parse_error.101 if expected token did not occur
  10539. */
  10540. void expect(typename lexer::token_type t) const
  10541. {
  10542. if (t != last_token)
  10543. {
  10544. std::string error_msg = "parse error - unexpected ";
  10545. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  10546. "'") :
  10547. lexer::token_type_name(last_token));
  10548. error_msg += "; expected " + lexer::token_type_name(t);
  10549. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  10550. }
  10551. }
  10552. /*!
  10553. @throw parse_error.101 if unexpected token occurred
  10554. */
  10555. void unexpect(typename lexer::token_type t) const
  10556. {
  10557. if (t == last_token)
  10558. {
  10559. std::string error_msg = "parse error - unexpected ";
  10560. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  10561. "'") :
  10562. lexer::token_type_name(last_token));
  10563. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  10564. }
  10565. }
  10566. private:
  10567. /// current level of recursion
  10568. int depth = 0;
  10569. /// callback function
  10570. const parser_callback_t callback = nullptr;
  10571. /// the type of the last read token
  10572. typename lexer::token_type last_token = lexer::token_type::uninitialized;
  10573. /// the lexer
  10574. lexer m_lexer;
  10575. };
  10576. public:
  10577. /*!
  10578. @brief JSON Pointer
  10579. A JSON pointer defines a string syntax for identifying a specific value
  10580. within a JSON document. It can be used with functions `at` and
  10581. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  10582. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  10583. @since version 2.0.0
  10584. */
  10585. class json_pointer
  10586. {
  10587. /// allow basic_json to access private members
  10588. friend class basic_json;
  10589. public:
  10590. /*!
  10591. @brief create JSON pointer
  10592. Create a JSON pointer according to the syntax described in
  10593. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  10594. @param[in] s string representing the JSON pointer; if omitted, the
  10595. empty string is assumed which references the whole JSON
  10596. value
  10597. @throw parse_error.107 if the given JSON pointer @a s is nonempty and
  10598. does not begin with a slash (`/`); see example below
  10599. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
  10600. is not followed by `0` (representing `~`) or `1` (representing `/`);
  10601. see example below
  10602. @liveexample{The example shows the construction several valid JSON
  10603. pointers as well as the exceptional behavior.,json_pointer}
  10604. @since version 2.0.0
  10605. */
  10606. explicit json_pointer(const std::string& s = "")
  10607. : reference_tokens(split(s))
  10608. {}
  10609. /*!
  10610. @brief return a string representation of the JSON pointer
  10611. @invariant For each JSON pointer `ptr`, it holds:
  10612. @code {.cpp}
  10613. ptr == json_pointer(ptr.to_string());
  10614. @endcode
  10615. @return a string representation of the JSON pointer
  10616. @liveexample{The example shows the result of `to_string`.,
  10617. json_pointer__to_string}
  10618. @since version 2.0.0
  10619. */
  10620. std::string to_string() const noexcept
  10621. {
  10622. return std::accumulate(reference_tokens.begin(),
  10623. reference_tokens.end(), std::string{},
  10624. [](const std::string & a, const std::string & b)
  10625. {
  10626. return a + "/" + escape(b);
  10627. });
  10628. }
  10629. /// @copydoc to_string()
  10630. operator std::string() const
  10631. {
  10632. return to_string();
  10633. }
  10634. private:
  10635. /*!
  10636. @brief remove and return last reference pointer
  10637. @throw out_of_range.405 if JSON pointer has no parent
  10638. */
  10639. std::string pop_back()
  10640. {
  10641. if (is_root())
  10642. {
  10643. JSON_THROW(out_of_range::create(405, "JSON pointer has no parent"));
  10644. }
  10645. auto last = reference_tokens.back();
  10646. reference_tokens.pop_back();
  10647. return last;
  10648. }
  10649. /// return whether pointer points to the root document
  10650. bool is_root() const
  10651. {
  10652. return reference_tokens.empty();
  10653. }
  10654. json_pointer top() const
  10655. {
  10656. if (is_root())
  10657. {
  10658. JSON_THROW(out_of_range::create(405, "JSON pointer has no parent"));
  10659. }
  10660. json_pointer result = *this;
  10661. result.reference_tokens = {reference_tokens[0]};
  10662. return result;
  10663. }
  10664. /*!
  10665. @brief create and return a reference to the pointed to value
  10666. @complexity Linear in the number of reference tokens.
  10667. @throw parse_error.109 if array index is not a number
  10668. @throw type_error.313 if value cannot be unflattened
  10669. */
  10670. reference get_and_create(reference j) const
  10671. {
  10672. pointer result = &j;
  10673. // in case no reference tokens exist, return a reference to the
  10674. // JSON value j which will be overwritten by a primitive value
  10675. for (const auto& reference_token : reference_tokens)
  10676. {
  10677. switch (result->m_type)
  10678. {
  10679. case value_t::null:
  10680. {
  10681. if (reference_token == "0")
  10682. {
  10683. // start a new array if reference token is 0
  10684. result = &result->operator[](0);
  10685. }
  10686. else
  10687. {
  10688. // start a new object otherwise
  10689. result = &result->operator[](reference_token);
  10690. }
  10691. break;
  10692. }
  10693. case value_t::object:
  10694. {
  10695. // create an entry in the object
  10696. result = &result->operator[](reference_token);
  10697. break;
  10698. }
  10699. case value_t::array:
  10700. {
  10701. // create an entry in the array
  10702. JSON_TRY
  10703. {
  10704. result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
  10705. }
  10706. JSON_CATCH (std::invalid_argument&)
  10707. {
  10708. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10709. }
  10710. break;
  10711. }
  10712. /*
  10713. The following code is only reached if there exists a
  10714. reference token _and_ the current value is primitive. In
  10715. this case, we have an error situation, because primitive
  10716. values may only occur as single value; that is, with an
  10717. empty list of reference tokens.
  10718. */
  10719. default:
  10720. {
  10721. JSON_THROW(type_error::create(313, "invalid value to unflatten"));
  10722. }
  10723. }
  10724. }
  10725. return *result;
  10726. }
  10727. /*!
  10728. @brief return a reference to the pointed to value
  10729. @note This version does not throw if a value is not present, but tries
  10730. to create nested values instead. For instance, calling this function
  10731. with pointer `"/this/that"` on a null value is equivalent to calling
  10732. `operator[]("this").operator[]("that")` on that value, effectively
  10733. changing the null value to an object.
  10734. @param[in] ptr a JSON value
  10735. @return reference to the JSON value pointed to by the JSON pointer
  10736. @complexity Linear in the length of the JSON pointer.
  10737. @throw parse_error.106 if an array index begins with '0'
  10738. @throw parse_error.109 if an array index was not a number
  10739. @throw out_of_range.404 if the JSON pointer can not be resolved
  10740. */
  10741. reference get_unchecked(pointer ptr) const
  10742. {
  10743. for (const auto& reference_token : reference_tokens)
  10744. {
  10745. // convert null values to arrays or objects before continuing
  10746. if (ptr->m_type == value_t::null)
  10747. {
  10748. // check if reference token is a number
  10749. const bool nums = std::all_of(reference_token.begin(),
  10750. reference_token.end(),
  10751. [](const char x)
  10752. {
  10753. return (x >= '0' and x <= '9');
  10754. });
  10755. // change value to array for numbers or "-" or to object
  10756. // otherwise
  10757. if (nums or reference_token == "-")
  10758. {
  10759. *ptr = value_t::array;
  10760. }
  10761. else
  10762. {
  10763. *ptr = value_t::object;
  10764. }
  10765. }
  10766. switch (ptr->m_type)
  10767. {
  10768. case value_t::object:
  10769. {
  10770. // use unchecked object access
  10771. ptr = &ptr->operator[](reference_token);
  10772. break;
  10773. }
  10774. case value_t::array:
  10775. {
  10776. // error condition (cf. RFC 6901, Sect. 4)
  10777. if (reference_token.size() > 1 and reference_token[0] == '0')
  10778. {
  10779. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  10780. }
  10781. if (reference_token == "-")
  10782. {
  10783. // explicitly treat "-" as index beyond the end
  10784. ptr = &ptr->operator[](ptr->m_value.array->size());
  10785. }
  10786. else
  10787. {
  10788. // convert array index to number; unchecked access
  10789. JSON_TRY
  10790. {
  10791. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  10792. }
  10793. JSON_CATCH (std::invalid_argument&)
  10794. {
  10795. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10796. }
  10797. }
  10798. break;
  10799. }
  10800. default:
  10801. {
  10802. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10803. }
  10804. }
  10805. }
  10806. return *ptr;
  10807. }
  10808. /*!
  10809. @throw parse_error.106 if an array index begins with '0'
  10810. @throw parse_error.109 if an array index was not a number
  10811. @throw out_of_range.402 if the array index '-' is used
  10812. @throw out_of_range.404 if the JSON pointer can not be resolved
  10813. */
  10814. reference get_checked(pointer ptr) const
  10815. {
  10816. for (const auto& reference_token : reference_tokens)
  10817. {
  10818. switch (ptr->m_type)
  10819. {
  10820. case value_t::object:
  10821. {
  10822. // note: at performs range check
  10823. ptr = &ptr->at(reference_token);
  10824. break;
  10825. }
  10826. case value_t::array:
  10827. {
  10828. if (reference_token == "-")
  10829. {
  10830. // "-" always fails the range check
  10831. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  10832. std::to_string(ptr->m_value.array->size()) +
  10833. ") is out of range"));
  10834. }
  10835. // error condition (cf. RFC 6901, Sect. 4)
  10836. if (reference_token.size() > 1 and reference_token[0] == '0')
  10837. {
  10838. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  10839. }
  10840. // note: at performs range check
  10841. JSON_TRY
  10842. {
  10843. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  10844. }
  10845. JSON_CATCH (std::invalid_argument&)
  10846. {
  10847. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10848. }
  10849. break;
  10850. }
  10851. default:
  10852. {
  10853. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10854. }
  10855. }
  10856. }
  10857. return *ptr;
  10858. }
  10859. /*!
  10860. @brief return a const reference to the pointed to value
  10861. @param[in] ptr a JSON value
  10862. @return const reference to the JSON value pointed to by the JSON
  10863. pointer
  10864. @throw parse_error.106 if an array index begins with '0'
  10865. @throw parse_error.109 if an array index was not a number
  10866. @throw out_of_range.402 if the array index '-' is used
  10867. @throw out_of_range.404 if the JSON pointer can not be resolved
  10868. */
  10869. const_reference get_unchecked(const_pointer ptr) const
  10870. {
  10871. for (const auto& reference_token : reference_tokens)
  10872. {
  10873. switch (ptr->m_type)
  10874. {
  10875. case value_t::object:
  10876. {
  10877. // use unchecked object access
  10878. ptr = &ptr->operator[](reference_token);
  10879. break;
  10880. }
  10881. case value_t::array:
  10882. {
  10883. if (reference_token == "-")
  10884. {
  10885. // "-" cannot be used for const access
  10886. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  10887. std::to_string(ptr->m_value.array->size()) +
  10888. ") is out of range"));
  10889. }
  10890. // error condition (cf. RFC 6901, Sect. 4)
  10891. if (reference_token.size() > 1 and reference_token[0] == '0')
  10892. {
  10893. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  10894. }
  10895. // use unchecked array access
  10896. JSON_TRY
  10897. {
  10898. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  10899. }
  10900. JSON_CATCH (std::invalid_argument&)
  10901. {
  10902. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10903. }
  10904. break;
  10905. }
  10906. default:
  10907. {
  10908. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10909. }
  10910. }
  10911. }
  10912. return *ptr;
  10913. }
  10914. /*!
  10915. @throw parse_error.106 if an array index begins with '0'
  10916. @throw parse_error.109 if an array index was not a number
  10917. @throw out_of_range.402 if the array index '-' is used
  10918. @throw out_of_range.404 if the JSON pointer can not be resolved
  10919. */
  10920. const_reference get_checked(const_pointer ptr) const
  10921. {
  10922. for (const auto& reference_token : reference_tokens)
  10923. {
  10924. switch (ptr->m_type)
  10925. {
  10926. case value_t::object:
  10927. {
  10928. // note: at performs range check
  10929. ptr = &ptr->at(reference_token);
  10930. break;
  10931. }
  10932. case value_t::array:
  10933. {
  10934. if (reference_token == "-")
  10935. {
  10936. // "-" always fails the range check
  10937. JSON_THROW(out_of_range::create(402, "array index '-' (" +
  10938. std::to_string(ptr->m_value.array->size()) +
  10939. ") is out of range"));
  10940. }
  10941. // error condition (cf. RFC 6901, Sect. 4)
  10942. if (reference_token.size() > 1 and reference_token[0] == '0')
  10943. {
  10944. JSON_THROW(parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'"));
  10945. }
  10946. // note: at performs range check
  10947. JSON_TRY
  10948. {
  10949. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  10950. }
  10951. JSON_CATCH (std::invalid_argument&)
  10952. {
  10953. JSON_THROW(parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  10954. }
  10955. break;
  10956. }
  10957. default:
  10958. {
  10959. JSON_THROW(out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  10960. }
  10961. }
  10962. }
  10963. return *ptr;
  10964. }
  10965. /*!
  10966. @brief split the string input to reference tokens
  10967. @note This function is only called by the json_pointer constructor.
  10968. All exceptions below are documented there.
  10969. @throw parse_error.107 if the pointer is not empty or begins with '/'
  10970. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  10971. */
  10972. static std::vector<std::string> split(const std::string& reference_string)
  10973. {
  10974. std::vector<std::string> result;
  10975. // special case: empty reference string -> no reference tokens
  10976. if (reference_string.empty())
  10977. {
  10978. return result;
  10979. }
  10980. // check if nonempty reference string begins with slash
  10981. if (reference_string[0] != '/')
  10982. {
  10983. JSON_THROW(parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'"));
  10984. }
  10985. // extract the reference tokens:
  10986. // - slash: position of the last read slash (or end of string)
  10987. // - start: position after the previous slash
  10988. for (
  10989. // search for the first slash after the first character
  10990. size_t slash = reference_string.find_first_of('/', 1),
  10991. // set the beginning of the first reference token
  10992. start = 1;
  10993. // we can stop if start == string::npos+1 = 0
  10994. start != 0;
  10995. // set the beginning of the next reference token
  10996. // (will eventually be 0 if slash == std::string::npos)
  10997. start = slash + 1,
  10998. // find next slash
  10999. slash = reference_string.find_first_of('/', start))
  11000. {
  11001. // use the text between the beginning of the reference token
  11002. // (start) and the last slash (slash).
  11003. auto reference_token = reference_string.substr(start, slash - start);
  11004. // check reference tokens are properly escaped
  11005. for (size_t pos = reference_token.find_first_of('~');
  11006. pos != std::string::npos;
  11007. pos = reference_token.find_first_of('~', pos + 1))
  11008. {
  11009. assert(reference_token[pos] == '~');
  11010. // ~ must be followed by 0 or 1
  11011. if (pos == reference_token.size() - 1 or
  11012. (reference_token[pos + 1] != '0' and
  11013. reference_token[pos + 1] != '1'))
  11014. {
  11015. JSON_THROW(parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  11016. }
  11017. }
  11018. // finally, store the reference token
  11019. unescape(reference_token);
  11020. result.push_back(reference_token);
  11021. }
  11022. return result;
  11023. }
  11024. /*!
  11025. @brief replace all occurrences of a substring by another string
  11026. @param[in,out] s the string to manipulate; changed so that all
  11027. occurrences of @a f are replaced with @a t
  11028. @param[in] f the substring to replace with @a t
  11029. @param[in] t the string to replace @a f
  11030. @pre The search string @a f must not be empty. **This precondition is
  11031. enforced with an assertion.**
  11032. @since version 2.0.0
  11033. */
  11034. static void replace_substring(std::string& s,
  11035. const std::string& f,
  11036. const std::string& t)
  11037. {
  11038. assert(not f.empty());
  11039. for (
  11040. size_t pos = s.find(f); // find first occurrence of f
  11041. pos != std::string::npos; // make sure f was found
  11042. s.replace(pos, f.size(), t), // replace with t
  11043. pos = s.find(f, pos + t.size()) // find next occurrence of f
  11044. );
  11045. }
  11046. /// escape tilde and slash
  11047. static std::string escape(std::string s)
  11048. {
  11049. // escape "~"" to "~0" and "/" to "~1"
  11050. replace_substring(s, "~", "~0");
  11051. replace_substring(s, "/", "~1");
  11052. return s;
  11053. }
  11054. /// unescape tilde and slash
  11055. static void unescape(std::string& s)
  11056. {
  11057. // first transform any occurrence of the sequence '~1' to '/'
  11058. replace_substring(s, "~1", "/");
  11059. // then transform any occurrence of the sequence '~0' to '~'
  11060. replace_substring(s, "~0", "~");
  11061. }
  11062. /*!
  11063. @param[in] reference_string the reference string to the current value
  11064. @param[in] value the value to consider
  11065. @param[in,out] result the result object to insert values to
  11066. @note Empty objects or arrays are flattened to `null`.
  11067. */
  11068. static void flatten(const std::string& reference_string,
  11069. const basic_json& value,
  11070. basic_json& result)
  11071. {
  11072. switch (value.m_type)
  11073. {
  11074. case value_t::array:
  11075. {
  11076. if (value.m_value.array->empty())
  11077. {
  11078. // flatten empty array as null
  11079. result[reference_string] = nullptr;
  11080. }
  11081. else
  11082. {
  11083. // iterate array and use index as reference string
  11084. for (size_t i = 0; i < value.m_value.array->size(); ++i)
  11085. {
  11086. flatten(reference_string + "/" + std::to_string(i),
  11087. value.m_value.array->operator[](i), result);
  11088. }
  11089. }
  11090. break;
  11091. }
  11092. case value_t::object:
  11093. {
  11094. if (value.m_value.object->empty())
  11095. {
  11096. // flatten empty object as null
  11097. result[reference_string] = nullptr;
  11098. }
  11099. else
  11100. {
  11101. // iterate object and use keys as reference string
  11102. for (const auto& element : *value.m_value.object)
  11103. {
  11104. flatten(reference_string + "/" + escape(element.first),
  11105. element.second, result);
  11106. }
  11107. }
  11108. break;
  11109. }
  11110. default:
  11111. {
  11112. // add primitive value with its reference string
  11113. result[reference_string] = value;
  11114. break;
  11115. }
  11116. }
  11117. }
  11118. /*!
  11119. @param[in] value flattened JSON
  11120. @return unflattened JSON
  11121. @throw parse_error.109 if array index is not a number
  11122. @throw type_error.314 if value is not an object
  11123. @throw type_error.315 if object values are not primitive
  11124. @throw type_error.313 if value cannot be unflattened
  11125. */
  11126. static basic_json unflatten(const basic_json& value)
  11127. {
  11128. if (not value.is_object())
  11129. {
  11130. JSON_THROW(type_error::create(314, "only objects can be unflattened"));
  11131. }
  11132. basic_json result;
  11133. // iterate the JSON object values
  11134. for (const auto& element : *value.m_value.object)
  11135. {
  11136. if (not element.second.is_primitive())
  11137. {
  11138. JSON_THROW(type_error::create(315, "values in object must be primitive"));
  11139. }
  11140. // assign value to reference pointed to by JSON pointer; Note
  11141. // that if the JSON pointer is "" (i.e., points to the whole
  11142. // value), function get_and_create returns a reference to
  11143. // result itself. An assignment will then create a primitive
  11144. // value.
  11145. json_pointer(element.first).get_and_create(result) = element.second;
  11146. }
  11147. return result;
  11148. }
  11149. friend bool operator==(json_pointer const& lhs,
  11150. json_pointer const& rhs) noexcept
  11151. {
  11152. return lhs.reference_tokens == rhs.reference_tokens;
  11153. }
  11154. friend bool operator!=(json_pointer const& lhs,
  11155. json_pointer const& rhs) noexcept
  11156. {
  11157. return !(lhs == rhs);
  11158. }
  11159. /// the reference tokens
  11160. std::vector<std::string> reference_tokens {};
  11161. };
  11162. //////////////////////////
  11163. // JSON Pointer support //
  11164. //////////////////////////
  11165. /// @name JSON Pointer functions
  11166. /// @{
  11167. /*!
  11168. @brief access specified element via JSON Pointer
  11169. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11170. No bound checking is performed. Similar to @ref operator[](const typename
  11171. object_t::key_type&), `null` values are created in arrays and objects if
  11172. necessary.
  11173. In particular:
  11174. - If the JSON pointer points to an object key that does not exist, it
  11175. is created an filled with a `null` value before a reference to it
  11176. is returned.
  11177. - If the JSON pointer points to an array index that does not exist, it
  11178. is created an filled with a `null` value before a reference to it
  11179. is returned. All indices between the current maximum and the given
  11180. index are also filled with `null`.
  11181. - The special value `-` is treated as a synonym for the index past the
  11182. end.
  11183. @param[in] ptr a JSON pointer
  11184. @return reference to the element pointed to by @a ptr
  11185. @complexity Constant.
  11186. @throw parse_error.106 if an array index begins with '0'
  11187. @throw parse_error.109 if an array index was not a number
  11188. @throw out_of_range.404 if the JSON pointer can not be resolved
  11189. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  11190. @since version 2.0.0
  11191. */
  11192. reference operator[](const json_pointer& ptr)
  11193. {
  11194. return ptr.get_unchecked(this);
  11195. }
  11196. /*!
  11197. @brief access specified element via JSON Pointer
  11198. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11199. No bound checking is performed. The function does not change the JSON
  11200. value; no `null` values are created. In particular, the the special value
  11201. `-` yields an exception.
  11202. @param[in] ptr JSON pointer to the desired element
  11203. @return const reference to the element pointed to by @a ptr
  11204. @complexity Constant.
  11205. @throw parse_error.106 if an array index begins with '0'
  11206. @throw parse_error.109 if an array index was not a number
  11207. @throw out_of_range.402 if the array index '-' is used
  11208. @throw out_of_range.404 if the JSON pointer can not be resolved
  11209. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  11210. @since version 2.0.0
  11211. */
  11212. const_reference operator[](const json_pointer& ptr) const
  11213. {
  11214. return ptr.get_unchecked(this);
  11215. }
  11216. /*!
  11217. @brief access specified element via JSON Pointer
  11218. Returns a reference to the element at with specified JSON pointer @a ptr,
  11219. with bounds checking.
  11220. @param[in] ptr JSON pointer to the desired element
  11221. @return reference to the element pointed to by @a ptr
  11222. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11223. begins with '0'. See example below.
  11224. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11225. is not a number. See example below.
  11226. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11227. is out of range. See example below.
  11228. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11229. pointer @a ptr. As `at` provides checked access (and no elements are
  11230. implicitly inserted), the index '-' is always invalid. See example below.
  11231. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11232. See example below.
  11233. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11234. changes in the JSON value.
  11235. @complexity Constant.
  11236. @since version 2.0.0
  11237. @liveexample{The behavior is shown in the example.,at_json_pointer}
  11238. */
  11239. reference at(const json_pointer& ptr)
  11240. {
  11241. return ptr.get_checked(this);
  11242. }
  11243. /*!
  11244. @brief access specified element via JSON Pointer
  11245. Returns a const reference to the element at with specified JSON pointer @a
  11246. ptr, with bounds checking.
  11247. @param[in] ptr JSON pointer to the desired element
  11248. @return reference to the element pointed to by @a ptr
  11249. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11250. begins with '0'. See example below.
  11251. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11252. is not a number. See example below.
  11253. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11254. is out of range. See example below.
  11255. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11256. pointer @a ptr. As `at` provides checked access (and no elements are
  11257. implicitly inserted), the index '-' is always invalid. See example below.
  11258. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11259. See example below.
  11260. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11261. changes in the JSON value.
  11262. @complexity Constant.
  11263. @since version 2.0.0
  11264. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  11265. */
  11266. const_reference at(const json_pointer& ptr) const
  11267. {
  11268. return ptr.get_checked(this);
  11269. }
  11270. /*!
  11271. @brief return flattened JSON value
  11272. The function creates a JSON object whose keys are JSON pointers (see [RFC
  11273. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  11274. primitive. The original JSON value can be restored using the @ref
  11275. unflatten() function.
  11276. @return an object that maps JSON pointers to primitive values
  11277. @note Empty objects and arrays are flattened to `null` and will not be
  11278. reconstructed correctly by the @ref unflatten() function.
  11279. @complexity Linear in the size the JSON value.
  11280. @liveexample{The following code shows how a JSON object is flattened to an
  11281. object whose keys consist of JSON pointers.,flatten}
  11282. @sa @ref unflatten() for the reverse function
  11283. @since version 2.0.0
  11284. */
  11285. basic_json flatten() const
  11286. {
  11287. basic_json result(value_t::object);
  11288. json_pointer::flatten("", *this, result);
  11289. return result;
  11290. }
  11291. /*!
  11292. @brief unflatten a previously flattened JSON value
  11293. The function restores the arbitrary nesting of a JSON value that has been
  11294. flattened before using the @ref flatten() function. The JSON value must
  11295. meet certain constraints:
  11296. 1. The value must be an object.
  11297. 2. The keys must be JSON pointers (see
  11298. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  11299. 3. The mapped values must be primitive JSON types.
  11300. @return the original JSON from a flattened version
  11301. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  11302. values and can not unflattened to their original type. Apart from
  11303. this example, for a JSON value `j`, the following is always true:
  11304. `j == j.flatten().unflatten()`.
  11305. @complexity Linear in the size the JSON value.
  11306. @throw type_error.314 if value is not an object
  11307. @throw type_error.315 if object values are not primitve
  11308. @liveexample{The following code shows how a flattened JSON object is
  11309. unflattened into the original nested JSON object.,unflatten}
  11310. @sa @ref flatten() for the reverse function
  11311. @since version 2.0.0
  11312. */
  11313. basic_json unflatten() const
  11314. {
  11315. return json_pointer::unflatten(*this);
  11316. }
  11317. /// @}
  11318. //////////////////////////
  11319. // JSON Patch functions //
  11320. //////////////////////////
  11321. /// @name JSON Patch functions
  11322. /// @{
  11323. /*!
  11324. @brief applies a JSON patch
  11325. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  11326. expressing a sequence of operations to apply to a JSON) document. With
  11327. this function, a JSON Patch is applied to the current JSON value by
  11328. executing all operations from the patch.
  11329. @param[in] json_patch JSON patch document
  11330. @return patched document
  11331. @note The application of a patch is atomic: Either all operations succeed
  11332. and the patched document is returned or an exception is thrown. In
  11333. any case, the original value is not changed: the patch is applied
  11334. to a copy of the value.
  11335. @throw parse_error.104 if the JSON patch does not consist of an array of
  11336. objects
  11337. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  11338. attributes are missing); example: `"operation add must have member path"`
  11339. @throw out_of_range.401 if an array index is out of range.
  11340. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  11341. resolved successfully in the current JSON value; example: `"key baz not
  11342. found"`
  11343. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  11344. "move")
  11345. @throw other_error.501 if "test" operation was unsuccessful
  11346. @complexity Linear in the size of the JSON value and the length of the
  11347. JSON patch. As usually only a fraction of the JSON value is affected by
  11348. the patch, the complexity can usually be neglected.
  11349. @liveexample{The following code shows how a JSON patch is applied to a
  11350. value.,patch}
  11351. @sa @ref diff -- create a JSON patch by comparing two JSON values
  11352. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11353. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  11354. @since version 2.0.0
  11355. */
  11356. basic_json patch(const basic_json& json_patch) const
  11357. {
  11358. // make a working copy to apply the patch to
  11359. basic_json result = *this;
  11360. // the valid JSON Patch operations
  11361. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  11362. const auto get_op = [](const std::string & op)
  11363. {
  11364. if (op == "add")
  11365. {
  11366. return patch_operations::add;
  11367. }
  11368. if (op == "remove")
  11369. {
  11370. return patch_operations::remove;
  11371. }
  11372. if (op == "replace")
  11373. {
  11374. return patch_operations::replace;
  11375. }
  11376. if (op == "move")
  11377. {
  11378. return patch_operations::move;
  11379. }
  11380. if (op == "copy")
  11381. {
  11382. return patch_operations::copy;
  11383. }
  11384. if (op == "test")
  11385. {
  11386. return patch_operations::test;
  11387. }
  11388. return patch_operations::invalid;
  11389. };
  11390. // wrapper for "add" operation; add value at ptr
  11391. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  11392. {
  11393. // adding to the root of the target document means replacing it
  11394. if (ptr.is_root())
  11395. {
  11396. result = val;
  11397. }
  11398. else
  11399. {
  11400. // make sure the top element of the pointer exists
  11401. json_pointer top_pointer = ptr.top();
  11402. if (top_pointer != ptr)
  11403. {
  11404. result.at(top_pointer);
  11405. }
  11406. // get reference to parent of JSON pointer ptr
  11407. const auto last_path = ptr.pop_back();
  11408. basic_json& parent = result[ptr];
  11409. switch (parent.m_type)
  11410. {
  11411. case value_t::null:
  11412. case value_t::object:
  11413. {
  11414. // use operator[] to add value
  11415. parent[last_path] = val;
  11416. break;
  11417. }
  11418. case value_t::array:
  11419. {
  11420. if (last_path == "-")
  11421. {
  11422. // special case: append to back
  11423. parent.push_back(val);
  11424. }
  11425. else
  11426. {
  11427. const auto idx = std::stoi(last_path);
  11428. if (static_cast<size_type>(idx) > parent.size())
  11429. {
  11430. // avoid undefined behavior
  11431. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11432. }
  11433. else
  11434. {
  11435. // default case: insert add offset
  11436. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  11437. }
  11438. }
  11439. break;
  11440. }
  11441. default:
  11442. {
  11443. // if there exists a parent it cannot be primitive
  11444. assert(false); // LCOV_EXCL_LINE
  11445. }
  11446. }
  11447. }
  11448. };
  11449. // wrapper for "remove" operation; remove value at ptr
  11450. const auto operation_remove = [&result](json_pointer & ptr)
  11451. {
  11452. // get reference to parent of JSON pointer ptr
  11453. const auto last_path = ptr.pop_back();
  11454. basic_json& parent = result.at(ptr);
  11455. // remove child
  11456. if (parent.is_object())
  11457. {
  11458. // perform range check
  11459. auto it = parent.find(last_path);
  11460. if (it != parent.end())
  11461. {
  11462. parent.erase(it);
  11463. }
  11464. else
  11465. {
  11466. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  11467. }
  11468. }
  11469. else if (parent.is_array())
  11470. {
  11471. // note erase performs range check
  11472. parent.erase(static_cast<size_type>(std::stoi(last_path)));
  11473. }
  11474. };
  11475. // type check: top level value must be an array
  11476. if (not json_patch.is_array())
  11477. {
  11478. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11479. }
  11480. // iterate and apply the operations
  11481. for (const auto& val : json_patch)
  11482. {
  11483. // wrapper to get a value for an operation
  11484. const auto get_value = [&val](const std::string & op,
  11485. const std::string & member,
  11486. bool string_type) -> basic_json&
  11487. {
  11488. // find value
  11489. auto it = val.m_value.object->find(member);
  11490. // context-sensitive error message
  11491. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  11492. // check if desired value is present
  11493. if (it == val.m_value.object->end())
  11494. {
  11495. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  11496. }
  11497. // check if result is of type string
  11498. if (string_type and not it->second.is_string())
  11499. {
  11500. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  11501. }
  11502. // no error: return value
  11503. return it->second;
  11504. };
  11505. // type check: every element of the array must be an object
  11506. if (not val.is_object())
  11507. {
  11508. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11509. }
  11510. // collect mandatory members
  11511. const std::string op = get_value("op", "op", true);
  11512. const std::string path = get_value(op, "path", true);
  11513. json_pointer ptr(path);
  11514. switch (get_op(op))
  11515. {
  11516. case patch_operations::add:
  11517. {
  11518. operation_add(ptr, get_value("add", "value", false));
  11519. break;
  11520. }
  11521. case patch_operations::remove:
  11522. {
  11523. operation_remove(ptr);
  11524. break;
  11525. }
  11526. case patch_operations::replace:
  11527. {
  11528. // the "path" location must exist - use at()
  11529. result.at(ptr) = get_value("replace", "value", false);
  11530. break;
  11531. }
  11532. case patch_operations::move:
  11533. {
  11534. const std::string from_path = get_value("move", "from", true);
  11535. json_pointer from_ptr(from_path);
  11536. // the "from" location must exist - use at()
  11537. basic_json v = result.at(from_ptr);
  11538. // The move operation is functionally identical to a
  11539. // "remove" operation on the "from" location, followed
  11540. // immediately by an "add" operation at the target
  11541. // location with the value that was just removed.
  11542. operation_remove(from_ptr);
  11543. operation_add(ptr, v);
  11544. break;
  11545. }
  11546. case patch_operations::copy:
  11547. {
  11548. const std::string from_path = get_value("copy", "from", true);;
  11549. const json_pointer from_ptr(from_path);
  11550. // the "from" location must exist - use at()
  11551. result[ptr] = result.at(from_ptr);
  11552. break;
  11553. }
  11554. case patch_operations::test:
  11555. {
  11556. bool success = false;
  11557. JSON_TRY
  11558. {
  11559. // check if "value" matches the one at "path"
  11560. // the "path" location must exist - use at()
  11561. success = (result.at(ptr) == get_value("test", "value", false));
  11562. }
  11563. JSON_CATCH (out_of_range&)
  11564. {
  11565. // ignore out of range errors: success remains false
  11566. }
  11567. // throw an exception if test fails
  11568. if (not success)
  11569. {
  11570. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  11571. }
  11572. break;
  11573. }
  11574. case patch_operations::invalid:
  11575. {
  11576. // op must be "add", "remove", "replace", "move", "copy", or
  11577. // "test"
  11578. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  11579. }
  11580. }
  11581. }
  11582. return result;
  11583. }
  11584. /*!
  11585. @brief creates a diff as a JSON patch
  11586. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  11587. be changed into the value @a target by calling @ref patch function.
  11588. @invariant For two JSON values @a source and @a target, the following code
  11589. yields always `true`:
  11590. @code {.cpp}
  11591. source.patch(diff(source, target)) == target;
  11592. @endcode
  11593. @note Currently, only `remove`, `add`, and `replace` operations are
  11594. generated.
  11595. @param[in] source JSON value to compare from
  11596. @param[in] target JSON value to compare against
  11597. @param[in] path helper value to create JSON pointers
  11598. @return a JSON patch to convert the @a source to @a target
  11599. @complexity Linear in the lengths of @a source and @a target.
  11600. @liveexample{The following code shows how a JSON patch is created as a
  11601. diff for two JSON values.,diff}
  11602. @sa @ref patch -- apply a JSON patch
  11603. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11604. @since version 2.0.0
  11605. */
  11606. static basic_json diff(const basic_json& source,
  11607. const basic_json& target,
  11608. const std::string& path = "")
  11609. {
  11610. // the patch
  11611. basic_json result(value_t::array);
  11612. // if the values are the same, return empty patch
  11613. if (source == target)
  11614. {
  11615. return result;
  11616. }
  11617. if (source.type() != target.type())
  11618. {
  11619. // different types: replace value
  11620. result.push_back(
  11621. {
  11622. {"op", "replace"},
  11623. {"path", path},
  11624. {"value", target}
  11625. });
  11626. }
  11627. else
  11628. {
  11629. switch (source.type())
  11630. {
  11631. case value_t::array:
  11632. {
  11633. // first pass: traverse common elements
  11634. size_t i = 0;
  11635. while (i < source.size() and i < target.size())
  11636. {
  11637. // recursive call to compare array values at index i
  11638. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  11639. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11640. ++i;
  11641. }
  11642. // i now reached the end of at least one array
  11643. // in a second pass, traverse the remaining elements
  11644. // remove my remaining elements
  11645. const auto end_index = static_cast<difference_type>(result.size());
  11646. while (i < source.size())
  11647. {
  11648. // add operations in reverse order to avoid invalid
  11649. // indices
  11650. result.insert(result.begin() + end_index, object(
  11651. {
  11652. {"op", "remove"},
  11653. {"path", path + "/" + std::to_string(i)}
  11654. }));
  11655. ++i;
  11656. }
  11657. // add other remaining elements
  11658. while (i < target.size())
  11659. {
  11660. result.push_back(
  11661. {
  11662. {"op", "add"},
  11663. {"path", path + "/" + std::to_string(i)},
  11664. {"value", target[i]}
  11665. });
  11666. ++i;
  11667. }
  11668. break;
  11669. }
  11670. case value_t::object:
  11671. {
  11672. // first pass: traverse this object's elements
  11673. for (auto it = source.begin(); it != source.end(); ++it)
  11674. {
  11675. // escape the key name to be used in a JSON patch
  11676. const auto key = json_pointer::escape(it.key());
  11677. if (target.find(it.key()) != target.end())
  11678. {
  11679. // recursive call to compare object values at key it
  11680. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  11681. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11682. }
  11683. else
  11684. {
  11685. // found a key that is not in o -> remove it
  11686. result.push_back(object(
  11687. {
  11688. {"op", "remove"},
  11689. {"path", path + "/" + key}
  11690. }));
  11691. }
  11692. }
  11693. // second pass: traverse other object's elements
  11694. for (auto it = target.begin(); it != target.end(); ++it)
  11695. {
  11696. if (source.find(it.key()) == source.end())
  11697. {
  11698. // found a key that is not in this -> add it
  11699. const auto key = json_pointer::escape(it.key());
  11700. result.push_back(
  11701. {
  11702. {"op", "add"},
  11703. {"path", path + "/" + key},
  11704. {"value", it.value()}
  11705. });
  11706. }
  11707. }
  11708. break;
  11709. }
  11710. default:
  11711. {
  11712. // both primitive type: replace value
  11713. result.push_back(
  11714. {
  11715. {"op", "replace"},
  11716. {"path", path},
  11717. {"value", target}
  11718. });
  11719. break;
  11720. }
  11721. }
  11722. }
  11723. return result;
  11724. }
  11725. /// @}
  11726. };
  11727. /////////////
  11728. // presets //
  11729. /////////////
  11730. /*!
  11731. @brief default JSON class
  11732. This type is the default specialization of the @ref basic_json class which
  11733. uses the standard template types.
  11734. @since version 1.0.0
  11735. */
  11736. using json = basic_json<>;
  11737. } // namespace nlohmann
  11738. ///////////////////////
  11739. // nonmember support //
  11740. ///////////////////////
  11741. // specialization of std::swap, and std::hash
  11742. namespace std
  11743. {
  11744. /*!
  11745. @brief exchanges the values of two JSON objects
  11746. @since version 1.0.0
  11747. */
  11748. template<>
  11749. inline void swap(nlohmann::json& j1,
  11750. nlohmann::json& j2) noexcept(
  11751. is_nothrow_move_constructible<nlohmann::json>::value and
  11752. is_nothrow_move_assignable<nlohmann::json>::value
  11753. )
  11754. {
  11755. j1.swap(j2);
  11756. }
  11757. /// hash value for JSON objects
  11758. template<>
  11759. struct hash<nlohmann::json>
  11760. {
  11761. /*!
  11762. @brief return a hash value for a JSON object
  11763. @since version 1.0.0
  11764. */
  11765. std::size_t operator()(const nlohmann::json& j) const
  11766. {
  11767. // a naive hashing via the string representation
  11768. const auto& h = hash<nlohmann::json::string_t>();
  11769. return h(j.dump());
  11770. }
  11771. };
  11772. /// specialization for std::less<value_t>
  11773. template <>
  11774. struct less<::nlohmann::detail::value_t>
  11775. {
  11776. /*!
  11777. @brief compare two value_t enum values
  11778. @since version 3.0.0
  11779. */
  11780. bool operator()(nlohmann::detail::value_t lhs,
  11781. nlohmann::detail::value_t rhs) const noexcept
  11782. {
  11783. return nlohmann::detail::operator<(lhs, rhs);
  11784. }
  11785. };
  11786. } // namespace std
  11787. /*!
  11788. @brief user-defined string literal for JSON values
  11789. This operator implements a user-defined string literal for JSON objects. It
  11790. can be used by adding `"_json"` to a string literal and returns a JSON object
  11791. if no parse error occurred.
  11792. @param[in] s a string representation of a JSON object
  11793. @param[in] n the length of string @a s
  11794. @return a JSON object
  11795. @since version 1.0.0
  11796. */
  11797. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  11798. {
  11799. return nlohmann::json::parse(s, s + n);
  11800. }
  11801. /*!
  11802. @brief user-defined string literal for JSON pointer
  11803. This operator implements a user-defined string literal for JSON Pointers. It
  11804. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  11805. object if no parse error occurred.
  11806. @param[in] s a string representation of a JSON Pointer
  11807. @param[in] n the length of string @a s
  11808. @return a JSON pointer object
  11809. @since version 2.0.0
  11810. */
  11811. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  11812. {
  11813. return nlohmann::json::json_pointer(std::string(s, n));
  11814. }
  11815. // restore GCC/clang diagnostic settings
  11816. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  11817. #pragma GCC diagnostic pop
  11818. #endif
  11819. #if defined(__clang__)
  11820. #pragma GCC diagnostic pop
  11821. #endif
  11822. // clean up
  11823. #undef JSON_CATCH
  11824. #undef JSON_THROW
  11825. #undef JSON_TRY
  11826. #undef JSON_DEPRECATED
  11827. #endif