json.hpp 356 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 2.0.7
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2016 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, for_each, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <cctype> // isdigit
  30. #include <ciso646> // and, not, or
  31. #include <cmath> // isfinite, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // strtod, strtof, strtold, strtoul
  35. #include <cstring> // strlen
  36. #include <functional> // function, hash, less
  37. #include <initializer_list> // initializer_list
  38. #include <iomanip> // setw
  39. #include <iostream> // istream, ostream
  40. #include <iterator> // advance, begin, 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, numpunct
  43. #include <map> // map
  44. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  45. #include <numeric> // accumulate
  46. #include <sstream> // stringstream
  47. #include <stdexcept> // domain_error, invalid_argument, out_of_range
  48. #include <string> // getline, stoi, string, to_string
  49. #include <type_traits> // add_pointer, enable_if, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_floating_point, is_integral, is_nothrow_move_assignable, std::is_nothrow_move_constructible, std::is_pointer, std::is_reference, std::is_same, remove_const, remove_pointer, remove_reference
  50. #include <utility> // declval, forward, make_pair, move, pair, swap
  51. #include <vector> // vector
  52. // exclude unsupported compilers
  53. #if defined(__clang__)
  54. #define CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
  55. #if CLANG_VERSION < 30400
  56. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  57. #endif
  58. #elif defined(__GNUC__)
  59. #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  60. #if GCC_VERSION < 40900
  61. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  62. #endif
  63. #endif
  64. // disable float-equal warnings on GCC/clang
  65. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  66. #pragma GCC diagnostic push
  67. #pragma GCC diagnostic ignored "-Wfloat-equal"
  68. #endif
  69. // allow for portable deprecation warnings
  70. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  71. #define JSON_DEPRECATED __attribute__((deprecated))
  72. #elif defined(_MSC_VER)
  73. #define JSON_DEPRECATED __declspec(deprecated)
  74. #else
  75. #define JSON_DEPRECATED
  76. #endif
  77. /*!
  78. @brief namespace for Niels Lohmann
  79. @see https://github.com/nlohmann
  80. @since version 1.0.0
  81. */
  82. namespace nlohmann
  83. {
  84. /*!
  85. @brief unnamed namespace with internal helper functions
  86. @since version 1.0.0
  87. */
  88. namespace
  89. {
  90. /*!
  91. @brief Helper to determine whether there's a key_type for T.
  92. Thus helper is used to tell associative containers apart from other containers
  93. such as sequence containers. For instance, `std::map` passes the test as it
  94. contains a `mapped_type`, whereas `std::vector` fails the test.
  95. @sa http://stackoverflow.com/a/7728728/266378
  96. @since version 1.0.0, overworked in version 2.0.6
  97. */
  98. template<typename T>
  99. struct has_mapped_type
  100. {
  101. private:
  102. template <typename U, typename = typename U::mapped_type>
  103. static int detect(U&&);
  104. static void detect(...);
  105. public:
  106. static constexpr bool value =
  107. std::is_integral<decltype(detect(std::declval<T>()))>::value;
  108. };
  109. /*!
  110. @brief helper class to create locales with decimal point
  111. This struct is used a default locale during the JSON serialization. JSON
  112. requires the decimal point to be `.`, so this function overloads the
  113. `do_decimal_point()` function to return `.`. This function is called by
  114. float-to-string conversions to retrieve the decimal separator between integer
  115. and fractional parts.
  116. @sa https://github.com/nlohmann/json/issues/51#issuecomment-86869315
  117. @since version 2.0.0
  118. */
  119. struct DecimalSeparator : std::numpunct<char>
  120. {
  121. char do_decimal_point() const
  122. {
  123. return '.';
  124. }
  125. };
  126. }
  127. /*!
  128. @brief a class to store JSON values
  129. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  130. in @ref object_t)
  131. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  132. in @ref array_t)
  133. @tparam StringType type for JSON strings and object keys (`std::string` by
  134. default; will be used in @ref string_t)
  135. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  136. in @ref boolean_t)
  137. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  138. default; will be used in @ref number_integer_t)
  139. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  140. `uint64_t` by default; will be used in @ref number_unsigned_t)
  141. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  142. default; will be used in @ref number_float_t)
  143. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  144. default)
  145. @requirement The class satisfies the following concept requirements:
  146. - Basic
  147. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  148. JSON values can be default constructed. The result will be a JSON null value.
  149. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  150. A JSON value can be constructed from an rvalue argument.
  151. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  152. A JSON value can be copy-constructed from an lvalue expression.
  153. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  154. A JSON value van be assigned from an rvalue argument.
  155. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  156. A JSON value can be copy-assigned from an lvalue expression.
  157. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  158. JSON values can be destructed.
  159. - Layout
  160. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  161. JSON values have
  162. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  163. All non-static data members are private and standard layout types, the class
  164. has no virtual functions or (virtual) base classes.
  165. - Library-wide
  166. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  167. JSON values can be compared with `==`, see @ref
  168. operator==(const_reference,const_reference).
  169. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  170. JSON values can be compared with `<`, see @ref
  171. operator<(const_reference,const_reference).
  172. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  173. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  174. other compatible types, using unqualified function call @ref swap().
  175. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  176. JSON values can be compared against `std::nullptr_t` objects which are used
  177. to model the `null` value.
  178. - Container
  179. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  180. JSON values can be used like STL containers and provide iterator access.
  181. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  182. JSON values can be used like STL containers and provide reverse iterator
  183. access.
  184. @invariant The member variables @a m_value and @a m_type have the following
  185. relationship:
  186. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  187. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  188. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  189. The invariants are checked by member function assert_invariant().
  190. @internal
  191. @note ObjectType trick from http://stackoverflow.com/a/9860911
  192. @endinternal
  193. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  194. Format](http://rfc7159.net/rfc7159)
  195. @since version 1.0.0
  196. @nosubgrouping
  197. */
  198. template <
  199. template<typename U, typename V, typename... Args> class ObjectType = std::map,
  200. template<typename U, typename... Args> class ArrayType = std::vector,
  201. class StringType = std::string,
  202. class BooleanType = bool,
  203. class NumberIntegerType = std::int64_t,
  204. class NumberUnsignedType = std::uint64_t,
  205. class NumberFloatType = double,
  206. template<typename U> class AllocatorType = std::allocator
  207. >
  208. class basic_json
  209. {
  210. private:
  211. /// workaround type for MSVC
  212. using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
  213. BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
  214. AllocatorType>;
  215. public:
  216. // forward declarations
  217. template<typename Base> class json_reverse_iterator;
  218. class json_pointer;
  219. /////////////////////
  220. // container types //
  221. /////////////////////
  222. /// @name container types
  223. /// The canonic container types to use @ref basic_json like any other STL
  224. /// container.
  225. /// @{
  226. /// the type of elements in a basic_json container
  227. using value_type = basic_json;
  228. /// the type of an element reference
  229. using reference = value_type&;
  230. /// the type of an element const reference
  231. using const_reference = const value_type&;
  232. /// a type to represent differences between iterators
  233. using difference_type = std::ptrdiff_t;
  234. /// a type to represent container sizes
  235. using size_type = std::size_t;
  236. /// the allocator type
  237. using allocator_type = AllocatorType<basic_json>;
  238. /// the type of an element pointer
  239. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  240. /// the type of an element const pointer
  241. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  242. /// an iterator for a basic_json container
  243. class iterator;
  244. /// a const iterator for a basic_json container
  245. class const_iterator;
  246. /// a reverse iterator for a basic_json container
  247. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  248. /// a const reverse iterator for a basic_json container
  249. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  250. /// @}
  251. /*!
  252. @brief returns the allocator associated with the container
  253. */
  254. static allocator_type get_allocator()
  255. {
  256. return allocator_type();
  257. }
  258. ///////////////////////////
  259. // JSON value data types //
  260. ///////////////////////////
  261. /// @name JSON value data types
  262. /// The data types to store a JSON value. These types are derived from
  263. /// the template arguments passed to class @ref basic_json.
  264. /// @{
  265. /*!
  266. @brief a type for an object
  267. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  268. > An object is an unordered collection of zero or more name/value pairs,
  269. > where a name is a string and a value is a string, number, boolean, null,
  270. > object, or array.
  271. To store objects in C++, a type is defined by the template parameters
  272. described below.
  273. @tparam ObjectType the container to store objects (e.g., `std::map` or
  274. `std::unordered_map`)
  275. @tparam StringType the type of the keys or names (e.g., `std::string`).
  276. The comparison function `std::less<StringType>` is used to order elements
  277. inside the container.
  278. @tparam AllocatorType the allocator to use for objects (e.g.,
  279. `std::allocator`)
  280. #### Default type
  281. With the default values for @a ObjectType (`std::map`), @a StringType
  282. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  283. value for @a object_t is:
  284. @code {.cpp}
  285. std::map<
  286. std::string, // key_type
  287. basic_json, // value_type
  288. std::less<std::string>, // key_compare
  289. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  290. >
  291. @endcode
  292. #### Behavior
  293. The choice of @a object_t influences the behavior of the JSON class. With
  294. the default type, objects have the following behavior:
  295. - When all names are unique, objects will be interoperable in the sense
  296. that all software implementations receiving that object will agree on
  297. the name-value mappings.
  298. - When the names within an object are not unique, later stored name/value
  299. pairs overwrite previously stored name/value pairs, leaving the used
  300. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  301. be treated as equal and both stored as `{"key": 1}`.
  302. - Internally, name/value pairs are stored in lexicographical order of the
  303. names. Objects will also be serialized (see @ref dump) in this order.
  304. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  305. and serialized as `{"a": 2, "b": 1}`.
  306. - When comparing objects, the order of the name/value pairs is irrelevant.
  307. This makes objects interoperable in the sense that they will not be
  308. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  309. `{"a": 2, "b": 1}` will be treated as equal.
  310. #### Limits
  311. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  312. > An implementation may set limits on the maximum depth of nesting.
  313. In this class, the object's limit of nesting is not constraint explicitly.
  314. However, a maximum depth of nesting may be introduced by the compiler or
  315. runtime environment. A theoretical limit can be queried by calling the
  316. @ref max_size function of a JSON object.
  317. #### Storage
  318. Objects are stored as pointers in a @ref basic_json type. That is, for any
  319. access to object values, a pointer of type `object_t*` must be
  320. dereferenced.
  321. @sa @ref array_t -- type for an array value
  322. @since version 1.0.0
  323. @note The order name/value pairs are added to the object is *not*
  324. preserved by the library. Therefore, iterating an object may return
  325. name/value pairs in a different order than they were originally stored. In
  326. fact, keys will be traversed in alphabetical order as `std::map` with
  327. `std::less` is used by default. Please note this behavior conforms to [RFC
  328. 7159](http://rfc7159.net/rfc7159), because any order implements the
  329. specified "unordered" nature of JSON objects.
  330. */
  331. using object_t = ObjectType<StringType,
  332. basic_json,
  333. std::less<StringType>,
  334. AllocatorType<std::pair<const StringType,
  335. basic_json>>>;
  336. /*!
  337. @brief a type for an array
  338. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  339. > An array is an ordered sequence of zero or more values.
  340. To store objects in C++, a type is defined by the template parameters
  341. explained below.
  342. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  343. `std::list`)
  344. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  345. #### Default type
  346. With the default values for @a ArrayType (`std::vector`) and @a
  347. AllocatorType (`std::allocator`), the default value for @a array_t is:
  348. @code {.cpp}
  349. std::vector<
  350. basic_json, // value_type
  351. std::allocator<basic_json> // allocator_type
  352. >
  353. @endcode
  354. #### Limits
  355. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  356. > An implementation may set limits on the maximum depth of nesting.
  357. In this class, the array's limit of nesting is not constraint explicitly.
  358. However, a maximum depth of nesting may be introduced by the compiler or
  359. runtime environment. A theoretical limit can be queried by calling the
  360. @ref max_size function of a JSON array.
  361. #### Storage
  362. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  363. access to array values, a pointer of type `array_t*` must be dereferenced.
  364. @sa @ref object_t -- type for an object value
  365. @since version 1.0.0
  366. */
  367. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  368. /*!
  369. @brief a type for a string
  370. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  371. > A string is a sequence of zero or more Unicode characters.
  372. To store objects in C++, a type is defined by the template parameter
  373. described below. Unicode values are split by the JSON class into
  374. byte-sized characters during deserialization.
  375. @tparam StringType the container to store strings (e.g., `std::string`).
  376. Note this container is used for keys/names in objects, see @ref object_t.
  377. #### Default type
  378. With the default values for @a StringType (`std::string`), the default
  379. value for @a string_t is:
  380. @code {.cpp}
  381. std::string
  382. @endcode
  383. #### String comparison
  384. [RFC 7159](http://rfc7159.net/rfc7159) states:
  385. > Software implementations are typically required to test names of object
  386. > members for equality. Implementations that transform the textual
  387. > representation into sequences of Unicode code units and then perform the
  388. > comparison numerically, code unit by code unit, are interoperable in the
  389. > sense that implementations will agree in all cases on equality or
  390. > inequality of two strings. For example, implementations that compare
  391. > strings with escaped characters unconverted may incorrectly find that
  392. > `"a\\b"` and `"a\u005Cb"` are not equal.
  393. This implementation is interoperable as it does compare strings code unit
  394. by code unit.
  395. #### Storage
  396. String values are stored as pointers in a @ref basic_json type. That is,
  397. for any access to string values, a pointer of type `string_t*` must be
  398. dereferenced.
  399. @since version 1.0.0
  400. */
  401. using string_t = StringType;
  402. /*!
  403. @brief a type for a boolean
  404. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  405. type which differentiates the two literals `true` and `false`.
  406. To store objects in C++, a type is defined by the template parameter @a
  407. BooleanType which chooses the type to use.
  408. #### Default type
  409. With the default values for @a BooleanType (`bool`), the default value for
  410. @a boolean_t is:
  411. @code {.cpp}
  412. bool
  413. @endcode
  414. #### Storage
  415. Boolean values are stored directly inside a @ref basic_json type.
  416. @since version 1.0.0
  417. */
  418. using boolean_t = BooleanType;
  419. /*!
  420. @brief a type for a number (integer)
  421. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  422. > The representation of numbers is similar to that used in most
  423. > programming languages. A number is represented in base 10 using decimal
  424. > digits. It contains an integer component that may be prefixed with an
  425. > optional minus sign, which may be followed by a fraction part and/or an
  426. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  427. > cannot be represented in the grammar below (such as Infinity and NaN)
  428. > are not permitted.
  429. This description includes both integer and floating-point numbers.
  430. However, C++ allows more precise storage if it is known whether the number
  431. is a signed integer, an unsigned integer or a floating-point number.
  432. Therefore, three different types, @ref number_integer_t, @ref
  433. number_unsigned_t and @ref number_float_t are used.
  434. To store integer numbers in C++, a type is defined by the template
  435. parameter @a NumberIntegerType which chooses the type to use.
  436. #### Default type
  437. With the default values for @a NumberIntegerType (`int64_t`), the default
  438. value for @a number_integer_t is:
  439. @code {.cpp}
  440. int64_t
  441. @endcode
  442. #### Default behavior
  443. - The restrictions about leading zeros is not enforced in C++. Instead,
  444. leading zeros in integer literals lead to an interpretation as octal
  445. number. Internally, the value will be stored as decimal number. For
  446. instance, the C++ integer literal `010` will be serialized to `8`.
  447. During deserialization, leading zeros yield an error.
  448. - Not-a-number (NaN) values will be serialized to `null`.
  449. #### Limits
  450. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  451. > An implementation may set limits on the range and precision of numbers.
  452. When the default type is used, the maximal integer number that can be
  453. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  454. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  455. that are out of range will yield over/underflow when used in a
  456. constructor. During deserialization, too large or small integer numbers
  457. will be automatically be stored as @ref number_unsigned_t or @ref
  458. number_float_t.
  459. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  460. > Note that when such software is used, numbers that are integers and are
  461. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  462. > that implementations will agree exactly on their numeric values.
  463. As this range is a subrange of the exactly supported range [INT64_MIN,
  464. INT64_MAX], this class's integer type is interoperable.
  465. #### Storage
  466. Integer number values are stored directly inside a @ref basic_json type.
  467. @sa @ref number_float_t -- type for number values (floating-point)
  468. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  469. @since version 1.0.0
  470. */
  471. using number_integer_t = NumberIntegerType;
  472. /*!
  473. @brief a type for a number (unsigned)
  474. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  475. > The representation of numbers is similar to that used in most
  476. > programming languages. A number is represented in base 10 using decimal
  477. > digits. It contains an integer component that may be prefixed with an
  478. > optional minus sign, which may be followed by a fraction part and/or an
  479. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  480. > cannot be represented in the grammar below (such as Infinity and NaN)
  481. > are not permitted.
  482. This description includes both integer and floating-point numbers.
  483. However, C++ allows more precise storage if it is known whether the number
  484. is a signed integer, an unsigned integer or a floating-point number.
  485. Therefore, three different types, @ref number_integer_t, @ref
  486. number_unsigned_t and @ref number_float_t are used.
  487. To store unsigned integer numbers in C++, a type is defined by the
  488. template parameter @a NumberUnsignedType which chooses the type to use.
  489. #### Default type
  490. With the default values for @a NumberUnsignedType (`uint64_t`), the
  491. default value for @a number_unsigned_t is:
  492. @code {.cpp}
  493. uint64_t
  494. @endcode
  495. #### Default behavior
  496. - The restrictions about leading zeros is not enforced in C++. Instead,
  497. leading zeros in integer literals lead to an interpretation as octal
  498. number. Internally, the value will be stored as decimal number. For
  499. instance, the C++ integer literal `010` will be serialized to `8`.
  500. During deserialization, leading zeros yield an error.
  501. - Not-a-number (NaN) values will be serialized to `null`.
  502. #### Limits
  503. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  504. > An implementation may set limits on the range and precision of numbers.
  505. When the default type is used, the maximal integer number that can be
  506. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  507. number that can be stored is `0`. Integer numbers that are out of range
  508. will yield over/underflow when used in a constructor. During
  509. deserialization, too large or small integer numbers will be automatically
  510. be stored as @ref number_integer_t or @ref number_float_t.
  511. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  512. > Note that when such software is used, numbers that are integers and are
  513. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  514. > that implementations will agree exactly on their numeric values.
  515. As this range is a subrange (when considered in conjunction with the
  516. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  517. this class's integer type is interoperable.
  518. #### Storage
  519. Integer number values are stored directly inside a @ref basic_json type.
  520. @sa @ref number_float_t -- type for number values (floating-point)
  521. @sa @ref number_integer_t -- type for number values (integer)
  522. @since version 2.0.0
  523. */
  524. using number_unsigned_t = NumberUnsignedType;
  525. /*!
  526. @brief a type for a number (floating-point)
  527. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  528. > The representation of numbers is similar to that used in most
  529. > programming languages. A number is represented in base 10 using decimal
  530. > digits. It contains an integer component that may be prefixed with an
  531. > optional minus sign, which may be followed by a fraction part and/or an
  532. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  533. > cannot be represented in the grammar below (such as Infinity and NaN)
  534. > are not permitted.
  535. This description includes both integer and floating-point numbers.
  536. However, C++ allows more precise storage if it is known whether the number
  537. is a signed integer, an unsigned integer or a floating-point number.
  538. Therefore, three different types, @ref number_integer_t, @ref
  539. number_unsigned_t and @ref number_float_t are used.
  540. To store floating-point numbers in C++, a type is defined by the template
  541. parameter @a NumberFloatType which chooses the type to use.
  542. #### Default type
  543. With the default values for @a NumberFloatType (`double`), the default
  544. value for @a number_float_t is:
  545. @code {.cpp}
  546. double
  547. @endcode
  548. #### Default behavior
  549. - The restrictions about leading zeros is not enforced in C++. Instead,
  550. leading zeros in floating-point literals will be ignored. Internally,
  551. the value will be stored as decimal number. For instance, the C++
  552. floating-point literal `01.2` will be serialized to `1.2`. During
  553. deserialization, leading zeros yield an error.
  554. - Not-a-number (NaN) values will be serialized to `null`.
  555. #### Limits
  556. [RFC 7159](http://rfc7159.net/rfc7159) states:
  557. > This specification allows implementations to set limits on the range and
  558. > precision of numbers accepted. Since software that implements IEEE
  559. > 754-2008 binary64 (double precision) numbers is generally available and
  560. > widely used, good interoperability can be achieved by implementations
  561. > that expect no more precision or range than these provide, in the sense
  562. > that implementations will approximate JSON numbers within the expected
  563. > precision.
  564. This implementation does exactly follow this approach, as it uses double
  565. precision floating-point numbers. Note values smaller than
  566. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  567. will be stored as NaN internally and be serialized to `null`.
  568. #### Storage
  569. Floating-point number values are stored directly inside a @ref basic_json
  570. type.
  571. @sa @ref number_integer_t -- type for number values (integer)
  572. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  573. @since version 1.0.0
  574. */
  575. using number_float_t = NumberFloatType;
  576. /// @}
  577. ///////////////////////////
  578. // JSON type enumeration //
  579. ///////////////////////////
  580. /*!
  581. @brief the JSON type enumeration
  582. This enumeration collects the different JSON types. It is internally used
  583. to distinguish the stored values, and the functions @ref is_null(), @ref
  584. is_object(), @ref is_array(), @ref is_string(), @ref is_boolean(), @ref
  585. is_number() (with @ref is_number_integer(), @ref is_number_unsigned(), and
  586. @ref is_number_float()), @ref is_discarded(), @ref is_primitive(), and
  587. @ref is_structured() rely on it.
  588. @note There are three enumeration entries (number_integer,
  589. number_unsigned, and number_float), because the library distinguishes
  590. these three types for numbers: @ref number_unsigned_t is used for unsigned
  591. integers, @ref number_integer_t is used for signed integers, and @ref
  592. number_float_t is used for floating-point numbers or to approximate
  593. integers which do not fit in the limits of their respective type.
  594. @sa @ref basic_json(const value_t value_type) -- create a JSON value with
  595. the default value for a given type
  596. @since version 1.0.0
  597. */
  598. enum class value_t : uint8_t
  599. {
  600. null, ///< null value
  601. object, ///< object (unordered set of name/value pairs)
  602. array, ///< array (ordered collection of values)
  603. string, ///< string value
  604. boolean, ///< boolean value
  605. number_integer, ///< number value (signed integer)
  606. number_unsigned, ///< number value (unsigned integer)
  607. number_float, ///< number value (floating-point)
  608. discarded ///< discarded by the the parser callback function
  609. };
  610. private:
  611. /// helper for exception-safe object creation
  612. template<typename T, typename... Args>
  613. static T* create(Args&& ... args)
  614. {
  615. AllocatorType<T> alloc;
  616. auto deleter = [&](T * object)
  617. {
  618. alloc.deallocate(object, 1);
  619. };
  620. std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
  621. alloc.construct(object.get(), std::forward<Args>(args)...);
  622. assert(object.get() != nullptr);
  623. return object.release();
  624. }
  625. ////////////////////////
  626. // JSON value storage //
  627. ////////////////////////
  628. /*!
  629. @brief a JSON value
  630. The actual storage for a JSON value of the @ref basic_json class. This
  631. union combines the different storage types for the JSON value types
  632. defined in @ref value_t.
  633. JSON type | value_t type | used type
  634. --------- | --------------- | ------------------------
  635. object | object | pointer to @ref object_t
  636. array | array | pointer to @ref array_t
  637. string | string | pointer to @ref string_t
  638. boolean | boolean | @ref boolean_t
  639. number | number_integer | @ref number_integer_t
  640. number | number_unsigned | @ref number_unsigned_t
  641. number | number_float | @ref number_float_t
  642. null | null | *no value is stored*
  643. @note Variable-length types (objects, arrays, and strings) are stored as
  644. pointers. The size of the union should not exceed 64 bits if the default
  645. value types are used.
  646. @since version 1.0.0
  647. */
  648. union json_value
  649. {
  650. /// object (stored with pointer to save storage)
  651. object_t* object;
  652. /// array (stored with pointer to save storage)
  653. array_t* array;
  654. /// string (stored with pointer to save storage)
  655. string_t* string;
  656. /// boolean
  657. boolean_t boolean;
  658. /// number (integer)
  659. number_integer_t number_integer;
  660. /// number (unsigned integer)
  661. number_unsigned_t number_unsigned;
  662. /// number (floating-point)
  663. number_float_t number_float;
  664. /// default constructor (for null values)
  665. json_value() = default;
  666. /// constructor for booleans
  667. json_value(boolean_t v) noexcept : boolean(v) {}
  668. /// constructor for numbers (integer)
  669. json_value(number_integer_t v) noexcept : number_integer(v) {}
  670. /// constructor for numbers (unsigned)
  671. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  672. /// constructor for numbers (floating-point)
  673. json_value(number_float_t v) noexcept : number_float(v) {}
  674. /// constructor for empty values of a given type
  675. json_value(value_t t)
  676. {
  677. switch (t)
  678. {
  679. case value_t::object:
  680. {
  681. object = create<object_t>();
  682. break;
  683. }
  684. case value_t::array:
  685. {
  686. array = create<array_t>();
  687. break;
  688. }
  689. case value_t::string:
  690. {
  691. string = create<string_t>("");
  692. break;
  693. }
  694. case value_t::boolean:
  695. {
  696. boolean = boolean_t(false);
  697. break;
  698. }
  699. case value_t::number_integer:
  700. {
  701. number_integer = number_integer_t(0);
  702. break;
  703. }
  704. case value_t::number_unsigned:
  705. {
  706. number_unsigned = number_unsigned_t(0);
  707. break;
  708. }
  709. case value_t::number_float:
  710. {
  711. number_float = number_float_t(0.0);
  712. break;
  713. }
  714. default:
  715. {
  716. break;
  717. }
  718. }
  719. }
  720. /// constructor for strings
  721. json_value(const string_t& value)
  722. {
  723. string = create<string_t>(value);
  724. }
  725. /// constructor for objects
  726. json_value(const object_t& value)
  727. {
  728. object = create<object_t>(value);
  729. }
  730. /// constructor for arrays
  731. json_value(const array_t& value)
  732. {
  733. array = create<array_t>(value);
  734. }
  735. };
  736. /*!
  737. @brief checks the class invariants
  738. This function asserts the class invariants. It needs to be called at the
  739. end of every constructor to make sure that created objects respect the
  740. invariant. Furthermore, it has to be called each time the type of a JSON
  741. value is changed, because the invariant expresses a relationship between
  742. @a m_type and @a m_value.
  743. */
  744. void assert_invariant() const
  745. {
  746. assert(m_type != value_t::object or m_value.object != nullptr);
  747. assert(m_type != value_t::array or m_value.array != nullptr);
  748. assert(m_type != value_t::string or m_value.string != nullptr);
  749. }
  750. public:
  751. //////////////////////////
  752. // JSON parser callback //
  753. //////////////////////////
  754. /*!
  755. @brief JSON callback events
  756. This enumeration lists the parser events that can trigger calling a
  757. callback function of type @ref parser_callback_t during parsing.
  758. @image html callback_events.png "Example when certain parse events are triggered"
  759. @since version 1.0.0
  760. */
  761. enum class parse_event_t : uint8_t
  762. {
  763. /// the parser read `{` and started to process a JSON object
  764. object_start,
  765. /// the parser read `}` and finished processing a JSON object
  766. object_end,
  767. /// the parser read `[` and started to process a JSON array
  768. array_start,
  769. /// the parser read `]` and finished processing a JSON array
  770. array_end,
  771. /// the parser read a key of a value in an object
  772. key,
  773. /// the parser finished reading a JSON value
  774. value
  775. };
  776. /*!
  777. @brief per-element parser callback type
  778. With a parser callback function, the result of parsing a JSON text can be
  779. influenced. When passed to @ref parse(std::istream&, const
  780. parser_callback_t) or @ref parse(const char*, const parser_callback_t),
  781. it is called on certain events (passed as @ref parse_event_t via parameter
  782. @a event) with a set recursion depth @a depth and context JSON value
  783. @a parsed. The return value of the callback function is a boolean
  784. indicating whether the element that emitted the callback shall be kept or
  785. not.
  786. We distinguish six scenarios (determined by the event type) in which the
  787. callback function can be called. The following table describes the values
  788. of the parameters @a depth, @a event, and @a parsed.
  789. parameter @a event | description | parameter @a depth | parameter @a parsed
  790. ------------------ | ----------- | ------------------ | -------------------
  791. 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
  792. 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
  793. 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
  794. 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
  795. 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
  796. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  797. @image html callback_events.png "Example when certain parse events are triggered"
  798. Discarding a value (i.e., returning `false`) has different effects
  799. depending on the context in which function was called:
  800. - Discarded values in structured types are skipped. That is, the parser
  801. will behave as if the discarded value was never read.
  802. - In case a value outside a structured type is skipped, it is replaced
  803. with `null`. This case happens if the top-level element is skipped.
  804. @param[in] depth the depth of the recursion during parsing
  805. @param[in] event an event of type parse_event_t indicating the context in
  806. the callback function has been called
  807. @param[in,out] parsed the current intermediate parse result; note that
  808. writing to this value has no effect for parse_event_t::key events
  809. @return Whether the JSON value which called the function during parsing
  810. should be kept (`true`) or not (`false`). In the latter case, it is either
  811. skipped completely or replaced by an empty discarded object.
  812. @sa @ref parse(std::istream&, parser_callback_t) or
  813. @ref parse(const char*, parser_callback_t) for examples
  814. @since version 1.0.0
  815. */
  816. using parser_callback_t = std::function<bool(int depth,
  817. parse_event_t event,
  818. basic_json& parsed)>;
  819. //////////////////
  820. // constructors //
  821. //////////////////
  822. /// @name constructors and destructors
  823. /// Constructors of class @ref basic_json, copy/move constructor, copy
  824. /// assignment, static functions creating objects, and the destructor.
  825. /// @{
  826. /*!
  827. @brief create an empty value with a given type
  828. Create an empty JSON value with a given type. The value will be default
  829. initialized with an empty value which depends on the type:
  830. Value type | initial value
  831. ----------- | -------------
  832. null | `null`
  833. boolean | `false`
  834. string | `""`
  835. number | `0`
  836. object | `{}`
  837. array | `[]`
  838. @param[in] value_type the type of the value to create
  839. @complexity Constant.
  840. @throw std::bad_alloc if allocation for object, array, or string value
  841. fails
  842. @liveexample{The following code shows the constructor for different @ref
  843. value_t values,basic_json__value_t}
  844. @sa @ref basic_json(std::nullptr_t) -- create a `null` value
  845. @sa @ref basic_json(boolean_t value) -- create a boolean value
  846. @sa @ref basic_json(const string_t&) -- create a string value
  847. @sa @ref basic_json(const object_t&) -- create a object value
  848. @sa @ref basic_json(const array_t&) -- create a array value
  849. @sa @ref basic_json(const number_float_t) -- create a number
  850. (floating-point) value
  851. @sa @ref basic_json(const number_integer_t) -- create a number (integer)
  852. value
  853. @sa @ref basic_json(const number_unsigned_t) -- create a number (unsigned)
  854. value
  855. @since version 1.0.0
  856. */
  857. basic_json(const value_t value_type)
  858. : m_type(value_type), m_value(value_type)
  859. {
  860. assert_invariant();
  861. }
  862. /*!
  863. @brief create a null object
  864. Create a `null` JSON value. It either takes a null pointer as parameter
  865. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  866. The passed null pointer itself is not read -- it is only used to choose
  867. the right constructor.
  868. @complexity Constant.
  869. @exceptionsafety No-throw guarantee: this constructor never throws
  870. exceptions.
  871. @liveexample{The following code shows the constructor with and without a
  872. null pointer parameter.,basic_json__nullptr_t}
  873. @since version 1.0.0
  874. */
  875. basic_json(std::nullptr_t = nullptr) noexcept
  876. : basic_json(value_t::null)
  877. {
  878. assert_invariant();
  879. }
  880. /*!
  881. @brief create an object (explicit)
  882. Create an object JSON value with a given content.
  883. @param[in] val a value for the object
  884. @complexity Linear in the size of the passed @a val.
  885. @throw std::bad_alloc if allocation for object value fails
  886. @liveexample{The following code shows the constructor with an @ref
  887. object_t parameter.,basic_json__object_t}
  888. @sa @ref basic_json(const CompatibleObjectType&) -- create an object value
  889. from a compatible STL container
  890. @since version 1.0.0
  891. */
  892. basic_json(const object_t& val)
  893. : m_type(value_t::object), m_value(val)
  894. {
  895. assert_invariant();
  896. }
  897. /*!
  898. @brief create an object (implicit)
  899. Create an object JSON value with a given content. This constructor allows
  900. any type @a CompatibleObjectType that can be used to construct values of
  901. type @ref object_t.
  902. @tparam CompatibleObjectType An object type whose `key_type` and
  903. `value_type` is compatible to @ref object_t. Examples include `std::map`,
  904. `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with
  905. a `key_type` of `std::string`, and a `value_type` from which a @ref
  906. basic_json value can be constructed.
  907. @param[in] val a value for the object
  908. @complexity Linear in the size of the passed @a val.
  909. @throw std::bad_alloc if allocation for object value fails
  910. @liveexample{The following code shows the constructor with several
  911. compatible object type parameters.,basic_json__CompatibleObjectType}
  912. @sa @ref basic_json(const object_t&) -- create an object value
  913. @since version 1.0.0
  914. */
  915. template<class CompatibleObjectType, typename std::enable_if<
  916. std::is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value and
  917. std::is_constructible<basic_json, typename CompatibleObjectType::mapped_type>::value, int>::type = 0>
  918. basic_json(const CompatibleObjectType& val)
  919. : m_type(value_t::object)
  920. {
  921. using std::begin;
  922. using std::end;
  923. m_value.object = create<object_t>(begin(val), end(val));
  924. assert_invariant();
  925. }
  926. /*!
  927. @brief create an array (explicit)
  928. Create an array JSON value with a given content.
  929. @param[in] val a value for the array
  930. @complexity Linear in the size of the passed @a val.
  931. @throw std::bad_alloc if allocation for array value fails
  932. @liveexample{The following code shows the constructor with an @ref array_t
  933. parameter.,basic_json__array_t}
  934. @sa @ref basic_json(const CompatibleArrayType&) -- create an array value
  935. from a compatible STL containers
  936. @since version 1.0.0
  937. */
  938. basic_json(const array_t& val)
  939. : m_type(value_t::array), m_value(val)
  940. {
  941. assert_invariant();
  942. }
  943. /*!
  944. @brief create an array (implicit)
  945. Create an array JSON value with a given content. This constructor allows
  946. any type @a CompatibleArrayType that can be used to construct values of
  947. type @ref array_t.
  948. @tparam CompatibleArrayType An object type whose `value_type` is
  949. compatible to @ref array_t. Examples include `std::vector`, `std::deque`,
  950. `std::list`, `std::forward_list`, `std::array`, `std::set`,
  951. `std::unordered_set`, `std::multiset`, and `unordered_multiset` with a
  952. `value_type` from which a @ref basic_json value can be constructed.
  953. @param[in] val a value for the array
  954. @complexity Linear in the size of the passed @a val.
  955. @throw std::bad_alloc if allocation for array value fails
  956. @liveexample{The following code shows the constructor with several
  957. compatible array type parameters.,basic_json__CompatibleArrayType}
  958. @sa @ref basic_json(const array_t&) -- create an array value
  959. @since version 1.0.0
  960. */
  961. template<class CompatibleArrayType, typename std::enable_if<
  962. not std::is_same<CompatibleArrayType, typename basic_json_t::iterator>::value and
  963. not std::is_same<CompatibleArrayType, typename basic_json_t::const_iterator>::value and
  964. not std::is_same<CompatibleArrayType, typename basic_json_t::reverse_iterator>::value and
  965. not std::is_same<CompatibleArrayType, typename basic_json_t::const_reverse_iterator>::value and
  966. not std::is_same<CompatibleArrayType, typename array_t::iterator>::value and
  967. not std::is_same<CompatibleArrayType, typename array_t::const_iterator>::value and
  968. std::is_constructible<basic_json, typename CompatibleArrayType::value_type>::value, int>::type = 0>
  969. basic_json(const CompatibleArrayType& val)
  970. : m_type(value_t::array)
  971. {
  972. using std::begin;
  973. using std::end;
  974. m_value.array = create<array_t>(begin(val), end(val));
  975. assert_invariant();
  976. }
  977. /*!
  978. @brief create a string (explicit)
  979. Create an string JSON value with a given content.
  980. @param[in] val a value for the string
  981. @complexity Linear in the size of the passed @a val.
  982. @throw std::bad_alloc if allocation for string value fails
  983. @liveexample{The following code shows the constructor with an @ref
  984. string_t parameter.,basic_json__string_t}
  985. @sa @ref basic_json(const typename string_t::value_type*) -- create a
  986. string value from a character pointer
  987. @sa @ref basic_json(const CompatibleStringType&) -- create a string value
  988. from a compatible string container
  989. @since version 1.0.0
  990. */
  991. basic_json(const string_t& val)
  992. : m_type(value_t::string), m_value(val)
  993. {
  994. assert_invariant();
  995. }
  996. /*!
  997. @brief create a string (explicit)
  998. Create a string JSON value with a given content.
  999. @param[in] val a literal value for the string
  1000. @complexity Linear in the size of the passed @a val.
  1001. @throw std::bad_alloc if allocation for string value fails
  1002. @liveexample{The following code shows the constructor with string literal
  1003. parameter.,basic_json__string_t_value_type}
  1004. @sa @ref basic_json(const string_t&) -- create a string value
  1005. @sa @ref basic_json(const CompatibleStringType&) -- create a string value
  1006. from a compatible string container
  1007. @since version 1.0.0
  1008. */
  1009. basic_json(const typename string_t::value_type* val)
  1010. : basic_json(string_t(val))
  1011. {
  1012. assert_invariant();
  1013. }
  1014. /*!
  1015. @brief create a string (implicit)
  1016. Create a string JSON value with a given content.
  1017. @param[in] val a value for the string
  1018. @tparam CompatibleStringType an string type which is compatible to @ref
  1019. string_t, for instance `std::string`.
  1020. @complexity Linear in the size of the passed @a val.
  1021. @throw std::bad_alloc if allocation for string value fails
  1022. @liveexample{The following code shows the construction of a string value
  1023. from a compatible type.,basic_json__CompatibleStringType}
  1024. @sa @ref basic_json(const string_t&) -- create a string value
  1025. @sa @ref basic_json(const typename string_t::value_type*) -- create a
  1026. string value from a character pointer
  1027. @since version 1.0.0
  1028. */
  1029. template<class CompatibleStringType, typename std::enable_if<
  1030. std::is_constructible<string_t, CompatibleStringType>::value, int>::type = 0>
  1031. basic_json(const CompatibleStringType& val)
  1032. : basic_json(string_t(val))
  1033. {
  1034. assert_invariant();
  1035. }
  1036. /*!
  1037. @brief create a boolean (explicit)
  1038. Creates a JSON boolean type from a given value.
  1039. @param[in] val a boolean value to store
  1040. @complexity Constant.
  1041. @liveexample{The example below demonstrates boolean
  1042. values.,basic_json__boolean_t}
  1043. @since version 1.0.0
  1044. */
  1045. basic_json(boolean_t val) noexcept
  1046. : m_type(value_t::boolean), m_value(val)
  1047. {
  1048. assert_invariant();
  1049. }
  1050. /*!
  1051. @brief create an integer number (explicit)
  1052. Create an integer number JSON value with a given content.
  1053. @tparam T A helper type to remove this function via SFINAE in case @ref
  1054. number_integer_t is the same as `int`. In this case, this constructor
  1055. would have the same signature as @ref basic_json(const int value). Note
  1056. the helper type @a T is not visible in this constructor's interface.
  1057. @param[in] val an integer to create a JSON number from
  1058. @complexity Constant.
  1059. @liveexample{The example below shows the construction of an integer
  1060. number value.,basic_json__number_integer_t}
  1061. @sa @ref basic_json(const int) -- create a number value (integer)
  1062. @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
  1063. value (integer) from a compatible number type
  1064. @since version 1.0.0
  1065. */
  1066. template<typename T, typename std::enable_if<
  1067. not (std::is_same<T, int>::value) and
  1068. std::is_same<T, number_integer_t>::value, int>::type = 0>
  1069. basic_json(const number_integer_t val) noexcept
  1070. : m_type(value_t::number_integer), m_value(val)
  1071. {
  1072. assert_invariant();
  1073. }
  1074. /*!
  1075. @brief create an integer number from an enum type (explicit)
  1076. Create an integer number JSON value with a given content.
  1077. @param[in] val an integer to create a JSON number from
  1078. @note This constructor allows to pass enums directly to a constructor. As
  1079. C++ has no way of specifying the type of an anonymous enum explicitly, we
  1080. can only rely on the fact that such values implicitly convert to int. As
  1081. int may already be the same type of number_integer_t, we may need to
  1082. switch off the constructor @ref basic_json(const number_integer_t).
  1083. @complexity Constant.
  1084. @liveexample{The example below shows the construction of an integer
  1085. number value from an anonymous enum.,basic_json__const_int}
  1086. @sa @ref basic_json(const number_integer_t) -- create a number value
  1087. (integer)
  1088. @sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
  1089. value (integer) from a compatible number type
  1090. @since version 1.0.0
  1091. */
  1092. basic_json(const int val) noexcept
  1093. : m_type(value_t::number_integer),
  1094. m_value(static_cast<number_integer_t>(val))
  1095. {
  1096. assert_invariant();
  1097. }
  1098. /*!
  1099. @brief create an integer number (implicit)
  1100. Create an integer number JSON value with a given content. This constructor
  1101. allows any type @a CompatibleNumberIntegerType that can be used to
  1102. construct values of type @ref number_integer_t.
  1103. @tparam CompatibleNumberIntegerType An integer type which is compatible to
  1104. @ref number_integer_t. Examples include the types `int`, `int32_t`,
  1105. `long`, and `short`.
  1106. @param[in] val an integer to create a JSON number from
  1107. @complexity Constant.
  1108. @liveexample{The example below shows the construction of several integer
  1109. number values from compatible
  1110. types.,basic_json__CompatibleIntegerNumberType}
  1111. @sa @ref basic_json(const number_integer_t) -- create a number value
  1112. (integer)
  1113. @sa @ref basic_json(const int) -- create a number value (integer)
  1114. @since version 1.0.0
  1115. */
  1116. template<typename CompatibleNumberIntegerType, typename std::enable_if<
  1117. std::is_constructible<number_integer_t, CompatibleNumberIntegerType>::value and
  1118. std::numeric_limits<CompatibleNumberIntegerType>::is_integer and
  1119. std::numeric_limits<CompatibleNumberIntegerType>::is_signed,
  1120. CompatibleNumberIntegerType>::type = 0>
  1121. basic_json(const CompatibleNumberIntegerType val) noexcept
  1122. : m_type(value_t::number_integer),
  1123. m_value(static_cast<number_integer_t>(val))
  1124. {
  1125. assert_invariant();
  1126. }
  1127. /*!
  1128. @brief create an unsigned integer number (explicit)
  1129. Create an unsigned integer number JSON value with a given content.
  1130. @tparam T helper type to compare number_unsigned_t and unsigned int (not
  1131. visible in) the interface.
  1132. @param[in] val an integer to create a JSON number from
  1133. @complexity Constant.
  1134. @sa @ref basic_json(const CompatibleNumberUnsignedType) -- create a number
  1135. value (unsigned integer) from a compatible number type
  1136. @since version 2.0.0
  1137. */
  1138. template<typename T, typename std::enable_if<
  1139. not (std::is_same<T, int>::value) and
  1140. std::is_same<T, number_unsigned_t>::value, int>::type = 0>
  1141. basic_json(const number_unsigned_t val) noexcept
  1142. : m_type(value_t::number_unsigned), m_value(val)
  1143. {
  1144. assert_invariant();
  1145. }
  1146. /*!
  1147. @brief create an unsigned number (implicit)
  1148. Create an unsigned number JSON value with a given content. This
  1149. constructor allows any type @a CompatibleNumberUnsignedType that can be
  1150. used to construct values of type @ref number_unsigned_t.
  1151. @tparam CompatibleNumberUnsignedType An integer type which is compatible
  1152. to @ref number_unsigned_t. Examples may include the types `unsigned int`,
  1153. `uint32_t`, or `unsigned short`.
  1154. @param[in] val an unsigned integer to create a JSON number from
  1155. @complexity Constant.
  1156. @sa @ref basic_json(const number_unsigned_t) -- create a number value
  1157. (unsigned)
  1158. @since version 2.0.0
  1159. */
  1160. template<typename CompatibleNumberUnsignedType, typename std::enable_if <
  1161. std::is_constructible<number_unsigned_t, CompatibleNumberUnsignedType>::value and
  1162. std::numeric_limits<CompatibleNumberUnsignedType>::is_integer and
  1163. not std::numeric_limits<CompatibleNumberUnsignedType>::is_signed,
  1164. CompatibleNumberUnsignedType>::type = 0>
  1165. basic_json(const CompatibleNumberUnsignedType val) noexcept
  1166. : m_type(value_t::number_unsigned),
  1167. m_value(static_cast<number_unsigned_t>(val))
  1168. {
  1169. assert_invariant();
  1170. }
  1171. /*!
  1172. @brief create a floating-point number (explicit)
  1173. Create a floating-point number JSON value with a given content.
  1174. @param[in] val a floating-point value to create a JSON number from
  1175. @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
  1176. disallows NaN values:
  1177. > Numeric values that cannot be represented in the grammar below (such as
  1178. > Infinity and NaN) are not permitted.
  1179. In case the parameter @a val is not a number, a JSON null value is created
  1180. instead.
  1181. @complexity Constant.
  1182. @liveexample{The following example creates several floating-point
  1183. values.,basic_json__number_float_t}
  1184. @sa @ref basic_json(const CompatibleNumberFloatType) -- create a number
  1185. value (floating-point) from a compatible number type
  1186. @since version 1.0.0
  1187. */
  1188. basic_json(const number_float_t val) noexcept
  1189. : m_type(value_t::number_float), m_value(val)
  1190. {
  1191. // replace infinity and NAN by null
  1192. if (not std::isfinite(val))
  1193. {
  1194. m_type = value_t::null;
  1195. m_value = json_value();
  1196. }
  1197. assert_invariant();
  1198. }
  1199. /*!
  1200. @brief create an floating-point number (implicit)
  1201. Create an floating-point number JSON value with a given content. This
  1202. constructor allows any type @a CompatibleNumberFloatType that can be used
  1203. to construct values of type @ref number_float_t.
  1204. @tparam CompatibleNumberFloatType A floating-point type which is
  1205. compatible to @ref number_float_t. Examples may include the types `float`
  1206. or `double`.
  1207. @param[in] val a floating-point to create a JSON number from
  1208. @note [RFC 7159](http://www.rfc-editor.org/rfc/rfc7159.txt), section 6
  1209. disallows NaN values:
  1210. > Numeric values that cannot be represented in the grammar below (such as
  1211. > Infinity and NaN) are not permitted.
  1212. In case the parameter @a val is not a number, a JSON null value is
  1213. created instead.
  1214. @complexity Constant.
  1215. @liveexample{The example below shows the construction of several
  1216. floating-point number values from compatible
  1217. types.,basic_json__CompatibleNumberFloatType}
  1218. @sa @ref basic_json(const number_float_t) -- create a number value
  1219. (floating-point)
  1220. @since version 1.0.0
  1221. */
  1222. template<typename CompatibleNumberFloatType, typename = typename std::enable_if<
  1223. std::is_constructible<number_float_t, CompatibleNumberFloatType>::value and
  1224. std::is_floating_point<CompatibleNumberFloatType>::value>::type>
  1225. basic_json(const CompatibleNumberFloatType val) noexcept
  1226. : basic_json(number_float_t(val))
  1227. {
  1228. assert_invariant();
  1229. }
  1230. /*!
  1231. @brief create a container (array or object) from an initializer list
  1232. Creates a JSON value of type array or object from the passed initializer
  1233. list @a init. In case @a type_deduction is `true` (default), the type of
  1234. the JSON value to be created is deducted from the initializer list @a init
  1235. according to the following rules:
  1236. 1. If the list is empty, an empty JSON object value `{}` is created.
  1237. 2. If the list consists of pairs whose first element is a string, a JSON
  1238. object value is created where the first elements of the pairs are
  1239. treated as keys and the second elements are as values.
  1240. 3. In all other cases, an array is created.
  1241. The rules aim to create the best fit between a C++ initializer list and
  1242. JSON values. The rationale is as follows:
  1243. 1. The empty initializer list is written as `{}` which is exactly an empty
  1244. JSON object.
  1245. 2. C++ has now way of describing mapped types other than to list a list of
  1246. pairs. As JSON requires that keys must be of type string, rule 2 is the
  1247. weakest constraint one can pose on initializer lists to interpret them
  1248. as an object.
  1249. 3. In all other cases, the initializer list could not be interpreted as
  1250. JSON object type, so interpreting it as JSON array type is safe.
  1251. With the rules described above, the following JSON values cannot be
  1252. expressed by an initializer list:
  1253. - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
  1254. with an empty initializer list in this case
  1255. - arrays whose elements satisfy rule 2: use @ref
  1256. array(std::initializer_list<basic_json>) with the same initializer list
  1257. in this case
  1258. @note When used without parentheses around an empty initializer list, @ref
  1259. basic_json() is called instead of this function, yielding the JSON null
  1260. value.
  1261. @param[in] init initializer list with JSON values
  1262. @param[in] type_deduction internal parameter; when set to `true`, the type
  1263. of the JSON value is deducted from the initializer list @a init; when set
  1264. to `false`, the type provided via @a manual_type is forced. This mode is
  1265. used by the functions @ref array(std::initializer_list<basic_json>) and
  1266. @ref object(std::initializer_list<basic_json>).
  1267. @param[in] manual_type internal parameter; when @a type_deduction is set
  1268. to `false`, the created JSON value will use the provided type (only @ref
  1269. value_t::array and @ref value_t::object are valid); when @a type_deduction
  1270. is set to `true`, this parameter has no effect
  1271. @throw std::domain_error if @a type_deduction is `false`, @a manual_type
  1272. is `value_t::object`, but @a init contains an element which is not a pair
  1273. whose first element is a string; example: `"cannot create object from
  1274. initializer list"`
  1275. @complexity Linear in the size of the initializer list @a init.
  1276. @liveexample{The example below shows how JSON values are created from
  1277. initializer lists.,basic_json__list_init_t}
  1278. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  1279. value from an initializer list
  1280. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  1281. value from an initializer list
  1282. @since version 1.0.0
  1283. */
  1284. basic_json(std::initializer_list<basic_json> init,
  1285. bool type_deduction = true,
  1286. value_t manual_type = value_t::array)
  1287. {
  1288. // check if each element is an array with two elements whose first
  1289. // element is a string
  1290. bool is_an_object = std::all_of(init.begin(), init.end(),
  1291. [](const basic_json & element)
  1292. {
  1293. return element.is_array() and element.size() == 2 and element[0].is_string();
  1294. });
  1295. // adjust type if type deduction is not wanted
  1296. if (not type_deduction)
  1297. {
  1298. // if array is wanted, do not create an object though possible
  1299. if (manual_type == value_t::array)
  1300. {
  1301. is_an_object = false;
  1302. }
  1303. // if object is wanted but impossible, throw an exception
  1304. if (manual_type == value_t::object and not is_an_object)
  1305. {
  1306. throw std::domain_error("cannot create object from initializer list");
  1307. }
  1308. }
  1309. if (is_an_object)
  1310. {
  1311. // the initializer list is a list of pairs -> create object
  1312. m_type = value_t::object;
  1313. m_value = value_t::object;
  1314. std::for_each(init.begin(), init.end(), [this](const basic_json & element)
  1315. {
  1316. m_value.object->emplace(*(element[0].m_value.string), element[1]);
  1317. });
  1318. }
  1319. else
  1320. {
  1321. // the initializer list describes an array -> create array
  1322. m_type = value_t::array;
  1323. m_value.array = create<array_t>(init);
  1324. }
  1325. assert_invariant();
  1326. }
  1327. /*!
  1328. @brief explicitly create an array from an initializer list
  1329. Creates a JSON array value from a given initializer list. That is, given a
  1330. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  1331. initializer list is empty, the empty array `[]` is created.
  1332. @note This function is only needed to express two edge cases that cannot
  1333. be realized with the initializer list constructor (@ref
  1334. basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
  1335. are:
  1336. 1. creating an array whose elements are all pairs whose first element is a
  1337. string -- in this case, the initializer list constructor would create an
  1338. object, taking the first elements as keys
  1339. 2. creating an empty array -- passing the empty initializer list to the
  1340. initializer list constructor yields an empty object
  1341. @param[in] init initializer list with JSON values to create an array from
  1342. (optional)
  1343. @return JSON array value
  1344. @complexity Linear in the size of @a init.
  1345. @liveexample{The following code shows an example for the `array`
  1346. function.,array}
  1347. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  1348. create a JSON value from an initializer list
  1349. @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
  1350. value from an initializer list
  1351. @since version 1.0.0
  1352. */
  1353. static basic_json array(std::initializer_list<basic_json> init =
  1354. std::initializer_list<basic_json>())
  1355. {
  1356. return basic_json(init, false, value_t::array);
  1357. }
  1358. /*!
  1359. @brief explicitly create an object from an initializer list
  1360. Creates a JSON object value from a given initializer list. The initializer
  1361. lists elements must be pairs, and their first elements must be strings. If
  1362. the initializer list is empty, the empty object `{}` is created.
  1363. @note This function is only added for symmetry reasons. In contrast to the
  1364. related function @ref array(std::initializer_list<basic_json>), there are
  1365. no cases which can only be expressed by this function. That is, any
  1366. initializer list @a init can also be passed to the initializer list
  1367. constructor @ref basic_json(std::initializer_list<basic_json>, bool,
  1368. value_t).
  1369. @param[in] init initializer list to create an object from (optional)
  1370. @return JSON object value
  1371. @throw std::domain_error if @a init is not a pair whose first elements are
  1372. strings; thrown by
  1373. @ref basic_json(std::initializer_list<basic_json>, bool, value_t)
  1374. @complexity Linear in the size of @a init.
  1375. @liveexample{The following code shows an example for the `object`
  1376. function.,object}
  1377. @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
  1378. create a JSON value from an initializer list
  1379. @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
  1380. value from an initializer list
  1381. @since version 1.0.0
  1382. */
  1383. static basic_json object(std::initializer_list<basic_json> init =
  1384. std::initializer_list<basic_json>())
  1385. {
  1386. return basic_json(init, false, value_t::object);
  1387. }
  1388. /*!
  1389. @brief construct an array with count copies of given value
  1390. Constructs a JSON array value by creating @a cnt copies of a passed value.
  1391. In case @a cnt is `0`, an empty array is created. As postcondition,
  1392. `std::distance(begin(),end()) == cnt` holds.
  1393. @param[in] cnt the number of JSON copies of @a val to create
  1394. @param[in] val the JSON value to copy
  1395. @complexity Linear in @a cnt.
  1396. @liveexample{The following code shows examples for the @ref
  1397. basic_json(size_type\, const basic_json&)
  1398. constructor.,basic_json__size_type_basic_json}
  1399. @since version 1.0.0
  1400. */
  1401. basic_json(size_type cnt, const basic_json& val)
  1402. : m_type(value_t::array)
  1403. {
  1404. m_value.array = create<array_t>(cnt, val);
  1405. assert_invariant();
  1406. }
  1407. /*!
  1408. @brief construct a JSON container given an iterator range
  1409. Constructs the JSON value with the contents of the range `[first, last)`.
  1410. The semantics depends on the different types a JSON value can have:
  1411. - In case of primitive types (number, boolean, or string), @a first must
  1412. be `begin()` and @a last must be `end()`. In this case, the value is
  1413. copied. Otherwise, std::out_of_range is thrown.
  1414. - In case of structured types (array, object), the constructor behaves as
  1415. similar versions for `std::vector`.
  1416. - In case of a null type, std::domain_error is thrown.
  1417. @tparam InputIT an input iterator type (@ref iterator or @ref
  1418. const_iterator)
  1419. @param[in] first begin of the range to copy from (included)
  1420. @param[in] last end of the range to copy from (excluded)
  1421. @pre Iterators @a first and @a last must be initialized. **This
  1422. precondition is enforced with an assertion.**
  1423. @throw std::domain_error if iterators are not compatible; that is, do not
  1424. belong to the same JSON value; example: `"iterators are not compatible"`
  1425. @throw std::out_of_range if iterators are for a primitive type (number,
  1426. boolean, or string) where an out of range error can be detected easily;
  1427. example: `"iterators out of range"`
  1428. @throw std::bad_alloc if allocation for object, array, or string fails
  1429. @throw std::domain_error if called with a null value; example: `"cannot
  1430. use construct with iterators from null"`
  1431. @complexity Linear in distance between @a first and @a last.
  1432. @liveexample{The example below shows several ways to create JSON values by
  1433. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  1434. @since version 1.0.0
  1435. */
  1436. template<class InputIT, typename std::enable_if<
  1437. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  1438. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  1439. basic_json(InputIT first, InputIT last)
  1440. {
  1441. assert(first.m_object != nullptr);
  1442. assert(last.m_object != nullptr);
  1443. // make sure iterator fits the current value
  1444. if (first.m_object != last.m_object)
  1445. {
  1446. throw std::domain_error("iterators are not compatible");
  1447. }
  1448. // copy type from first iterator
  1449. m_type = first.m_object->m_type;
  1450. // check if iterator range is complete for primitive values
  1451. switch (m_type)
  1452. {
  1453. case value_t::boolean:
  1454. case value_t::number_float:
  1455. case value_t::number_integer:
  1456. case value_t::number_unsigned:
  1457. case value_t::string:
  1458. {
  1459. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  1460. {
  1461. throw std::out_of_range("iterators out of range");
  1462. }
  1463. break;
  1464. }
  1465. default:
  1466. {
  1467. break;
  1468. }
  1469. }
  1470. switch (m_type)
  1471. {
  1472. case value_t::number_integer:
  1473. {
  1474. m_value.number_integer = first.m_object->m_value.number_integer;
  1475. break;
  1476. }
  1477. case value_t::number_unsigned:
  1478. {
  1479. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  1480. break;
  1481. }
  1482. case value_t::number_float:
  1483. {
  1484. m_value.number_float = first.m_object->m_value.number_float;
  1485. break;
  1486. }
  1487. case value_t::boolean:
  1488. {
  1489. m_value.boolean = first.m_object->m_value.boolean;
  1490. break;
  1491. }
  1492. case value_t::string:
  1493. {
  1494. m_value = *first.m_object->m_value.string;
  1495. break;
  1496. }
  1497. case value_t::object:
  1498. {
  1499. m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator);
  1500. break;
  1501. }
  1502. case value_t::array:
  1503. {
  1504. m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator);
  1505. break;
  1506. }
  1507. default:
  1508. {
  1509. throw std::domain_error("cannot use construct with iterators from " + first.m_object->type_name());
  1510. }
  1511. }
  1512. assert_invariant();
  1513. }
  1514. /*!
  1515. @brief construct a JSON value given an input stream
  1516. @param[in,out] i stream to read a serialized JSON value from
  1517. @param[in] cb a parser callback function of type @ref parser_callback_t
  1518. which is used to control the deserialization by filtering unwanted values
  1519. (optional)
  1520. @complexity Linear in the length of the input. The parser is a predictive
  1521. LL(1) parser. The complexity can be higher if the parser callback function
  1522. @a cb has a super-linear complexity.
  1523. @note A UTF-8 byte order mark is silently ignored.
  1524. @deprecated This constructor is deprecated and will be removed in version
  1525. 3.0.0 to unify the interface of the library. Deserialization will be
  1526. done by stream operators or by calling one of the `parse` functions,
  1527. e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls
  1528. like `json j(i);` for an input stream @a i need to be replaced by
  1529. `json j = json::parse(i);`. See the example below.
  1530. @liveexample{The example below demonstrates constructing a JSON value from
  1531. a `std::stringstream` with and without callback
  1532. function.,basic_json__istream}
  1533. @since version 2.0.0, deprecated in version 2.0.3, to be removed in
  1534. version 3.0.0
  1535. */
  1536. JSON_DEPRECATED
  1537. explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)
  1538. {
  1539. *this = parser(i, cb).parse();
  1540. assert_invariant();
  1541. }
  1542. ///////////////////////////////////////
  1543. // other constructors and destructor //
  1544. ///////////////////////////////////////
  1545. /*!
  1546. @brief copy constructor
  1547. Creates a copy of a given JSON value.
  1548. @param[in] other the JSON value to copy
  1549. @complexity Linear in the size of @a other.
  1550. @requirement This function helps `basic_json` satisfying the
  1551. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1552. requirements:
  1553. - The complexity is linear.
  1554. - As postcondition, it holds: `other == basic_json(other)`.
  1555. @throw std::bad_alloc if allocation for object, array, or string fails.
  1556. @liveexample{The following code shows an example for the copy
  1557. constructor.,basic_json__basic_json}
  1558. @since version 1.0.0
  1559. */
  1560. basic_json(const basic_json& other)
  1561. : m_type(other.m_type)
  1562. {
  1563. // check of passed value is valid
  1564. other.assert_invariant();
  1565. switch (m_type)
  1566. {
  1567. case value_t::object:
  1568. {
  1569. m_value = *other.m_value.object;
  1570. break;
  1571. }
  1572. case value_t::array:
  1573. {
  1574. m_value = *other.m_value.array;
  1575. break;
  1576. }
  1577. case value_t::string:
  1578. {
  1579. m_value = *other.m_value.string;
  1580. break;
  1581. }
  1582. case value_t::boolean:
  1583. {
  1584. m_value = other.m_value.boolean;
  1585. break;
  1586. }
  1587. case value_t::number_integer:
  1588. {
  1589. m_value = other.m_value.number_integer;
  1590. break;
  1591. }
  1592. case value_t::number_unsigned:
  1593. {
  1594. m_value = other.m_value.number_unsigned;
  1595. break;
  1596. }
  1597. case value_t::number_float:
  1598. {
  1599. m_value = other.m_value.number_float;
  1600. break;
  1601. }
  1602. default:
  1603. {
  1604. break;
  1605. }
  1606. }
  1607. assert_invariant();
  1608. }
  1609. /*!
  1610. @brief move constructor
  1611. Move constructor. Constructs a JSON value with the contents of the given
  1612. value @a other using move semantics. It "steals" the resources from @a
  1613. other and leaves it as JSON null value.
  1614. @param[in,out] other value to move to this object
  1615. @post @a other is a JSON null value
  1616. @complexity Constant.
  1617. @liveexample{The code below shows the move constructor explicitly called
  1618. via std::move.,basic_json__moveconstructor}
  1619. @since version 1.0.0
  1620. */
  1621. basic_json(basic_json&& other) noexcept
  1622. : m_type(std::move(other.m_type)),
  1623. m_value(std::move(other.m_value))
  1624. {
  1625. // check that passed value is valid
  1626. other.assert_invariant();
  1627. // invalidate payload
  1628. other.m_type = value_t::null;
  1629. other.m_value = {};
  1630. assert_invariant();
  1631. }
  1632. /*!
  1633. @brief copy assignment
  1634. Copy assignment operator. Copies a JSON value via the "copy and swap"
  1635. strategy: It is expressed in terms of the copy constructor, destructor,
  1636. and the swap() member function.
  1637. @param[in] other value to copy from
  1638. @complexity Linear.
  1639. @requirement This function helps `basic_json` satisfying the
  1640. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1641. requirements:
  1642. - The complexity is linear.
  1643. @liveexample{The code below shows and example for the copy assignment. It
  1644. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  1645. copy of `a` (which is the null value after the swap) is
  1646. destroyed.,basic_json__copyassignment}
  1647. @since version 1.0.0
  1648. */
  1649. reference& operator=(basic_json other) noexcept (
  1650. std::is_nothrow_move_constructible<value_t>::value and
  1651. std::is_nothrow_move_assignable<value_t>::value and
  1652. std::is_nothrow_move_constructible<json_value>::value and
  1653. std::is_nothrow_move_assignable<json_value>::value
  1654. )
  1655. {
  1656. // check that passed value is valid
  1657. other.assert_invariant();
  1658. using std::swap;
  1659. swap(m_type, other.m_type);
  1660. swap(m_value, other.m_value);
  1661. assert_invariant();
  1662. return *this;
  1663. }
  1664. /*!
  1665. @brief destructor
  1666. Destroys the JSON value and frees all allocated memory.
  1667. @complexity Linear.
  1668. @requirement This function helps `basic_json` satisfying the
  1669. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  1670. requirements:
  1671. - The complexity is linear.
  1672. - All stored elements are destroyed and all memory is freed.
  1673. @since version 1.0.0
  1674. */
  1675. ~basic_json()
  1676. {
  1677. assert_invariant();
  1678. switch (m_type)
  1679. {
  1680. case value_t::object:
  1681. {
  1682. AllocatorType<object_t> alloc;
  1683. alloc.destroy(m_value.object);
  1684. alloc.deallocate(m_value.object, 1);
  1685. break;
  1686. }
  1687. case value_t::array:
  1688. {
  1689. AllocatorType<array_t> alloc;
  1690. alloc.destroy(m_value.array);
  1691. alloc.deallocate(m_value.array, 1);
  1692. break;
  1693. }
  1694. case value_t::string:
  1695. {
  1696. AllocatorType<string_t> alloc;
  1697. alloc.destroy(m_value.string);
  1698. alloc.deallocate(m_value.string, 1);
  1699. break;
  1700. }
  1701. default:
  1702. {
  1703. // all other types need no specific destructor
  1704. break;
  1705. }
  1706. }
  1707. }
  1708. /// @}
  1709. public:
  1710. ///////////////////////
  1711. // object inspection //
  1712. ///////////////////////
  1713. /// @name object inspection
  1714. /// Functions to inspect the type of a JSON value.
  1715. /// @{
  1716. /*!
  1717. @brief serialization
  1718. Serialization function for JSON values. The function tries to mimic
  1719. Python's `json.dumps()` function, and currently supports its @a indent
  1720. parameter.
  1721. @param[in] indent If indent is nonnegative, then array elements and object
  1722. members will be pretty-printed with that indent level. An indent level of
  1723. `0` will only insert newlines. `-1` (the default) selects the most compact
  1724. representation.
  1725. @return string containing the serialization of the JSON value
  1726. @complexity Linear.
  1727. @liveexample{The following example shows the effect of different @a indent
  1728. parameters to the result of the serialization.,dump}
  1729. @see https://docs.python.org/2/library/json.html#json.dump
  1730. @since version 1.0.0
  1731. */
  1732. string_t dump(const int indent = -1) const
  1733. {
  1734. std::stringstream ss;
  1735. // fix locale problems
  1736. const static std::locale loc(std::locale(), new DecimalSeparator);
  1737. ss.imbue(loc);
  1738. // 6, 15 or 16 digits of precision allows round-trip IEEE 754
  1739. // string->float->string, string->double->string or string->long
  1740. // double->string; to be safe, we read this value from
  1741. // std::numeric_limits<number_float_t>::digits10
  1742. ss.precision(std::numeric_limits<double>::digits10);
  1743. if (indent >= 0)
  1744. {
  1745. dump(ss, true, static_cast<unsigned int>(indent));
  1746. }
  1747. else
  1748. {
  1749. dump(ss, false, 0);
  1750. }
  1751. return ss.str();
  1752. }
  1753. /*!
  1754. @brief return the type of the JSON value (explicit)
  1755. Return the type of the JSON value as a value from the @ref value_t
  1756. enumeration.
  1757. @return the type of the JSON value
  1758. @complexity Constant.
  1759. @exceptionsafety No-throw guarantee: this member function never throws
  1760. exceptions.
  1761. @liveexample{The following code exemplifies `type()` for all JSON
  1762. types.,type}
  1763. @since version 1.0.0
  1764. */
  1765. constexpr value_t type() const noexcept
  1766. {
  1767. return m_type;
  1768. }
  1769. /*!
  1770. @brief return whether type is primitive
  1771. This function returns true iff the JSON type is primitive (string, number,
  1772. boolean, or null).
  1773. @return `true` if type is primitive (string, number, boolean, or null),
  1774. `false` otherwise.
  1775. @complexity Constant.
  1776. @exceptionsafety No-throw guarantee: this member function never throws
  1777. exceptions.
  1778. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  1779. types.,is_primitive}
  1780. @sa @ref is_structured() -- returns whether JSON value is structured
  1781. @sa @ref is_null() -- returns whether JSON value is `null`
  1782. @sa @ref is_string() -- returns whether JSON value is a string
  1783. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  1784. @sa @ref is_number() -- returns whether JSON value is a number
  1785. @since version 1.0.0
  1786. */
  1787. constexpr bool is_primitive() const noexcept
  1788. {
  1789. return is_null() or is_string() or is_boolean() or is_number();
  1790. }
  1791. /*!
  1792. @brief return whether type is structured
  1793. This function returns true iff the JSON type is structured (array or
  1794. object).
  1795. @return `true` if type is structured (array or object), `false` otherwise.
  1796. @complexity Constant.
  1797. @exceptionsafety No-throw guarantee: this member function never throws
  1798. exceptions.
  1799. @liveexample{The following code exemplifies `is_structured()` for all JSON
  1800. types.,is_structured}
  1801. @sa @ref is_primitive() -- returns whether value is primitive
  1802. @sa @ref is_array() -- returns whether value is an array
  1803. @sa @ref is_object() -- returns whether value is an object
  1804. @since version 1.0.0
  1805. */
  1806. constexpr bool is_structured() const noexcept
  1807. {
  1808. return is_array() or is_object();
  1809. }
  1810. /*!
  1811. @brief return whether value is null
  1812. This function returns true iff the JSON value is null.
  1813. @return `true` if type is null, `false` otherwise.
  1814. @complexity Constant.
  1815. @exceptionsafety No-throw guarantee: this member function never throws
  1816. exceptions.
  1817. @liveexample{The following code exemplifies `is_null()` for all JSON
  1818. types.,is_null}
  1819. @since version 1.0.0
  1820. */
  1821. constexpr bool is_null() const noexcept
  1822. {
  1823. return m_type == value_t::null;
  1824. }
  1825. /*!
  1826. @brief return whether value is a boolean
  1827. This function returns true iff the JSON value is a boolean.
  1828. @return `true` if type is boolean, `false` otherwise.
  1829. @complexity Constant.
  1830. @exceptionsafety No-throw guarantee: this member function never throws
  1831. exceptions.
  1832. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  1833. types.,is_boolean}
  1834. @since version 1.0.0
  1835. */
  1836. constexpr bool is_boolean() const noexcept
  1837. {
  1838. return m_type == value_t::boolean;
  1839. }
  1840. /*!
  1841. @brief return whether value is a number
  1842. This function returns true iff the JSON value is a number. This includes
  1843. both integer and floating-point values.
  1844. @return `true` if type is number (regardless whether integer, unsigned
  1845. integer or floating-type), `false` otherwise.
  1846. @complexity Constant.
  1847. @exceptionsafety No-throw guarantee: this member function never throws
  1848. exceptions.
  1849. @liveexample{The following code exemplifies `is_number()` for all JSON
  1850. types.,is_number}
  1851. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  1852. integer number
  1853. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1854. number
  1855. @sa @ref is_number_float() -- check if value is a floating-point number
  1856. @since version 1.0.0
  1857. */
  1858. constexpr bool is_number() const noexcept
  1859. {
  1860. return is_number_integer() or is_number_float();
  1861. }
  1862. /*!
  1863. @brief return whether value is an integer number
  1864. This function returns true iff the JSON value is an integer or unsigned
  1865. integer number. This excludes floating-point values.
  1866. @return `true` if type is an integer or unsigned integer number, `false`
  1867. otherwise.
  1868. @complexity Constant.
  1869. @exceptionsafety No-throw guarantee: this member function never throws
  1870. exceptions.
  1871. @liveexample{The following code exemplifies `is_number_integer()` for all
  1872. JSON types.,is_number_integer}
  1873. @sa @ref is_number() -- check if value is a number
  1874. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1875. number
  1876. @sa @ref is_number_float() -- check if value is a floating-point number
  1877. @since version 1.0.0
  1878. */
  1879. constexpr bool is_number_integer() const noexcept
  1880. {
  1881. return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
  1882. }
  1883. /*!
  1884. @brief return whether value is an unsigned integer number
  1885. This function returns true iff the JSON value is an unsigned integer
  1886. number. This excludes floating-point and (signed) integer values.
  1887. @return `true` if type is an unsigned integer number, `false` otherwise.
  1888. @complexity Constant.
  1889. @exceptionsafety No-throw guarantee: this member function never throws
  1890. exceptions.
  1891. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  1892. JSON types.,is_number_unsigned}
  1893. @sa @ref is_number() -- check if value is a number
  1894. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  1895. integer number
  1896. @sa @ref is_number_float() -- check if value is a floating-point number
  1897. @since version 2.0.0
  1898. */
  1899. constexpr bool is_number_unsigned() const noexcept
  1900. {
  1901. return m_type == value_t::number_unsigned;
  1902. }
  1903. /*!
  1904. @brief return whether value is a floating-point number
  1905. This function returns true iff the JSON value is a floating-point number.
  1906. This excludes integer and unsigned integer values.
  1907. @return `true` if type is a floating-point number, `false` otherwise.
  1908. @complexity Constant.
  1909. @exceptionsafety No-throw guarantee: this member function never throws
  1910. exceptions.
  1911. @liveexample{The following code exemplifies `is_number_float()` for all
  1912. JSON types.,is_number_float}
  1913. @sa @ref is_number() -- check if value is number
  1914. @sa @ref is_number_integer() -- check if value is an integer number
  1915. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  1916. number
  1917. @since version 1.0.0
  1918. */
  1919. constexpr bool is_number_float() const noexcept
  1920. {
  1921. return m_type == value_t::number_float;
  1922. }
  1923. /*!
  1924. @brief return whether value is an object
  1925. This function returns true iff the JSON value is an object.
  1926. @return `true` if type is object, `false` otherwise.
  1927. @complexity Constant.
  1928. @exceptionsafety No-throw guarantee: this member function never throws
  1929. exceptions.
  1930. @liveexample{The following code exemplifies `is_object()` for all JSON
  1931. types.,is_object}
  1932. @since version 1.0.0
  1933. */
  1934. constexpr bool is_object() const noexcept
  1935. {
  1936. return m_type == value_t::object;
  1937. }
  1938. /*!
  1939. @brief return whether value is an array
  1940. This function returns true iff the JSON value is an array.
  1941. @return `true` if type is array, `false` otherwise.
  1942. @complexity Constant.
  1943. @exceptionsafety No-throw guarantee: this member function never throws
  1944. exceptions.
  1945. @liveexample{The following code exemplifies `is_array()` for all JSON
  1946. types.,is_array}
  1947. @since version 1.0.0
  1948. */
  1949. constexpr bool is_array() const noexcept
  1950. {
  1951. return m_type == value_t::array;
  1952. }
  1953. /*!
  1954. @brief return whether value is a string
  1955. This function returns true iff the JSON value is a string.
  1956. @return `true` if type is string, `false` otherwise.
  1957. @complexity Constant.
  1958. @exceptionsafety No-throw guarantee: this member function never throws
  1959. exceptions.
  1960. @liveexample{The following code exemplifies `is_string()` for all JSON
  1961. types.,is_string}
  1962. @since version 1.0.0
  1963. */
  1964. constexpr bool is_string() const noexcept
  1965. {
  1966. return m_type == value_t::string;
  1967. }
  1968. /*!
  1969. @brief return whether value is discarded
  1970. This function returns true iff the JSON value was discarded during parsing
  1971. with a callback function (see @ref parser_callback_t).
  1972. @note This function will always be `false` for JSON values after parsing.
  1973. That is, discarded values can only occur during parsing, but will be
  1974. removed when inside a structured value or replaced by null in other cases.
  1975. @return `true` if type is discarded, `false` otherwise.
  1976. @complexity Constant.
  1977. @exceptionsafety No-throw guarantee: this member function never throws
  1978. exceptions.
  1979. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  1980. types.,is_discarded}
  1981. @since version 1.0.0
  1982. */
  1983. constexpr bool is_discarded() const noexcept
  1984. {
  1985. return m_type == value_t::discarded;
  1986. }
  1987. /*!
  1988. @brief return the type of the JSON value (implicit)
  1989. Implicitly return the type of the JSON value as a value from the @ref
  1990. value_t enumeration.
  1991. @return the type of the JSON value
  1992. @complexity Constant.
  1993. @exceptionsafety No-throw guarantee: this member function never throws
  1994. exceptions.
  1995. @liveexample{The following code exemplifies the @ref value_t operator for
  1996. all JSON types.,operator__value_t}
  1997. @since version 1.0.0
  1998. */
  1999. constexpr operator value_t() const noexcept
  2000. {
  2001. return m_type;
  2002. }
  2003. /// @}
  2004. private:
  2005. //////////////////
  2006. // value access //
  2007. //////////////////
  2008. /// get an object (explicit)
  2009. template<class T, typename std::enable_if<
  2010. std::is_convertible<typename object_t::key_type, typename T::key_type>::value and
  2011. std::is_convertible<basic_json_t, typename T::mapped_type>::value, int>::type = 0>
  2012. T get_impl(T*) const
  2013. {
  2014. if (is_object())
  2015. {
  2016. return T(m_value.object->begin(), m_value.object->end());
  2017. }
  2018. else
  2019. {
  2020. throw std::domain_error("type must be object, but is " + type_name());
  2021. }
  2022. }
  2023. /// get an object (explicit)
  2024. object_t get_impl(object_t*) const
  2025. {
  2026. if (is_object())
  2027. {
  2028. return *(m_value.object);
  2029. }
  2030. else
  2031. {
  2032. throw std::domain_error("type must be object, but is " + type_name());
  2033. }
  2034. }
  2035. /// get an array (explicit)
  2036. template<class T, typename std::enable_if<
  2037. std::is_convertible<basic_json_t, typename T::value_type>::value and
  2038. not std::is_same<basic_json_t, typename T::value_type>::value and
  2039. not std::is_arithmetic<T>::value and
  2040. not std::is_convertible<std::string, T>::value and
  2041. not has_mapped_type<T>::value, int>::type = 0>
  2042. T get_impl(T*) const
  2043. {
  2044. if (is_array())
  2045. {
  2046. T to_vector;
  2047. std::transform(m_value.array->begin(), m_value.array->end(),
  2048. std::inserter(to_vector, to_vector.end()), [](basic_json i)
  2049. {
  2050. return i.get<typename T::value_type>();
  2051. });
  2052. return to_vector;
  2053. }
  2054. else
  2055. {
  2056. throw std::domain_error("type must be array, but is " + type_name());
  2057. }
  2058. }
  2059. /// get an array (explicit)
  2060. template<class T, typename std::enable_if<
  2061. std::is_convertible<basic_json_t, T>::value and
  2062. not std::is_same<basic_json_t, T>::value, int>::type = 0>
  2063. std::vector<T> get_impl(std::vector<T>*) const
  2064. {
  2065. if (is_array())
  2066. {
  2067. std::vector<T> to_vector;
  2068. to_vector.reserve(m_value.array->size());
  2069. std::transform(m_value.array->begin(), m_value.array->end(),
  2070. std::inserter(to_vector, to_vector.end()), [](basic_json i)
  2071. {
  2072. return i.get<T>();
  2073. });
  2074. return to_vector;
  2075. }
  2076. else
  2077. {
  2078. throw std::domain_error("type must be array, but is " + type_name());
  2079. }
  2080. }
  2081. /// get an array (explicit)
  2082. template<class T, typename std::enable_if<
  2083. std::is_same<basic_json, typename T::value_type>::value and
  2084. not has_mapped_type<T>::value, int>::type = 0>
  2085. T get_impl(T*) const
  2086. {
  2087. if (is_array())
  2088. {
  2089. return T(m_value.array->begin(), m_value.array->end());
  2090. }
  2091. else
  2092. {
  2093. throw std::domain_error("type must be array, but is " + type_name());
  2094. }
  2095. }
  2096. /// get an array (explicit)
  2097. array_t get_impl(array_t*) const
  2098. {
  2099. if (is_array())
  2100. {
  2101. return *(m_value.array);
  2102. }
  2103. else
  2104. {
  2105. throw std::domain_error("type must be array, but is " + type_name());
  2106. }
  2107. }
  2108. /// get a string (explicit)
  2109. template<typename T, typename std::enable_if<
  2110. std::is_convertible<string_t, T>::value, int>::type = 0>
  2111. T get_impl(T*) const
  2112. {
  2113. if (is_string())
  2114. {
  2115. return *m_value.string;
  2116. }
  2117. else
  2118. {
  2119. throw std::domain_error("type must be string, but is " + type_name());
  2120. }
  2121. }
  2122. /// get a number (explicit)
  2123. template<typename T, typename std::enable_if<
  2124. std::is_arithmetic<T>::value, int>::type = 0>
  2125. T get_impl(T*) const
  2126. {
  2127. switch (m_type)
  2128. {
  2129. case value_t::number_integer:
  2130. {
  2131. return static_cast<T>(m_value.number_integer);
  2132. }
  2133. case value_t::number_unsigned:
  2134. {
  2135. return static_cast<T>(m_value.number_unsigned);
  2136. }
  2137. case value_t::number_float:
  2138. {
  2139. return static_cast<T>(m_value.number_float);
  2140. }
  2141. default:
  2142. {
  2143. throw std::domain_error("type must be number, but is " + type_name());
  2144. }
  2145. }
  2146. }
  2147. /// get a boolean (explicit)
  2148. constexpr boolean_t get_impl(boolean_t*) const
  2149. {
  2150. return is_boolean()
  2151. ? m_value.boolean
  2152. : throw std::domain_error("type must be boolean, but is " + type_name());
  2153. }
  2154. /// get a pointer to the value (object)
  2155. object_t* get_impl_ptr(object_t*) noexcept
  2156. {
  2157. return is_object() ? m_value.object : nullptr;
  2158. }
  2159. /// get a pointer to the value (object)
  2160. constexpr const object_t* get_impl_ptr(const object_t*) const noexcept
  2161. {
  2162. return is_object() ? m_value.object : nullptr;
  2163. }
  2164. /// get a pointer to the value (array)
  2165. array_t* get_impl_ptr(array_t*) noexcept
  2166. {
  2167. return is_array() ? m_value.array : nullptr;
  2168. }
  2169. /// get a pointer to the value (array)
  2170. constexpr const array_t* get_impl_ptr(const array_t*) const noexcept
  2171. {
  2172. return is_array() ? m_value.array : nullptr;
  2173. }
  2174. /// get a pointer to the value (string)
  2175. string_t* get_impl_ptr(string_t*) noexcept
  2176. {
  2177. return is_string() ? m_value.string : nullptr;
  2178. }
  2179. /// get a pointer to the value (string)
  2180. constexpr const string_t* get_impl_ptr(const string_t*) const noexcept
  2181. {
  2182. return is_string() ? m_value.string : nullptr;
  2183. }
  2184. /// get a pointer to the value (boolean)
  2185. boolean_t* get_impl_ptr(boolean_t*) noexcept
  2186. {
  2187. return is_boolean() ? &m_value.boolean : nullptr;
  2188. }
  2189. /// get a pointer to the value (boolean)
  2190. constexpr const boolean_t* get_impl_ptr(const boolean_t*) const noexcept
  2191. {
  2192. return is_boolean() ? &m_value.boolean : nullptr;
  2193. }
  2194. /// get a pointer to the value (integer number)
  2195. number_integer_t* get_impl_ptr(number_integer_t*) noexcept
  2196. {
  2197. return is_number_integer() ? &m_value.number_integer : nullptr;
  2198. }
  2199. /// get a pointer to the value (integer number)
  2200. constexpr const number_integer_t* get_impl_ptr(const number_integer_t*) const noexcept
  2201. {
  2202. return is_number_integer() ? &m_value.number_integer : nullptr;
  2203. }
  2204. /// get a pointer to the value (unsigned number)
  2205. number_unsigned_t* get_impl_ptr(number_unsigned_t*) noexcept
  2206. {
  2207. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2208. }
  2209. /// get a pointer to the value (unsigned number)
  2210. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t*) const noexcept
  2211. {
  2212. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  2213. }
  2214. /// get a pointer to the value (floating-point number)
  2215. number_float_t* get_impl_ptr(number_float_t*) noexcept
  2216. {
  2217. return is_number_float() ? &m_value.number_float : nullptr;
  2218. }
  2219. /// get a pointer to the value (floating-point number)
  2220. constexpr const number_float_t* get_impl_ptr(const number_float_t*) const noexcept
  2221. {
  2222. return is_number_float() ? &m_value.number_float : nullptr;
  2223. }
  2224. /*!
  2225. @brief helper function to implement get_ref()
  2226. This funcion helps to implement get_ref() without code duplication for
  2227. const and non-const overloads
  2228. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  2229. @throw std::domain_error if ReferenceType does not match underlying value
  2230. type of the current JSON
  2231. */
  2232. template<typename ReferenceType, typename ThisType>
  2233. static ReferenceType get_ref_impl(ThisType& obj)
  2234. {
  2235. // helper type
  2236. using PointerType = typename std::add_pointer<ReferenceType>::type;
  2237. // delegate the call to get_ptr<>()
  2238. auto ptr = obj.template get_ptr<PointerType>();
  2239. if (ptr != nullptr)
  2240. {
  2241. return *ptr;
  2242. }
  2243. else
  2244. {
  2245. throw std::domain_error("incompatible ReferenceType for get_ref, actual type is " +
  2246. obj.type_name());
  2247. }
  2248. }
  2249. public:
  2250. /// @name value access
  2251. /// Direct access to the stored value of a JSON value.
  2252. /// @{
  2253. /*!
  2254. @brief get a value (explicit)
  2255. Explicit type conversion between the JSON value and a compatible value.
  2256. @tparam ValueType non-pointer type compatible to the JSON value, for
  2257. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  2258. `std::vector` types for JSON arrays
  2259. @return copy of the JSON value, converted to type @a ValueType
  2260. @throw std::domain_error in case passed type @a ValueType is incompatible
  2261. to JSON; example: `"type must be object, but is null"`
  2262. @complexity Linear in the size of the JSON value.
  2263. @liveexample{The example below shows several conversions from JSON values
  2264. to other types. There a few things to note: (1) Floating-point numbers can
  2265. be converted to integers\, (2) A JSON array can be converted to a standard
  2266. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2267. associative containers such as `std::unordered_map<std::string\,
  2268. json>`.,get__ValueType_const}
  2269. @internal
  2270. The idea of using a casted null pointer to choose the correct
  2271. implementation is from <http://stackoverflow.com/a/8315197/266378>.
  2272. @endinternal
  2273. @sa @ref operator ValueType() const for implicit conversion
  2274. @sa @ref get() for pointer-member access
  2275. @since version 1.0.0
  2276. */
  2277. template<typename ValueType, typename std::enable_if<
  2278. not std::is_pointer<ValueType>::value, int>::type = 0>
  2279. ValueType get() const
  2280. {
  2281. return get_impl(static_cast<ValueType*>(nullptr));
  2282. }
  2283. /*!
  2284. @brief get a pointer value (explicit)
  2285. Explicit pointer access to the internally stored JSON value. No copies are
  2286. made.
  2287. @warning The pointer becomes invalid if the underlying JSON object
  2288. changes.
  2289. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2290. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2291. @ref number_unsigned_t, or @ref number_float_t.
  2292. @return pointer to the internally stored JSON value if the requested
  2293. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2294. @complexity Constant.
  2295. @liveexample{The example below shows how pointers to internal values of a
  2296. JSON value can be requested. Note that no type conversions are made and a
  2297. `nullptr` is returned if the value and the requested pointer type does not
  2298. match.,get__PointerType}
  2299. @sa @ref get_ptr() for explicit pointer-member access
  2300. @since version 1.0.0
  2301. */
  2302. template<typename PointerType, typename std::enable_if<
  2303. std::is_pointer<PointerType>::value, int>::type = 0>
  2304. PointerType get() noexcept
  2305. {
  2306. // delegate the call to get_ptr
  2307. return get_ptr<PointerType>();
  2308. }
  2309. /*!
  2310. @brief get a pointer value (explicit)
  2311. @copydoc get()
  2312. */
  2313. template<typename PointerType, typename std::enable_if<
  2314. std::is_pointer<PointerType>::value, int>::type = 0>
  2315. constexpr const PointerType get() const noexcept
  2316. {
  2317. // delegate the call to get_ptr
  2318. return get_ptr<PointerType>();
  2319. }
  2320. /*!
  2321. @brief get a pointer value (implicit)
  2322. Implicit pointer access to the internally stored JSON value. No copies are
  2323. made.
  2324. @warning Writing data to the pointee of the result yields an undefined
  2325. state.
  2326. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  2327. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  2328. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  2329. assertion.
  2330. @return pointer to the internally stored JSON value if the requested
  2331. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  2332. @complexity Constant.
  2333. @liveexample{The example below shows how pointers to internal values of a
  2334. JSON value can be requested. Note that no type conversions are made and a
  2335. `nullptr` is returned if the value and the requested pointer type does not
  2336. match.,get_ptr}
  2337. @since version 1.0.0
  2338. */
  2339. template<typename PointerType, typename std::enable_if<
  2340. std::is_pointer<PointerType>::value, int>::type = 0>
  2341. PointerType get_ptr() noexcept
  2342. {
  2343. // get the type of the PointerType (remove pointer and const)
  2344. using pointee_t = typename std::remove_const<typename
  2345. std::remove_pointer<typename
  2346. std::remove_const<PointerType>::type>::type>::type;
  2347. // make sure the type matches the allowed types
  2348. static_assert(
  2349. std::is_same<object_t, pointee_t>::value
  2350. or std::is_same<array_t, pointee_t>::value
  2351. or std::is_same<string_t, pointee_t>::value
  2352. or std::is_same<boolean_t, pointee_t>::value
  2353. or std::is_same<number_integer_t, pointee_t>::value
  2354. or std::is_same<number_unsigned_t, pointee_t>::value
  2355. or std::is_same<number_float_t, pointee_t>::value
  2356. , "incompatible pointer type");
  2357. // delegate the call to get_impl_ptr<>()
  2358. return get_impl_ptr(static_cast<PointerType>(nullptr));
  2359. }
  2360. /*!
  2361. @brief get a pointer value (implicit)
  2362. @copydoc get_ptr()
  2363. */
  2364. template<typename PointerType, typename std::enable_if<
  2365. std::is_pointer<PointerType>::value and
  2366. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  2367. constexpr const PointerType get_ptr() const noexcept
  2368. {
  2369. // get the type of the PointerType (remove pointer and const)
  2370. using pointee_t = typename std::remove_const<typename
  2371. std::remove_pointer<typename
  2372. std::remove_const<PointerType>::type>::type>::type;
  2373. // make sure the type matches the allowed types
  2374. static_assert(
  2375. std::is_same<object_t, pointee_t>::value
  2376. or std::is_same<array_t, pointee_t>::value
  2377. or std::is_same<string_t, pointee_t>::value
  2378. or std::is_same<boolean_t, pointee_t>::value
  2379. or std::is_same<number_integer_t, pointee_t>::value
  2380. or std::is_same<number_unsigned_t, pointee_t>::value
  2381. or std::is_same<number_float_t, pointee_t>::value
  2382. , "incompatible pointer type");
  2383. // delegate the call to get_impl_ptr<>() const
  2384. return get_impl_ptr(static_cast<const PointerType>(nullptr));
  2385. }
  2386. /*!
  2387. @brief get a reference value (implicit)
  2388. Implict reference access to the internally stored JSON value. No copies
  2389. are made.
  2390. @warning Writing data to the referee of the result yields an undefined
  2391. state.
  2392. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  2393. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  2394. @ref number_float_t. Enforced by static assertion.
  2395. @return reference to the internally stored JSON value if the requested
  2396. reference type @a ReferenceType fits to the JSON value; throws
  2397. std::domain_error otherwise
  2398. @throw std::domain_error in case passed type @a ReferenceType is
  2399. incompatible with the stored JSON value
  2400. @complexity Constant.
  2401. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  2402. @since version 1.1.0
  2403. */
  2404. template<typename ReferenceType, typename std::enable_if<
  2405. std::is_reference<ReferenceType>::value, int>::type = 0>
  2406. ReferenceType get_ref()
  2407. {
  2408. // delegate call to get_ref_impl
  2409. return get_ref_impl<ReferenceType>(*this);
  2410. }
  2411. /*!
  2412. @brief get a reference value (implicit)
  2413. @copydoc get_ref()
  2414. */
  2415. template<typename ReferenceType, typename std::enable_if<
  2416. std::is_reference<ReferenceType>::value and
  2417. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  2418. ReferenceType get_ref() const
  2419. {
  2420. // delegate call to get_ref_impl
  2421. return get_ref_impl<ReferenceType>(*this);
  2422. }
  2423. /*!
  2424. @brief get a value (implicit)
  2425. Implicit type conversion between the JSON value and a compatible value.
  2426. The call is realized by calling @ref get() const.
  2427. @tparam ValueType non-pointer type compatible to the JSON value, for
  2428. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  2429. `std::vector` types for JSON arrays. The character type of @ref string_t
  2430. as well as an initializer list of this type is excluded to avoid
  2431. ambiguities as these types implicitly convert to `std::string`.
  2432. @return copy of the JSON value, converted to type @a ValueType
  2433. @throw std::domain_error in case passed type @a ValueType is incompatible
  2434. to JSON, thrown by @ref get() const
  2435. @complexity Linear in the size of the JSON value.
  2436. @liveexample{The example below shows several conversions from JSON values
  2437. to other types. There a few things to note: (1) Floating-point numbers can
  2438. be converted to integers\, (2) A JSON array can be converted to a standard
  2439. `std::vector<short>`\, (3) A JSON object can be converted to C++
  2440. associative containers such as `std::unordered_map<std::string\,
  2441. json>`.,operator__ValueType}
  2442. @since version 1.0.0
  2443. */
  2444. template < typename ValueType, typename std::enable_if <
  2445. not std::is_pointer<ValueType>::value and
  2446. not std::is_same<ValueType, typename string_t::value_type>::value
  2447. #ifndef _MSC_VER // Fix for issue #167 operator<< abiguity under VS2015
  2448. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  2449. #endif
  2450. , int >::type = 0 >
  2451. operator ValueType() const
  2452. {
  2453. // delegate the call to get<>() const
  2454. return get<ValueType>();
  2455. }
  2456. /// @}
  2457. ////////////////////
  2458. // element access //
  2459. ////////////////////
  2460. /// @name element access
  2461. /// Access to the JSON value.
  2462. /// @{
  2463. /*!
  2464. @brief access specified array element with bounds checking
  2465. Returns a reference to the element at specified location @a idx, with
  2466. bounds checking.
  2467. @param[in] idx index of the element to access
  2468. @return reference to the element at index @a idx
  2469. @throw std::domain_error if the JSON value is not an array; example:
  2470. `"cannot use at() with string"`
  2471. @throw std::out_of_range if the index @a idx is out of range of the array;
  2472. that is, `idx >= size()`; example: `"array index 7 is out of range"`
  2473. @complexity Constant.
  2474. @liveexample{The example below shows how array elements can be read and
  2475. written using `at()`.,at__size_type}
  2476. @since version 1.0.0
  2477. */
  2478. reference at(size_type idx)
  2479. {
  2480. // at only works for arrays
  2481. if (is_array())
  2482. {
  2483. try
  2484. {
  2485. return m_value.array->at(idx);
  2486. }
  2487. catch (std::out_of_range&)
  2488. {
  2489. // create better exception explanation
  2490. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  2491. }
  2492. }
  2493. else
  2494. {
  2495. throw std::domain_error("cannot use at() with " + type_name());
  2496. }
  2497. }
  2498. /*!
  2499. @brief access specified array element with bounds checking
  2500. Returns a const reference to the element at specified location @a idx,
  2501. with bounds checking.
  2502. @param[in] idx index of the element to access
  2503. @return const reference to the element at index @a idx
  2504. @throw std::domain_error if the JSON value is not an array; example:
  2505. `"cannot use at() with string"`
  2506. @throw std::out_of_range if the index @a idx is out of range of the array;
  2507. that is, `idx >= size()`; example: `"array index 7 is out of range"`
  2508. @complexity Constant.
  2509. @liveexample{The example below shows how array elements can be read using
  2510. `at()`.,at__size_type_const}
  2511. @since version 1.0.0
  2512. */
  2513. const_reference at(size_type idx) const
  2514. {
  2515. // at only works for arrays
  2516. if (is_array())
  2517. {
  2518. try
  2519. {
  2520. return m_value.array->at(idx);
  2521. }
  2522. catch (std::out_of_range&)
  2523. {
  2524. // create better exception explanation
  2525. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  2526. }
  2527. }
  2528. else
  2529. {
  2530. throw std::domain_error("cannot use at() with " + type_name());
  2531. }
  2532. }
  2533. /*!
  2534. @brief access specified object element with bounds checking
  2535. Returns a reference to the element at with specified key @a key, with
  2536. bounds checking.
  2537. @param[in] key key of the element to access
  2538. @return reference to the element at key @a key
  2539. @throw std::domain_error if the JSON value is not an object; example:
  2540. `"cannot use at() with boolean"`
  2541. @throw std::out_of_range if the key @a key is is not stored in the object;
  2542. that is, `find(key) == end()`; example: `"key "the fast" not found"`
  2543. @complexity Logarithmic in the size of the container.
  2544. @liveexample{The example below shows how object elements can be read and
  2545. written using `at()`.,at__object_t_key_type}
  2546. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2547. access by reference
  2548. @sa @ref value() for access by value with a default value
  2549. @since version 1.0.0
  2550. */
  2551. reference at(const typename object_t::key_type& key)
  2552. {
  2553. // at only works for objects
  2554. if (is_object())
  2555. {
  2556. try
  2557. {
  2558. return m_value.object->at(key);
  2559. }
  2560. catch (std::out_of_range&)
  2561. {
  2562. // create better exception explanation
  2563. throw std::out_of_range("key '" + key + "' not found");
  2564. }
  2565. }
  2566. else
  2567. {
  2568. throw std::domain_error("cannot use at() with " + type_name());
  2569. }
  2570. }
  2571. /*!
  2572. @brief access specified object element with bounds checking
  2573. Returns a const reference to the element at with specified key @a key,
  2574. with bounds checking.
  2575. @param[in] key key of the element to access
  2576. @return const reference to the element at key @a key
  2577. @throw std::domain_error if the JSON value is not an object; example:
  2578. `"cannot use at() with boolean"`
  2579. @throw std::out_of_range if the key @a key is is not stored in the object;
  2580. that is, `find(key) == end()`; example: `"key "the fast" not found"`
  2581. @complexity Logarithmic in the size of the container.
  2582. @liveexample{The example below shows how object elements can be read using
  2583. `at()`.,at__object_t_key_type_const}
  2584. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2585. access by reference
  2586. @sa @ref value() for access by value with a default value
  2587. @since version 1.0.0
  2588. */
  2589. const_reference at(const typename object_t::key_type& key) const
  2590. {
  2591. // at only works for objects
  2592. if (is_object())
  2593. {
  2594. try
  2595. {
  2596. return m_value.object->at(key);
  2597. }
  2598. catch (std::out_of_range&)
  2599. {
  2600. // create better exception explanation
  2601. throw std::out_of_range("key '" + key + "' not found");
  2602. }
  2603. }
  2604. else
  2605. {
  2606. throw std::domain_error("cannot use at() with " + type_name());
  2607. }
  2608. }
  2609. /*!
  2610. @brief access specified array element
  2611. Returns a reference to the element at specified location @a idx.
  2612. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  2613. then the array is silently filled up with `null` values to make `idx` a
  2614. valid reference to the last stored element.
  2615. @param[in] idx index of the element to access
  2616. @return reference to the element at index @a idx
  2617. @throw std::domain_error if JSON is not an array or null; example:
  2618. `"cannot use operator[] with string"`
  2619. @complexity Constant if @a idx is in the range of the array. Otherwise
  2620. linear in `idx - size()`.
  2621. @liveexample{The example below shows how array elements can be read and
  2622. written using `[]` operator. Note the addition of `null`
  2623. values.,operatorarray__size_type}
  2624. @since version 1.0.0
  2625. */
  2626. reference operator[](size_type idx)
  2627. {
  2628. // implicitly convert null value to an empty array
  2629. if (is_null())
  2630. {
  2631. m_type = value_t::array;
  2632. m_value.array = create<array_t>();
  2633. assert_invariant();
  2634. }
  2635. // operator[] only works for arrays
  2636. if (is_array())
  2637. {
  2638. // fill up array with null values if given idx is outside range
  2639. if (idx >= m_value.array->size())
  2640. {
  2641. m_value.array->insert(m_value.array->end(),
  2642. idx - m_value.array->size() + 1,
  2643. basic_json());
  2644. }
  2645. return m_value.array->operator[](idx);
  2646. }
  2647. else
  2648. {
  2649. throw std::domain_error("cannot use operator[] with " + type_name());
  2650. }
  2651. }
  2652. /*!
  2653. @brief access specified array element
  2654. Returns a const reference to the element at specified location @a idx.
  2655. @param[in] idx index of the element to access
  2656. @return const reference to the element at index @a idx
  2657. @throw std::domain_error if JSON is not an array; example: `"cannot use
  2658. operator[] with null"`
  2659. @complexity Constant.
  2660. @liveexample{The example below shows how array elements can be read using
  2661. the `[]` operator.,operatorarray__size_type_const}
  2662. @since version 1.0.0
  2663. */
  2664. const_reference operator[](size_type idx) const
  2665. {
  2666. // const operator[] only works for arrays
  2667. if (is_array())
  2668. {
  2669. return m_value.array->operator[](idx);
  2670. }
  2671. else
  2672. {
  2673. throw std::domain_error("cannot use operator[] with " + type_name());
  2674. }
  2675. }
  2676. /*!
  2677. @brief access specified object element
  2678. Returns a reference to the element at with specified key @a key.
  2679. @note If @a key is not found in the object, then it is silently added to
  2680. the object and filled with a `null` value to make `key` a valid reference.
  2681. In case the value was `null` before, it is converted to an object.
  2682. @param[in] key key of the element to access
  2683. @return reference to the element at key @a key
  2684. @throw std::domain_error if JSON is not an object or null; example:
  2685. `"cannot use operator[] with string"`
  2686. @complexity Logarithmic in the size of the container.
  2687. @liveexample{The example below shows how object elements can be read and
  2688. written using the `[]` operator.,operatorarray__key_type}
  2689. @sa @ref at(const typename object_t::key_type&) for access by reference
  2690. with range checking
  2691. @sa @ref value() for access by value with a default value
  2692. @since version 1.0.0
  2693. */
  2694. reference operator[](const typename object_t::key_type& key)
  2695. {
  2696. // implicitly convert null value to an empty object
  2697. if (is_null())
  2698. {
  2699. m_type = value_t::object;
  2700. m_value.object = create<object_t>();
  2701. assert_invariant();
  2702. }
  2703. // operator[] only works for objects
  2704. if (is_object())
  2705. {
  2706. return m_value.object->operator[](key);
  2707. }
  2708. else
  2709. {
  2710. throw std::domain_error("cannot use operator[] with " + type_name());
  2711. }
  2712. }
  2713. /*!
  2714. @brief read-only access specified object element
  2715. Returns a const reference to the element at with specified key @a key. No
  2716. bounds checking is performed.
  2717. @warning If the element with key @a key does not exist, the behavior is
  2718. undefined.
  2719. @param[in] key key of the element to access
  2720. @return const reference to the element at key @a key
  2721. @pre The element with key @a key must exist. **This precondition is
  2722. enforced with an assertion.**
  2723. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2724. operator[] with null"`
  2725. @complexity Logarithmic in the size of the container.
  2726. @liveexample{The example below shows how object elements can be read using
  2727. the `[]` operator.,operatorarray__key_type_const}
  2728. @sa @ref at(const typename object_t::key_type&) for access by reference
  2729. with range checking
  2730. @sa @ref value() for access by value with a default value
  2731. @since version 1.0.0
  2732. */
  2733. const_reference operator[](const typename object_t::key_type& key) const
  2734. {
  2735. // const operator[] only works for objects
  2736. if (is_object())
  2737. {
  2738. assert(m_value.object->find(key) != m_value.object->end());
  2739. return m_value.object->find(key)->second;
  2740. }
  2741. else
  2742. {
  2743. throw std::domain_error("cannot use operator[] with " + type_name());
  2744. }
  2745. }
  2746. /*!
  2747. @brief access specified object element
  2748. Returns a reference to the element at with specified key @a key.
  2749. @note If @a key is not found in the object, then it is silently added to
  2750. the object and filled with a `null` value to make `key` a valid reference.
  2751. In case the value was `null` before, it is converted to an object.
  2752. @param[in] key key of the element to access
  2753. @return reference to the element at key @a key
  2754. @throw std::domain_error if JSON is not an object or null; example:
  2755. `"cannot use operator[] with string"`
  2756. @complexity Logarithmic in the size of the container.
  2757. @liveexample{The example below shows how object elements can be read and
  2758. written using the `[]` operator.,operatorarray__key_type}
  2759. @sa @ref at(const typename object_t::key_type&) for access by reference
  2760. with range checking
  2761. @sa @ref value() for access by value with a default value
  2762. @since version 1.0.0
  2763. */
  2764. template<typename T, std::size_t n>
  2765. reference operator[](T * (&key)[n])
  2766. {
  2767. return operator[](static_cast<const T>(key));
  2768. }
  2769. /*!
  2770. @brief read-only access specified object element
  2771. Returns a const reference to the element at with specified key @a key. No
  2772. bounds checking is performed.
  2773. @warning If the element with key @a key does not exist, the behavior is
  2774. undefined.
  2775. @note This function is required for compatibility reasons with Clang.
  2776. @param[in] key key of the element to access
  2777. @return const reference to the element at key @a key
  2778. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2779. operator[] with null"`
  2780. @complexity Logarithmic in the size of the container.
  2781. @liveexample{The example below shows how object elements can be read using
  2782. the `[]` operator.,operatorarray__key_type_const}
  2783. @sa @ref at(const typename object_t::key_type&) for access by reference
  2784. with range checking
  2785. @sa @ref value() for access by value with a default value
  2786. @since version 1.0.0
  2787. */
  2788. template<typename T, std::size_t n>
  2789. const_reference operator[](T * (&key)[n]) const
  2790. {
  2791. return operator[](static_cast<const T>(key));
  2792. }
  2793. /*!
  2794. @brief access specified object element
  2795. Returns a reference to the element at with specified key @a key.
  2796. @note If @a key is not found in the object, then it is silently added to
  2797. the object and filled with a `null` value to make `key` a valid reference.
  2798. In case the value was `null` before, it is converted to an object.
  2799. @param[in] key key of the element to access
  2800. @return reference to the element at key @a key
  2801. @throw std::domain_error if JSON is not an object or null; example:
  2802. `"cannot use operator[] with string"`
  2803. @complexity Logarithmic in the size of the container.
  2804. @liveexample{The example below shows how object elements can be read and
  2805. written using the `[]` operator.,operatorarray__key_type}
  2806. @sa @ref at(const typename object_t::key_type&) for access by reference
  2807. with range checking
  2808. @sa @ref value() for access by value with a default value
  2809. @since version 1.1.0
  2810. */
  2811. template<typename T>
  2812. reference operator[](T* key)
  2813. {
  2814. // implicitly convert null to object
  2815. if (is_null())
  2816. {
  2817. m_type = value_t::object;
  2818. m_value = value_t::object;
  2819. assert_invariant();
  2820. }
  2821. // at only works for objects
  2822. if (is_object())
  2823. {
  2824. return m_value.object->operator[](key);
  2825. }
  2826. else
  2827. {
  2828. throw std::domain_error("cannot use operator[] with " + type_name());
  2829. }
  2830. }
  2831. /*!
  2832. @brief read-only access specified object element
  2833. Returns a const reference to the element at with specified key @a key. No
  2834. bounds checking is performed.
  2835. @warning If the element with key @a key does not exist, the behavior is
  2836. undefined.
  2837. @param[in] key key of the element to access
  2838. @return const reference to the element at key @a key
  2839. @pre The element with key @a key must exist. **This precondition is
  2840. enforced with an assertion.**
  2841. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2842. operator[] with null"`
  2843. @complexity Logarithmic in the size of the container.
  2844. @liveexample{The example below shows how object elements can be read using
  2845. the `[]` operator.,operatorarray__key_type_const}
  2846. @sa @ref at(const typename object_t::key_type&) for access by reference
  2847. with range checking
  2848. @sa @ref value() for access by value with a default value
  2849. @since version 1.1.0
  2850. */
  2851. template<typename T>
  2852. const_reference operator[](T* key) const
  2853. {
  2854. // at only works for objects
  2855. if (is_object())
  2856. {
  2857. assert(m_value.object->find(key) != m_value.object->end());
  2858. return m_value.object->find(key)->second;
  2859. }
  2860. else
  2861. {
  2862. throw std::domain_error("cannot use operator[] with " + type_name());
  2863. }
  2864. }
  2865. /*!
  2866. @brief access specified object element with default value
  2867. Returns either a copy of an object's element at the specified key @a key
  2868. or a given default value if no element with key @a key exists.
  2869. The function is basically equivalent to executing
  2870. @code {.cpp}
  2871. try {
  2872. return at(key);
  2873. } catch(std::out_of_range) {
  2874. return default_value;
  2875. }
  2876. @endcode
  2877. @note Unlike @ref at(const typename object_t::key_type&), this function
  2878. does not throw if the given key @a key was not found.
  2879. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  2880. function does not implicitly add an element to the position defined by @a
  2881. key. This function is furthermore also applicable to const objects.
  2882. @param[in] key key of the element to access
  2883. @param[in] default_value the value to return if @a key is not found
  2884. @tparam ValueType type compatible to JSON values, for instance `int` for
  2885. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  2886. JSON arrays. Note the type of the expected value at @a key and the default
  2887. value @a default_value must be compatible.
  2888. @return copy of the element at key @a key or @a default_value if @a key
  2889. is not found
  2890. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2891. value() with null"`
  2892. @complexity Logarithmic in the size of the container.
  2893. @liveexample{The example below shows how object elements can be queried
  2894. with a default value.,basic_json__value}
  2895. @sa @ref at(const typename object_t::key_type&) for access by reference
  2896. with range checking
  2897. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  2898. access by reference
  2899. @since version 1.0.0
  2900. */
  2901. template<class ValueType, typename std::enable_if<
  2902. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  2903. ValueType value(const typename object_t::key_type& key, ValueType default_value) const
  2904. {
  2905. // at only works for objects
  2906. if (is_object())
  2907. {
  2908. // if key is found, return value and given default value otherwise
  2909. const auto it = find(key);
  2910. if (it != end())
  2911. {
  2912. return *it;
  2913. }
  2914. else
  2915. {
  2916. return default_value;
  2917. }
  2918. }
  2919. else
  2920. {
  2921. throw std::domain_error("cannot use value() with " + type_name());
  2922. }
  2923. }
  2924. /*!
  2925. @brief overload for a default value of type const char*
  2926. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  2927. */
  2928. string_t value(const typename object_t::key_type& key, const char* default_value) const
  2929. {
  2930. return value(key, string_t(default_value));
  2931. }
  2932. /*!
  2933. @brief access specified object element via JSON Pointer with default value
  2934. Returns either a copy of an object's element at the specified key @a key
  2935. or a given default value if no element with key @a key exists.
  2936. The function is basically equivalent to executing
  2937. @code {.cpp}
  2938. try {
  2939. return at(ptr);
  2940. } catch(std::out_of_range) {
  2941. return default_value;
  2942. }
  2943. @endcode
  2944. @note Unlike @ref at(const json_pointer&), this function does not throw
  2945. if the given key @a key was not found.
  2946. @param[in] ptr a JSON pointer to the element to access
  2947. @param[in] default_value the value to return if @a ptr found no value
  2948. @tparam ValueType type compatible to JSON values, for instance `int` for
  2949. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  2950. JSON arrays. Note the type of the expected value at @a key and the default
  2951. value @a default_value must be compatible.
  2952. @return copy of the element at key @a key or @a default_value if @a key
  2953. is not found
  2954. @throw std::domain_error if JSON is not an object; example: `"cannot use
  2955. value() with null"`
  2956. @complexity Logarithmic in the size of the container.
  2957. @liveexample{The example below shows how object elements can be queried
  2958. with a default value.,basic_json__value_ptr}
  2959. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  2960. @since version 2.0.2
  2961. */
  2962. template<class ValueType, typename std::enable_if<
  2963. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  2964. ValueType value(const json_pointer& ptr, ValueType default_value) const
  2965. {
  2966. // at only works for objects
  2967. if (is_object())
  2968. {
  2969. // if pointer resolves a value, return it or use default value
  2970. try
  2971. {
  2972. return ptr.get_checked(this);
  2973. }
  2974. catch (std::out_of_range&)
  2975. {
  2976. return default_value;
  2977. }
  2978. }
  2979. else
  2980. {
  2981. throw std::domain_error("cannot use value() with " + type_name());
  2982. }
  2983. }
  2984. /*!
  2985. @brief overload for a default value of type const char*
  2986. @copydoc basic_json::value(const json_pointer&, ValueType) const
  2987. */
  2988. string_t value(const json_pointer& ptr, const char* default_value) const
  2989. {
  2990. return value(ptr, string_t(default_value));
  2991. }
  2992. /*!
  2993. @brief access the first element
  2994. Returns a reference to the first element in the container. For a JSON
  2995. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  2996. @return In case of a structured type (array or object), a reference to the
  2997. first element is returned. In cast of number, string, or boolean values, a
  2998. reference to the value is returned.
  2999. @complexity Constant.
  3000. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3001. or an empty array or object (undefined behavior, **guarded by
  3002. assertions**).
  3003. @post The JSON value remains unchanged.
  3004. @throw std::out_of_range when called on `null` value
  3005. @liveexample{The following code shows an example for `front()`.,front}
  3006. @sa @ref back() -- access the last element
  3007. @since version 1.0.0
  3008. */
  3009. reference front()
  3010. {
  3011. return *begin();
  3012. }
  3013. /*!
  3014. @copydoc basic_json::front()
  3015. */
  3016. const_reference front() const
  3017. {
  3018. return *cbegin();
  3019. }
  3020. /*!
  3021. @brief access the last element
  3022. Returns a reference to the last element in the container. For a JSON
  3023. container `c`, the expression `c.back()` is equivalent to
  3024. @code {.cpp}
  3025. auto tmp = c.end();
  3026. --tmp;
  3027. return *tmp;
  3028. @endcode
  3029. @return In case of a structured type (array or object), a reference to the
  3030. last element is returned. In cast of number, string, or boolean values, a
  3031. reference to the value is returned.
  3032. @complexity Constant.
  3033. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  3034. or an empty array or object (undefined behavior, **guarded by
  3035. assertions**).
  3036. @post The JSON value remains unchanged.
  3037. @throw std::out_of_range when called on `null` value.
  3038. @liveexample{The following code shows an example for `back()`.,back}
  3039. @sa @ref front() -- access the first element
  3040. @since version 1.0.0
  3041. */
  3042. reference back()
  3043. {
  3044. auto tmp = end();
  3045. --tmp;
  3046. return *tmp;
  3047. }
  3048. /*!
  3049. @copydoc basic_json::back()
  3050. */
  3051. const_reference back() const
  3052. {
  3053. auto tmp = cend();
  3054. --tmp;
  3055. return *tmp;
  3056. }
  3057. /*!
  3058. @brief remove element given an iterator
  3059. Removes the element specified by iterator @a pos. The iterator @a pos must
  3060. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  3061. but is not dereferenceable) cannot be used as a value for @a pos.
  3062. If called on a primitive type other than `null`, the resulting JSON value
  3063. will be `null`.
  3064. @param[in] pos iterator to the element to remove
  3065. @return Iterator following the last removed element. If the iterator @a
  3066. pos refers to the last element, the `end()` iterator is returned.
  3067. @tparam IteratorType an @ref iterator or @ref const_iterator
  3068. @post Invalidates iterators and references at or after the point of the
  3069. erase, including the `end()` iterator.
  3070. @throw std::domain_error if called on a `null` value; example: `"cannot
  3071. use erase() with null"`
  3072. @throw std::domain_error if called on an iterator which does not belong to
  3073. the current JSON value; example: `"iterator does not fit current value"`
  3074. @throw std::out_of_range if called on a primitive type with invalid
  3075. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  3076. out of range"`
  3077. @complexity The complexity depends on the type:
  3078. - objects: amortized constant
  3079. - arrays: linear in distance between pos and the end of the container
  3080. - strings: linear in the length of the string
  3081. - other types: constant
  3082. @liveexample{The example shows the result of `erase()` for different JSON
  3083. types.,erase__IteratorType}
  3084. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3085. the given range
  3086. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3087. from an object at the given key
  3088. @sa @ref erase(const size_type) -- removes the element from an array at
  3089. the given index
  3090. @since version 1.0.0
  3091. */
  3092. template<class IteratorType, typename std::enable_if<
  3093. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3094. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3095. = 0>
  3096. IteratorType erase(IteratorType pos)
  3097. {
  3098. // make sure iterator fits the current value
  3099. if (this != pos.m_object)
  3100. {
  3101. throw std::domain_error("iterator does not fit current value");
  3102. }
  3103. IteratorType result = end();
  3104. switch (m_type)
  3105. {
  3106. case value_t::boolean:
  3107. case value_t::number_float:
  3108. case value_t::number_integer:
  3109. case value_t::number_unsigned:
  3110. case value_t::string:
  3111. {
  3112. if (not pos.m_it.primitive_iterator.is_begin())
  3113. {
  3114. throw std::out_of_range("iterator out of range");
  3115. }
  3116. if (is_string())
  3117. {
  3118. AllocatorType<string_t> alloc;
  3119. alloc.destroy(m_value.string);
  3120. alloc.deallocate(m_value.string, 1);
  3121. m_value.string = nullptr;
  3122. }
  3123. m_type = value_t::null;
  3124. assert_invariant();
  3125. break;
  3126. }
  3127. case value_t::object:
  3128. {
  3129. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  3130. break;
  3131. }
  3132. case value_t::array:
  3133. {
  3134. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  3135. break;
  3136. }
  3137. default:
  3138. {
  3139. throw std::domain_error("cannot use erase() with " + type_name());
  3140. }
  3141. }
  3142. return result;
  3143. }
  3144. /*!
  3145. @brief remove elements given an iterator range
  3146. Removes the element specified by the range `[first; last)`. The iterator
  3147. @a first does not need to be dereferenceable if `first == last`: erasing
  3148. an empty range is a no-op.
  3149. If called on a primitive type other than `null`, the resulting JSON value
  3150. will be `null`.
  3151. @param[in] first iterator to the beginning of the range to remove
  3152. @param[in] last iterator past the end of the range to remove
  3153. @return Iterator following the last removed element. If the iterator @a
  3154. second refers to the last element, the `end()` iterator is returned.
  3155. @tparam IteratorType an @ref iterator or @ref const_iterator
  3156. @post Invalidates iterators and references at or after the point of the
  3157. erase, including the `end()` iterator.
  3158. @throw std::domain_error if called on a `null` value; example: `"cannot
  3159. use erase() with null"`
  3160. @throw std::domain_error if called on iterators which does not belong to
  3161. the current JSON value; example: `"iterators do not fit current value"`
  3162. @throw std::out_of_range if called on a primitive type with invalid
  3163. iterators (i.e., if `first != begin()` and `last != end()`); example:
  3164. `"iterators out of range"`
  3165. @complexity The complexity depends on the type:
  3166. - objects: `log(size()) + std::distance(first, last)`
  3167. - arrays: linear in the distance between @a first and @a last, plus linear
  3168. in the distance between @a last and end of the container
  3169. - strings: linear in the length of the string
  3170. - other types: constant
  3171. @liveexample{The example shows the result of `erase()` for different JSON
  3172. types.,erase__IteratorType_IteratorType}
  3173. @sa @ref erase(IteratorType) -- removes the element at a given position
  3174. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3175. from an object at the given key
  3176. @sa @ref erase(const size_type) -- removes the element from an array at
  3177. the given index
  3178. @since version 1.0.0
  3179. */
  3180. template<class IteratorType, typename std::enable_if<
  3181. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  3182. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  3183. = 0>
  3184. IteratorType erase(IteratorType first, IteratorType last)
  3185. {
  3186. // make sure iterator fits the current value
  3187. if (this != first.m_object or this != last.m_object)
  3188. {
  3189. throw std::domain_error("iterators do not fit current value");
  3190. }
  3191. IteratorType result = end();
  3192. switch (m_type)
  3193. {
  3194. case value_t::boolean:
  3195. case value_t::number_float:
  3196. case value_t::number_integer:
  3197. case value_t::number_unsigned:
  3198. case value_t::string:
  3199. {
  3200. if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
  3201. {
  3202. throw std::out_of_range("iterators out of range");
  3203. }
  3204. if (is_string())
  3205. {
  3206. AllocatorType<string_t> alloc;
  3207. alloc.destroy(m_value.string);
  3208. alloc.deallocate(m_value.string, 1);
  3209. m_value.string = nullptr;
  3210. }
  3211. m_type = value_t::null;
  3212. assert_invariant();
  3213. break;
  3214. }
  3215. case value_t::object:
  3216. {
  3217. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  3218. last.m_it.object_iterator);
  3219. break;
  3220. }
  3221. case value_t::array:
  3222. {
  3223. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  3224. last.m_it.array_iterator);
  3225. break;
  3226. }
  3227. default:
  3228. {
  3229. throw std::domain_error("cannot use erase() with " + type_name());
  3230. }
  3231. }
  3232. return result;
  3233. }
  3234. /*!
  3235. @brief remove element from a JSON object given a key
  3236. Removes elements from a JSON object with the key value @a key.
  3237. @param[in] key value of the elements to remove
  3238. @return Number of elements removed. If @a ObjectType is the default
  3239. `std::map` type, the return value will always be `0` (@a key was not
  3240. found) or `1` (@a key was found).
  3241. @post References and iterators to the erased elements are invalidated.
  3242. Other references and iterators are not affected.
  3243. @throw std::domain_error when called on a type other than JSON object;
  3244. example: `"cannot use erase() with null"`
  3245. @complexity `log(size()) + count(key)`
  3246. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  3247. @sa @ref erase(IteratorType) -- removes the element at a given position
  3248. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3249. the given range
  3250. @sa @ref erase(const size_type) -- removes the element from an array at
  3251. the given index
  3252. @since version 1.0.0
  3253. */
  3254. size_type erase(const typename object_t::key_type& key)
  3255. {
  3256. // this erase only works for objects
  3257. if (is_object())
  3258. {
  3259. return m_value.object->erase(key);
  3260. }
  3261. else
  3262. {
  3263. throw std::domain_error("cannot use erase() with " + type_name());
  3264. }
  3265. }
  3266. /*!
  3267. @brief remove element from a JSON array given an index
  3268. Removes element from a JSON array at the index @a idx.
  3269. @param[in] idx index of the element to remove
  3270. @throw std::domain_error when called on a type other than JSON array;
  3271. example: `"cannot use erase() with null"`
  3272. @throw std::out_of_range when `idx >= size()`; example: `"array index 17
  3273. is out of range"`
  3274. @complexity Linear in distance between @a idx and the end of the container.
  3275. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  3276. @sa @ref erase(IteratorType) -- removes the element at a given position
  3277. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  3278. the given range
  3279. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  3280. from an object at the given key
  3281. @since version 1.0.0
  3282. */
  3283. void erase(const size_type idx)
  3284. {
  3285. // this erase only works for arrays
  3286. if (is_array())
  3287. {
  3288. if (idx >= size())
  3289. {
  3290. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  3291. }
  3292. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  3293. }
  3294. else
  3295. {
  3296. throw std::domain_error("cannot use erase() with " + type_name());
  3297. }
  3298. }
  3299. /// @}
  3300. ////////////
  3301. // lookup //
  3302. ////////////
  3303. /// @name lookup
  3304. /// @{
  3305. /*!
  3306. @brief find an element in a JSON object
  3307. Finds an element in a JSON object with key equivalent to @a key. If the
  3308. element is not found or the JSON value is not an object, end() is
  3309. returned.
  3310. @param[in] key key value of the element to search for
  3311. @return Iterator to an element with key equivalent to @a key. If no such
  3312. element is found, past-the-end (see end()) iterator is returned.
  3313. @complexity Logarithmic in the size of the JSON object.
  3314. @liveexample{The example shows how `find()` is used.,find__key_type}
  3315. @since version 1.0.0
  3316. */
  3317. iterator find(typename object_t::key_type key)
  3318. {
  3319. auto result = end();
  3320. if (is_object())
  3321. {
  3322. result.m_it.object_iterator = m_value.object->find(key);
  3323. }
  3324. return result;
  3325. }
  3326. /*!
  3327. @brief find an element in a JSON object
  3328. @copydoc find(typename object_t::key_type)
  3329. */
  3330. const_iterator find(typename object_t::key_type key) const
  3331. {
  3332. auto result = cend();
  3333. if (is_object())
  3334. {
  3335. result.m_it.object_iterator = m_value.object->find(key);
  3336. }
  3337. return result;
  3338. }
  3339. /*!
  3340. @brief returns the number of occurrences of a key in a JSON object
  3341. Returns the number of elements with key @a key. If ObjectType is the
  3342. default `std::map` type, the return value will always be `0` (@a key was
  3343. not found) or `1` (@a key was found).
  3344. @param[in] key key value of the element to count
  3345. @return Number of elements with key @a key. If the JSON value is not an
  3346. object, the return value will be `0`.
  3347. @complexity Logarithmic in the size of the JSON object.
  3348. @liveexample{The example shows how `count()` is used.,count}
  3349. @since version 1.0.0
  3350. */
  3351. size_type count(typename object_t::key_type key) const
  3352. {
  3353. // return 0 for all nonobject types
  3354. return is_object() ? m_value.object->count(key) : 0;
  3355. }
  3356. /// @}
  3357. ///////////////
  3358. // iterators //
  3359. ///////////////
  3360. /// @name iterators
  3361. /// @{
  3362. /*!
  3363. @brief returns an iterator to the first element
  3364. Returns an iterator to the first element.
  3365. @image html range-begin-end.svg "Illustration from cppreference.com"
  3366. @return iterator to the first element
  3367. @complexity Constant.
  3368. @requirement This function helps `basic_json` satisfying the
  3369. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3370. requirements:
  3371. - The complexity is constant.
  3372. @liveexample{The following code shows an example for `begin()`.,begin}
  3373. @sa @ref cbegin() -- returns a const iterator to the beginning
  3374. @sa @ref end() -- returns an iterator to the end
  3375. @sa @ref cend() -- returns a const iterator to the end
  3376. @since version 1.0.0
  3377. */
  3378. iterator begin() noexcept
  3379. {
  3380. iterator result(this);
  3381. result.set_begin();
  3382. return result;
  3383. }
  3384. /*!
  3385. @copydoc basic_json::cbegin()
  3386. */
  3387. const_iterator begin() const noexcept
  3388. {
  3389. return cbegin();
  3390. }
  3391. /*!
  3392. @brief returns a const iterator to the first element
  3393. Returns a const iterator to the first element.
  3394. @image html range-begin-end.svg "Illustration from cppreference.com"
  3395. @return const iterator to the first element
  3396. @complexity Constant.
  3397. @requirement This function helps `basic_json` satisfying the
  3398. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3399. requirements:
  3400. - The complexity is constant.
  3401. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  3402. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  3403. @sa @ref begin() -- returns an iterator to the beginning
  3404. @sa @ref end() -- returns an iterator to the end
  3405. @sa @ref cend() -- returns a const iterator to the end
  3406. @since version 1.0.0
  3407. */
  3408. const_iterator cbegin() const noexcept
  3409. {
  3410. const_iterator result(this);
  3411. result.set_begin();
  3412. return result;
  3413. }
  3414. /*!
  3415. @brief returns an iterator to one past the last element
  3416. Returns an iterator to one past the last element.
  3417. @image html range-begin-end.svg "Illustration from cppreference.com"
  3418. @return iterator one past the last element
  3419. @complexity Constant.
  3420. @requirement This function helps `basic_json` satisfying the
  3421. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3422. requirements:
  3423. - The complexity is constant.
  3424. @liveexample{The following code shows an example for `end()`.,end}
  3425. @sa @ref cend() -- returns a const iterator to the end
  3426. @sa @ref begin() -- returns an iterator to the beginning
  3427. @sa @ref cbegin() -- returns a const iterator to the beginning
  3428. @since version 1.0.0
  3429. */
  3430. iterator end() noexcept
  3431. {
  3432. iterator result(this);
  3433. result.set_end();
  3434. return result;
  3435. }
  3436. /*!
  3437. @copydoc basic_json::cend()
  3438. */
  3439. const_iterator end() const noexcept
  3440. {
  3441. return cend();
  3442. }
  3443. /*!
  3444. @brief returns a const iterator to one past the last element
  3445. Returns a const iterator to one past the last element.
  3446. @image html range-begin-end.svg "Illustration from cppreference.com"
  3447. @return const iterator one past the last element
  3448. @complexity Constant.
  3449. @requirement This function helps `basic_json` satisfying the
  3450. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3451. requirements:
  3452. - The complexity is constant.
  3453. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  3454. @liveexample{The following code shows an example for `cend()`.,cend}
  3455. @sa @ref end() -- returns an iterator to the end
  3456. @sa @ref begin() -- returns an iterator to the beginning
  3457. @sa @ref cbegin() -- returns a const iterator to the beginning
  3458. @since version 1.0.0
  3459. */
  3460. const_iterator cend() const noexcept
  3461. {
  3462. const_iterator result(this);
  3463. result.set_end();
  3464. return result;
  3465. }
  3466. /*!
  3467. @brief returns an iterator to the reverse-beginning
  3468. Returns an iterator to the reverse-beginning; that is, the last element.
  3469. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3470. @complexity Constant.
  3471. @requirement This function helps `basic_json` satisfying the
  3472. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3473. requirements:
  3474. - The complexity is constant.
  3475. - Has the semantics of `reverse_iterator(end())`.
  3476. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  3477. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3478. @sa @ref rend() -- returns a reverse iterator to the end
  3479. @sa @ref crend() -- returns a const reverse iterator to the end
  3480. @since version 1.0.0
  3481. */
  3482. reverse_iterator rbegin() noexcept
  3483. {
  3484. return reverse_iterator(end());
  3485. }
  3486. /*!
  3487. @copydoc basic_json::crbegin()
  3488. */
  3489. const_reverse_iterator rbegin() const noexcept
  3490. {
  3491. return crbegin();
  3492. }
  3493. /*!
  3494. @brief returns an iterator to the reverse-end
  3495. Returns an iterator to the reverse-end; that is, one before the first
  3496. element.
  3497. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3498. @complexity Constant.
  3499. @requirement This function helps `basic_json` satisfying the
  3500. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3501. requirements:
  3502. - The complexity is constant.
  3503. - Has the semantics of `reverse_iterator(begin())`.
  3504. @liveexample{The following code shows an example for `rend()`.,rend}
  3505. @sa @ref crend() -- returns a const reverse iterator to the end
  3506. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3507. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3508. @since version 1.0.0
  3509. */
  3510. reverse_iterator rend() noexcept
  3511. {
  3512. return reverse_iterator(begin());
  3513. }
  3514. /*!
  3515. @copydoc basic_json::crend()
  3516. */
  3517. const_reverse_iterator rend() const noexcept
  3518. {
  3519. return crend();
  3520. }
  3521. /*!
  3522. @brief returns a const reverse iterator to the last element
  3523. Returns a const iterator to the reverse-beginning; that is, the last
  3524. element.
  3525. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3526. @complexity Constant.
  3527. @requirement This function helps `basic_json` satisfying the
  3528. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3529. requirements:
  3530. - The complexity is constant.
  3531. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  3532. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  3533. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3534. @sa @ref rend() -- returns a reverse iterator to the end
  3535. @sa @ref crend() -- returns a const reverse iterator to the end
  3536. @since version 1.0.0
  3537. */
  3538. const_reverse_iterator crbegin() const noexcept
  3539. {
  3540. return const_reverse_iterator(cend());
  3541. }
  3542. /*!
  3543. @brief returns a const reverse iterator to one before the first
  3544. Returns a const reverse iterator to the reverse-end; that is, one before
  3545. the first element.
  3546. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  3547. @complexity Constant.
  3548. @requirement This function helps `basic_json` satisfying the
  3549. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  3550. requirements:
  3551. - The complexity is constant.
  3552. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  3553. @liveexample{The following code shows an example for `crend()`.,crend}
  3554. @sa @ref rend() -- returns a reverse iterator to the end
  3555. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  3556. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  3557. @since version 1.0.0
  3558. */
  3559. const_reverse_iterator crend() const noexcept
  3560. {
  3561. return const_reverse_iterator(cbegin());
  3562. }
  3563. private:
  3564. // forward declaration
  3565. template<typename IteratorType> class iteration_proxy;
  3566. public:
  3567. /*!
  3568. @brief wrapper to access iterator member functions in range-based for
  3569. This function allows to access @ref iterator::key() and @ref
  3570. iterator::value() during range-based for loops. In these loops, a
  3571. reference to the JSON values is returned, so there is no access to the
  3572. underlying iterator.
  3573. @note The name of this function is not yet final and may change in the
  3574. future.
  3575. */
  3576. static iteration_proxy<iterator> iterator_wrapper(reference cont)
  3577. {
  3578. return iteration_proxy<iterator>(cont);
  3579. }
  3580. /*!
  3581. @copydoc iterator_wrapper(reference)
  3582. */
  3583. static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
  3584. {
  3585. return iteration_proxy<const_iterator>(cont);
  3586. }
  3587. /// @}
  3588. //////////////
  3589. // capacity //
  3590. //////////////
  3591. /// @name capacity
  3592. /// @{
  3593. /*!
  3594. @brief checks whether the container is empty
  3595. Checks if a JSON value has no elements.
  3596. @return The return value depends on the different types and is
  3597. defined as follows:
  3598. Value type | return value
  3599. ----------- | -------------
  3600. null | `true`
  3601. boolean | `false`
  3602. string | `false`
  3603. number | `false`
  3604. object | result of function `object_t::empty()`
  3605. array | result of function `array_t::empty()`
  3606. @note This function does not return whether a string stored as JSON value
  3607. is empty - it returns whether the JSON container itself is empty which is
  3608. false in the case of a string.
  3609. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3610. the Container concept; that is, their `empty()` functions have constant
  3611. complexity.
  3612. @requirement This function helps `basic_json` satisfying the
  3613. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3614. requirements:
  3615. - The complexity is constant.
  3616. - Has the semantics of `begin() == end()`.
  3617. @liveexample{The following code uses `empty()` to check if a JSON
  3618. object contains any elements.,empty}
  3619. @sa @ref size() -- returns the number of elements
  3620. @since version 1.0.0
  3621. */
  3622. bool empty() const noexcept
  3623. {
  3624. switch (m_type)
  3625. {
  3626. case value_t::null:
  3627. {
  3628. // null values are empty
  3629. return true;
  3630. }
  3631. case value_t::array:
  3632. {
  3633. // delegate call to array_t::empty()
  3634. return m_value.array->empty();
  3635. }
  3636. case value_t::object:
  3637. {
  3638. // delegate call to object_t::empty()
  3639. return m_value.object->empty();
  3640. }
  3641. default:
  3642. {
  3643. // all other types are nonempty
  3644. return false;
  3645. }
  3646. }
  3647. }
  3648. /*!
  3649. @brief returns the number of elements
  3650. Returns the number of elements in a JSON value.
  3651. @return The return value depends on the different types and is
  3652. defined as follows:
  3653. Value type | return value
  3654. ----------- | -------------
  3655. null | `0`
  3656. boolean | `1`
  3657. string | `1`
  3658. number | `1`
  3659. object | result of function object_t::size()
  3660. array | result of function array_t::size()
  3661. @note This function does not return the length of a string stored as JSON
  3662. value - it returns the number of elements in the JSON value which is 1 in
  3663. the case of a string.
  3664. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3665. the Container concept; that is, their size() functions have constant
  3666. complexity.
  3667. @requirement This function helps `basic_json` satisfying the
  3668. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3669. requirements:
  3670. - The complexity is constant.
  3671. - Has the semantics of `std::distance(begin(), end())`.
  3672. @liveexample{The following code calls `size()` on the different value
  3673. types.,size}
  3674. @sa @ref empty() -- checks whether the container is empty
  3675. @sa @ref max_size() -- returns the maximal number of elements
  3676. @since version 1.0.0
  3677. */
  3678. size_type size() const noexcept
  3679. {
  3680. switch (m_type)
  3681. {
  3682. case value_t::null:
  3683. {
  3684. // null values are empty
  3685. return 0;
  3686. }
  3687. case value_t::array:
  3688. {
  3689. // delegate call to array_t::size()
  3690. return m_value.array->size();
  3691. }
  3692. case value_t::object:
  3693. {
  3694. // delegate call to object_t::size()
  3695. return m_value.object->size();
  3696. }
  3697. default:
  3698. {
  3699. // all other types have size 1
  3700. return 1;
  3701. }
  3702. }
  3703. }
  3704. /*!
  3705. @brief returns the maximum possible number of elements
  3706. Returns the maximum number of elements a JSON value is able to hold due to
  3707. system or library implementation limitations, i.e. `std::distance(begin(),
  3708. end())` for the JSON value.
  3709. @return The return value depends on the different types and is
  3710. defined as follows:
  3711. Value type | return value
  3712. ----------- | -------------
  3713. null | `0` (same as `size()`)
  3714. boolean | `1` (same as `size()`)
  3715. string | `1` (same as `size()`)
  3716. number | `1` (same as `size()`)
  3717. object | result of function `object_t::max_size()`
  3718. array | result of function `array_t::max_size()`
  3719. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  3720. the Container concept; that is, their `max_size()` functions have constant
  3721. complexity.
  3722. @requirement This function helps `basic_json` satisfying the
  3723. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  3724. requirements:
  3725. - The complexity is constant.
  3726. - Has the semantics of returning `b.size()` where `b` is the largest
  3727. possible JSON value.
  3728. @liveexample{The following code calls `max_size()` on the different value
  3729. types. Note the output is implementation specific.,max_size}
  3730. @sa @ref size() -- returns the number of elements
  3731. @since version 1.0.0
  3732. */
  3733. size_type max_size() const noexcept
  3734. {
  3735. switch (m_type)
  3736. {
  3737. case value_t::array:
  3738. {
  3739. // delegate call to array_t::max_size()
  3740. return m_value.array->max_size();
  3741. }
  3742. case value_t::object:
  3743. {
  3744. // delegate call to object_t::max_size()
  3745. return m_value.object->max_size();
  3746. }
  3747. default:
  3748. {
  3749. // all other types have max_size() == size()
  3750. return size();
  3751. }
  3752. }
  3753. }
  3754. /// @}
  3755. ///////////////
  3756. // modifiers //
  3757. ///////////////
  3758. /// @name modifiers
  3759. /// @{
  3760. /*!
  3761. @brief clears the contents
  3762. Clears the content of a JSON value and resets it to the default value as
  3763. if @ref basic_json(value_t) would have been called:
  3764. Value type | initial value
  3765. ----------- | -------------
  3766. null | `null`
  3767. boolean | `false`
  3768. string | `""`
  3769. number | `0`
  3770. object | `{}`
  3771. array | `[]`
  3772. @note Floating-point numbers are set to `0.0` which will be serialized to
  3773. `0`. The vale type remains @ref number_float_t.
  3774. @complexity Linear in the size of the JSON value.
  3775. @liveexample{The example below shows the effect of `clear()` to different
  3776. JSON types.,clear}
  3777. @since version 1.0.0
  3778. */
  3779. void clear() noexcept
  3780. {
  3781. switch (m_type)
  3782. {
  3783. case value_t::number_integer:
  3784. {
  3785. m_value.number_integer = 0;
  3786. break;
  3787. }
  3788. case value_t::number_unsigned:
  3789. {
  3790. m_value.number_unsigned = 0;
  3791. break;
  3792. }
  3793. case value_t::number_float:
  3794. {
  3795. m_value.number_float = 0.0;
  3796. break;
  3797. }
  3798. case value_t::boolean:
  3799. {
  3800. m_value.boolean = false;
  3801. break;
  3802. }
  3803. case value_t::string:
  3804. {
  3805. m_value.string->clear();
  3806. break;
  3807. }
  3808. case value_t::array:
  3809. {
  3810. m_value.array->clear();
  3811. break;
  3812. }
  3813. case value_t::object:
  3814. {
  3815. m_value.object->clear();
  3816. break;
  3817. }
  3818. default:
  3819. {
  3820. break;
  3821. }
  3822. }
  3823. }
  3824. /*!
  3825. @brief add an object to an array
  3826. Appends the given element @a val to the end of the JSON value. If the
  3827. function is called on a JSON null value, an empty array is created before
  3828. appending @a val.
  3829. @param[in] val the value to add to the JSON array
  3830. @throw std::domain_error when called on a type other than JSON array or
  3831. null; example: `"cannot use push_back() with number"`
  3832. @complexity Amortized constant.
  3833. @liveexample{The example shows how `push_back()` and `+=` can be used to
  3834. add elements to a JSON array. Note how the `null` value was silently
  3835. converted to a JSON array.,push_back}
  3836. @since version 1.0.0
  3837. */
  3838. void push_back(basic_json&& val)
  3839. {
  3840. // push_back only works for null objects or arrays
  3841. if (not(is_null() or is_array()))
  3842. {
  3843. throw std::domain_error("cannot use push_back() with " + type_name());
  3844. }
  3845. // transform null object into an array
  3846. if (is_null())
  3847. {
  3848. m_type = value_t::array;
  3849. m_value = value_t::array;
  3850. assert_invariant();
  3851. }
  3852. // add element to array (move semantics)
  3853. m_value.array->push_back(std::move(val));
  3854. // invalidate object
  3855. val.m_type = value_t::null;
  3856. }
  3857. /*!
  3858. @brief add an object to an array
  3859. @copydoc push_back(basic_json&&)
  3860. */
  3861. reference operator+=(basic_json&& val)
  3862. {
  3863. push_back(std::move(val));
  3864. return *this;
  3865. }
  3866. /*!
  3867. @brief add an object to an array
  3868. @copydoc push_back(basic_json&&)
  3869. */
  3870. void push_back(const basic_json& val)
  3871. {
  3872. // push_back only works for null objects or arrays
  3873. if (not(is_null() or is_array()))
  3874. {
  3875. throw std::domain_error("cannot use push_back() with " + type_name());
  3876. }
  3877. // transform null object into an array
  3878. if (is_null())
  3879. {
  3880. m_type = value_t::array;
  3881. m_value = value_t::array;
  3882. assert_invariant();
  3883. }
  3884. // add element to array
  3885. m_value.array->push_back(val);
  3886. }
  3887. /*!
  3888. @brief add an object to an array
  3889. @copydoc push_back(basic_json&&)
  3890. */
  3891. reference operator+=(const basic_json& val)
  3892. {
  3893. push_back(val);
  3894. return *this;
  3895. }
  3896. /*!
  3897. @brief add an object to an object
  3898. Inserts the given element @a val to the JSON object. If the function is
  3899. called on a JSON null value, an empty object is created before inserting
  3900. @a val.
  3901. @param[in] val the value to add to the JSON object
  3902. @throw std::domain_error when called on a type other than JSON object or
  3903. null; example: `"cannot use push_back() with number"`
  3904. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  3905. @liveexample{The example shows how `push_back()` and `+=` can be used to
  3906. add elements to a JSON object. Note how the `null` value was silently
  3907. converted to a JSON object.,push_back__object_t__value}
  3908. @since version 1.0.0
  3909. */
  3910. void push_back(const typename object_t::value_type& val)
  3911. {
  3912. // push_back only works for null objects or objects
  3913. if (not(is_null() or is_object()))
  3914. {
  3915. throw std::domain_error("cannot use push_back() with " + type_name());
  3916. }
  3917. // transform null object into an object
  3918. if (is_null())
  3919. {
  3920. m_type = value_t::object;
  3921. m_value = value_t::object;
  3922. assert_invariant();
  3923. }
  3924. // add element to array
  3925. m_value.object->insert(val);
  3926. }
  3927. /*!
  3928. @brief add an object to an object
  3929. @copydoc push_back(const typename object_t::value_type&)
  3930. */
  3931. reference operator+=(const typename object_t::value_type& val)
  3932. {
  3933. push_back(val);
  3934. return *this;
  3935. }
  3936. /*!
  3937. @brief add an object to an object
  3938. This function allows to use `push_back` with an initializer list. In case
  3939. 1. the current value is an object,
  3940. 2. the initializer list @a init contains only two elements, and
  3941. 3. the first element of @a init is a string,
  3942. @a init is converted into an object element and added using
  3943. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  3944. is converted to a JSON value and added using @ref push_back(basic_json&&).
  3945. @param init an initializer list
  3946. @complexity Linear in the size of the initializer list @a init.
  3947. @note This function is required to resolve an ambiguous overload error,
  3948. because pairs like `{"key", "value"}` can be both interpreted as
  3949. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  3950. https://github.com/nlohmann/json/issues/235 for more information.
  3951. @liveexample{The example shows how initializer lists are treated as
  3952. objects when possible.,push_back__initializer_list}
  3953. */
  3954. void push_back(std::initializer_list<basic_json> init)
  3955. {
  3956. if (is_object() and init.size() == 2 and init.begin()->is_string())
  3957. {
  3958. const string_t key = *init.begin();
  3959. push_back(typename object_t::value_type(key, *(init.begin() + 1)));
  3960. }
  3961. else
  3962. {
  3963. push_back(basic_json(init));
  3964. }
  3965. }
  3966. /*!
  3967. @brief add an object to an object
  3968. @copydoc push_back(std::initializer_list<basic_json>)
  3969. */
  3970. reference operator+=(std::initializer_list<basic_json> init)
  3971. {
  3972. push_back(init);
  3973. return *this;
  3974. }
  3975. /*!
  3976. @brief inserts element
  3977. Inserts element @a val before iterator @a pos.
  3978. @param[in] pos iterator before which the content will be inserted; may be
  3979. the end() iterator
  3980. @param[in] val element to insert
  3981. @return iterator pointing to the inserted @a val.
  3982. @throw std::domain_error if called on JSON values other than arrays;
  3983. example: `"cannot use insert() with string"`
  3984. @throw std::domain_error if @a pos is not an iterator of *this; example:
  3985. `"iterator does not fit current value"`
  3986. @complexity Constant plus linear in the distance between pos and end of the
  3987. container.
  3988. @liveexample{The example shows how `insert()` is used.,insert}
  3989. @since version 1.0.0
  3990. */
  3991. iterator insert(const_iterator pos, const basic_json& val)
  3992. {
  3993. // insert only works for arrays
  3994. if (is_array())
  3995. {
  3996. // check if iterator pos fits to this JSON value
  3997. if (pos.m_object != this)
  3998. {
  3999. throw std::domain_error("iterator does not fit current value");
  4000. }
  4001. // insert to array and return iterator
  4002. iterator result(this);
  4003. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  4004. return result;
  4005. }
  4006. else
  4007. {
  4008. throw std::domain_error("cannot use insert() with " + type_name());
  4009. }
  4010. }
  4011. /*!
  4012. @brief inserts element
  4013. @copydoc insert(const_iterator, const basic_json&)
  4014. */
  4015. iterator insert(const_iterator pos, basic_json&& val)
  4016. {
  4017. return insert(pos, val);
  4018. }
  4019. /*!
  4020. @brief inserts elements
  4021. Inserts @a cnt copies of @a val before iterator @a pos.
  4022. @param[in] pos iterator before which the content will be inserted; may be
  4023. the end() iterator
  4024. @param[in] cnt number of copies of @a val to insert
  4025. @param[in] val element to insert
  4026. @return iterator pointing to the first element inserted, or @a pos if
  4027. `cnt==0`
  4028. @throw std::domain_error if called on JSON values other than arrays;
  4029. example: `"cannot use insert() with string"`
  4030. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4031. `"iterator does not fit current value"`
  4032. @complexity Linear in @a cnt plus linear in the distance between @a pos
  4033. and end of the container.
  4034. @liveexample{The example shows how `insert()` is used.,insert__count}
  4035. @since version 1.0.0
  4036. */
  4037. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  4038. {
  4039. // insert only works for arrays
  4040. if (is_array())
  4041. {
  4042. // check if iterator pos fits to this JSON value
  4043. if (pos.m_object != this)
  4044. {
  4045. throw std::domain_error("iterator does not fit current value");
  4046. }
  4047. // insert to array and return iterator
  4048. iterator result(this);
  4049. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  4050. return result;
  4051. }
  4052. else
  4053. {
  4054. throw std::domain_error("cannot use insert() with " + type_name());
  4055. }
  4056. }
  4057. /*!
  4058. @brief inserts elements
  4059. Inserts elements from range `[first, last)` before iterator @a pos.
  4060. @param[in] pos iterator before which the content will be inserted; may be
  4061. the end() iterator
  4062. @param[in] first begin of the range of elements to insert
  4063. @param[in] last end of the range of elements to insert
  4064. @throw std::domain_error if called on JSON values other than arrays;
  4065. example: `"cannot use insert() with string"`
  4066. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4067. `"iterator does not fit current value"`
  4068. @throw std::domain_error if @a first and @a last do not belong to the same
  4069. JSON value; example: `"iterators do not fit"`
  4070. @throw std::domain_error if @a first or @a last are iterators into
  4071. container for which insert is called; example: `"passed iterators may not
  4072. belong to container"`
  4073. @return iterator pointing to the first element inserted, or @a pos if
  4074. `first==last`
  4075. @complexity Linear in `std::distance(first, last)` plus linear in the
  4076. distance between @a pos and end of the container.
  4077. @liveexample{The example shows how `insert()` is used.,insert__range}
  4078. @since version 1.0.0
  4079. */
  4080. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  4081. {
  4082. // insert only works for arrays
  4083. if (not is_array())
  4084. {
  4085. throw std::domain_error("cannot use insert() with " + type_name());
  4086. }
  4087. // check if iterator pos fits to this JSON value
  4088. if (pos.m_object != this)
  4089. {
  4090. throw std::domain_error("iterator does not fit current value");
  4091. }
  4092. // check if range iterators belong to the same JSON object
  4093. if (first.m_object != last.m_object)
  4094. {
  4095. throw std::domain_error("iterators do not fit");
  4096. }
  4097. if (first.m_object == this or last.m_object == this)
  4098. {
  4099. throw std::domain_error("passed iterators may not belong to container");
  4100. }
  4101. // insert to array and return iterator
  4102. iterator result(this);
  4103. result.m_it.array_iterator = m_value.array->insert(
  4104. pos.m_it.array_iterator,
  4105. first.m_it.array_iterator,
  4106. last.m_it.array_iterator);
  4107. return result;
  4108. }
  4109. /*!
  4110. @brief inserts elements
  4111. Inserts elements from initializer list @a ilist before iterator @a pos.
  4112. @param[in] pos iterator before which the content will be inserted; may be
  4113. the end() iterator
  4114. @param[in] ilist initializer list to insert the values from
  4115. @throw std::domain_error if called on JSON values other than arrays;
  4116. example: `"cannot use insert() with string"`
  4117. @throw std::domain_error if @a pos is not an iterator of *this; example:
  4118. `"iterator does not fit current value"`
  4119. @return iterator pointing to the first element inserted, or @a pos if
  4120. `ilist` is empty
  4121. @complexity Linear in `ilist.size()` plus linear in the distance between
  4122. @a pos and end of the container.
  4123. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  4124. @since version 1.0.0
  4125. */
  4126. iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
  4127. {
  4128. // insert only works for arrays
  4129. if (not is_array())
  4130. {
  4131. throw std::domain_error("cannot use insert() with " + type_name());
  4132. }
  4133. // check if iterator pos fits to this JSON value
  4134. if (pos.m_object != this)
  4135. {
  4136. throw std::domain_error("iterator does not fit current value");
  4137. }
  4138. // insert to array and return iterator
  4139. iterator result(this);
  4140. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
  4141. return result;
  4142. }
  4143. /*!
  4144. @brief exchanges the values
  4145. Exchanges the contents of the JSON value with those of @a other. Does not
  4146. invoke any move, copy, or swap operations on individual elements. All
  4147. iterators and references remain valid. The past-the-end iterator is
  4148. invalidated.
  4149. @param[in,out] other JSON value to exchange the contents with
  4150. @complexity Constant.
  4151. @liveexample{The example below shows how JSON values can be swapped with
  4152. `swap()`.,swap__reference}
  4153. @since version 1.0.0
  4154. */
  4155. void swap(reference other) noexcept (
  4156. std::is_nothrow_move_constructible<value_t>::value and
  4157. std::is_nothrow_move_assignable<value_t>::value and
  4158. std::is_nothrow_move_constructible<json_value>::value and
  4159. std::is_nothrow_move_assignable<json_value>::value
  4160. )
  4161. {
  4162. std::swap(m_type, other.m_type);
  4163. std::swap(m_value, other.m_value);
  4164. assert_invariant();
  4165. }
  4166. /*!
  4167. @brief exchanges the values
  4168. Exchanges the contents of a JSON array with those of @a other. Does not
  4169. invoke any move, copy, or swap operations on individual elements. All
  4170. iterators and references remain valid. The past-the-end iterator is
  4171. invalidated.
  4172. @param[in,out] other array to exchange the contents with
  4173. @throw std::domain_error when JSON value is not an array; example: `"cannot
  4174. use swap() with string"`
  4175. @complexity Constant.
  4176. @liveexample{The example below shows how arrays can be swapped with
  4177. `swap()`.,swap__array_t}
  4178. @since version 1.0.0
  4179. */
  4180. void swap(array_t& other)
  4181. {
  4182. // swap only works for arrays
  4183. if (is_array())
  4184. {
  4185. std::swap(*(m_value.array), other);
  4186. }
  4187. else
  4188. {
  4189. throw std::domain_error("cannot use swap() with " + type_name());
  4190. }
  4191. }
  4192. /*!
  4193. @brief exchanges the values
  4194. Exchanges the contents of a JSON object with those of @a other. Does not
  4195. invoke any move, copy, or swap operations on individual elements. All
  4196. iterators and references remain valid. The past-the-end iterator is
  4197. invalidated.
  4198. @param[in,out] other object to exchange the contents with
  4199. @throw std::domain_error when JSON value is not an object; example:
  4200. `"cannot use swap() with string"`
  4201. @complexity Constant.
  4202. @liveexample{The example below shows how objects can be swapped with
  4203. `swap()`.,swap__object_t}
  4204. @since version 1.0.0
  4205. */
  4206. void swap(object_t& other)
  4207. {
  4208. // swap only works for objects
  4209. if (is_object())
  4210. {
  4211. std::swap(*(m_value.object), other);
  4212. }
  4213. else
  4214. {
  4215. throw std::domain_error("cannot use swap() with " + type_name());
  4216. }
  4217. }
  4218. /*!
  4219. @brief exchanges the values
  4220. Exchanges the contents of a JSON string with those of @a other. Does not
  4221. invoke any move, copy, or swap operations on individual elements. All
  4222. iterators and references remain valid. The past-the-end iterator is
  4223. invalidated.
  4224. @param[in,out] other string to exchange the contents with
  4225. @throw std::domain_error when JSON value is not a string; example: `"cannot
  4226. use swap() with boolean"`
  4227. @complexity Constant.
  4228. @liveexample{The example below shows how strings can be swapped with
  4229. `swap()`.,swap__string_t}
  4230. @since version 1.0.0
  4231. */
  4232. void swap(string_t& other)
  4233. {
  4234. // swap only works for strings
  4235. if (is_string())
  4236. {
  4237. std::swap(*(m_value.string), other);
  4238. }
  4239. else
  4240. {
  4241. throw std::domain_error("cannot use swap() with " + type_name());
  4242. }
  4243. }
  4244. /// @}
  4245. //////////////////////////////////////////
  4246. // lexicographical comparison operators //
  4247. //////////////////////////////////////////
  4248. /// @name lexicographical comparison operators
  4249. /// @{
  4250. private:
  4251. /*!
  4252. @brief comparison operator for JSON types
  4253. Returns an ordering that is similar to Python:
  4254. - order: null < boolean < number < object < array < string
  4255. - furthermore, each type is not smaller than itself
  4256. @since version 1.0.0
  4257. */
  4258. friend bool operator<(const value_t lhs, const value_t rhs) noexcept
  4259. {
  4260. static constexpr std::array<uint8_t, 8> order = {{
  4261. 0, // null
  4262. 3, // object
  4263. 4, // array
  4264. 5, // string
  4265. 1, // boolean
  4266. 2, // integer
  4267. 2, // unsigned
  4268. 2, // float
  4269. }
  4270. };
  4271. // discarded values are not comparable
  4272. if (lhs == value_t::discarded or rhs == value_t::discarded)
  4273. {
  4274. return false;
  4275. }
  4276. return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
  4277. }
  4278. public:
  4279. /*!
  4280. @brief comparison: equal
  4281. Compares two JSON values for equality according to the following rules:
  4282. - Two JSON values are equal if (1) they are from the same type and (2)
  4283. their stored values are the same.
  4284. - Integer and floating-point numbers are automatically converted before
  4285. comparison. Floating-point numbers are compared indirectly: two
  4286. floating-point numbers `f1` and `f2` are considered equal if neither
  4287. `f1 > f2` nor `f2 > f1` holds.
  4288. - Two JSON null values are equal.
  4289. @param[in] lhs first JSON value to consider
  4290. @param[in] rhs second JSON value to consider
  4291. @return whether the values @a lhs and @a rhs are equal
  4292. @complexity Linear.
  4293. @liveexample{The example demonstrates comparing several JSON
  4294. types.,operator__equal}
  4295. @since version 1.0.0
  4296. */
  4297. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  4298. {
  4299. const auto lhs_type = lhs.type();
  4300. const auto rhs_type = rhs.type();
  4301. if (lhs_type == rhs_type)
  4302. {
  4303. switch (lhs_type)
  4304. {
  4305. case value_t::array:
  4306. {
  4307. return *lhs.m_value.array == *rhs.m_value.array;
  4308. }
  4309. case value_t::object:
  4310. {
  4311. return *lhs.m_value.object == *rhs.m_value.object;
  4312. }
  4313. case value_t::null:
  4314. {
  4315. return true;
  4316. }
  4317. case value_t::string:
  4318. {
  4319. return *lhs.m_value.string == *rhs.m_value.string;
  4320. }
  4321. case value_t::boolean:
  4322. {
  4323. return lhs.m_value.boolean == rhs.m_value.boolean;
  4324. }
  4325. case value_t::number_integer:
  4326. {
  4327. return lhs.m_value.number_integer == rhs.m_value.number_integer;
  4328. }
  4329. case value_t::number_unsigned:
  4330. {
  4331. return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
  4332. }
  4333. case value_t::number_float:
  4334. {
  4335. return lhs.m_value.number_float == rhs.m_value.number_float;
  4336. }
  4337. default:
  4338. {
  4339. return false;
  4340. }
  4341. }
  4342. }
  4343. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4344. {
  4345. return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
  4346. }
  4347. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4348. {
  4349. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
  4350. }
  4351. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4352. {
  4353. return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
  4354. }
  4355. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4356. {
  4357. return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4358. }
  4359. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4360. {
  4361. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
  4362. }
  4363. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4364. {
  4365. return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4366. }
  4367. return false;
  4368. }
  4369. /*!
  4370. @brief comparison: equal
  4371. The functions compares the given JSON value against a null pointer. As the
  4372. null pointer can be used to initialize a JSON value to null, a comparison
  4373. of JSON value @a v with a null pointer should be equivalent to call
  4374. `v.is_null()`.
  4375. @param[in] v JSON value to consider
  4376. @return whether @a v is null
  4377. @complexity Constant.
  4378. @liveexample{The example compares several JSON types to the null pointer.
  4379. ,operator__equal__nullptr_t}
  4380. @since version 1.0.0
  4381. */
  4382. friend bool operator==(const_reference v, std::nullptr_t) noexcept
  4383. {
  4384. return v.is_null();
  4385. }
  4386. /*!
  4387. @brief comparison: equal
  4388. @copydoc operator==(const_reference, std::nullptr_t)
  4389. */
  4390. friend bool operator==(std::nullptr_t, const_reference v) noexcept
  4391. {
  4392. return v.is_null();
  4393. }
  4394. /*!
  4395. @brief comparison: not equal
  4396. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  4397. @param[in] lhs first JSON value to consider
  4398. @param[in] rhs second JSON value to consider
  4399. @return whether the values @a lhs and @a rhs are not equal
  4400. @complexity Linear.
  4401. @liveexample{The example demonstrates comparing several JSON
  4402. types.,operator__notequal}
  4403. @since version 1.0.0
  4404. */
  4405. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  4406. {
  4407. return not (lhs == rhs);
  4408. }
  4409. /*!
  4410. @brief comparison: not equal
  4411. The functions compares the given JSON value against a null pointer. As the
  4412. null pointer can be used to initialize a JSON value to null, a comparison
  4413. of JSON value @a v with a null pointer should be equivalent to call
  4414. `not v.is_null()`.
  4415. @param[in] v JSON value to consider
  4416. @return whether @a v is not null
  4417. @complexity Constant.
  4418. @liveexample{The example compares several JSON types to the null pointer.
  4419. ,operator__notequal__nullptr_t}
  4420. @since version 1.0.0
  4421. */
  4422. friend bool operator!=(const_reference v, std::nullptr_t) noexcept
  4423. {
  4424. return not v.is_null();
  4425. }
  4426. /*!
  4427. @brief comparison: not equal
  4428. @copydoc operator!=(const_reference, std::nullptr_t)
  4429. */
  4430. friend bool operator!=(std::nullptr_t, const_reference v) noexcept
  4431. {
  4432. return not v.is_null();
  4433. }
  4434. /*!
  4435. @brief comparison: less than
  4436. Compares whether one JSON value @a lhs is less than another JSON value @a
  4437. rhs according to the following rules:
  4438. - If @a lhs and @a rhs have the same type, the values are compared using
  4439. the default `<` operator.
  4440. - Integer and floating-point numbers are automatically converted before
  4441. comparison
  4442. - In case @a lhs and @a rhs have different types, the values are ignored
  4443. and the order of the types is considered, see
  4444. @ref operator<(const value_t, const value_t).
  4445. @param[in] lhs first JSON value to consider
  4446. @param[in] rhs second JSON value to consider
  4447. @return whether @a lhs is less than @a rhs
  4448. @complexity Linear.
  4449. @liveexample{The example demonstrates comparing several JSON
  4450. types.,operator__less}
  4451. @since version 1.0.0
  4452. */
  4453. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  4454. {
  4455. const auto lhs_type = lhs.type();
  4456. const auto rhs_type = rhs.type();
  4457. if (lhs_type == rhs_type)
  4458. {
  4459. switch (lhs_type)
  4460. {
  4461. case value_t::array:
  4462. {
  4463. return *lhs.m_value.array < *rhs.m_value.array;
  4464. }
  4465. case value_t::object:
  4466. {
  4467. return *lhs.m_value.object < *rhs.m_value.object;
  4468. }
  4469. case value_t::null:
  4470. {
  4471. return false;
  4472. }
  4473. case value_t::string:
  4474. {
  4475. return *lhs.m_value.string < *rhs.m_value.string;
  4476. }
  4477. case value_t::boolean:
  4478. {
  4479. return lhs.m_value.boolean < rhs.m_value.boolean;
  4480. }
  4481. case value_t::number_integer:
  4482. {
  4483. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  4484. }
  4485. case value_t::number_unsigned:
  4486. {
  4487. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  4488. }
  4489. case value_t::number_float:
  4490. {
  4491. return lhs.m_value.number_float < rhs.m_value.number_float;
  4492. }
  4493. default:
  4494. {
  4495. return false;
  4496. }
  4497. }
  4498. }
  4499. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  4500. {
  4501. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  4502. }
  4503. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  4504. {
  4505. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  4506. }
  4507. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  4508. {
  4509. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  4510. }
  4511. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  4512. {
  4513. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  4514. }
  4515. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  4516. {
  4517. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  4518. }
  4519. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  4520. {
  4521. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  4522. }
  4523. // We only reach this line if we cannot compare values. In that case,
  4524. // we compare types. Note we have to call the operator explicitly,
  4525. // because MSVC has problems otherwise.
  4526. return operator<(lhs_type, rhs_type);
  4527. }
  4528. /*!
  4529. @brief comparison: less than or equal
  4530. Compares whether one JSON value @a lhs is less than or equal to another
  4531. JSON value by calculating `not (rhs < lhs)`.
  4532. @param[in] lhs first JSON value to consider
  4533. @param[in] rhs second JSON value to consider
  4534. @return whether @a lhs is less than or equal to @a rhs
  4535. @complexity Linear.
  4536. @liveexample{The example demonstrates comparing several JSON
  4537. types.,operator__greater}
  4538. @since version 1.0.0
  4539. */
  4540. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  4541. {
  4542. return not (rhs < lhs);
  4543. }
  4544. /*!
  4545. @brief comparison: greater than
  4546. Compares whether one JSON value @a lhs is greater than another
  4547. JSON value by calculating `not (lhs <= rhs)`.
  4548. @param[in] lhs first JSON value to consider
  4549. @param[in] rhs second JSON value to consider
  4550. @return whether @a lhs is greater than to @a rhs
  4551. @complexity Linear.
  4552. @liveexample{The example demonstrates comparing several JSON
  4553. types.,operator__lessequal}
  4554. @since version 1.0.0
  4555. */
  4556. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  4557. {
  4558. return not (lhs <= rhs);
  4559. }
  4560. /*!
  4561. @brief comparison: greater than or equal
  4562. Compares whether one JSON value @a lhs is greater than or equal to another
  4563. JSON value by calculating `not (lhs < rhs)`.
  4564. @param[in] lhs first JSON value to consider
  4565. @param[in] rhs second JSON value to consider
  4566. @return whether @a lhs is greater than or equal to @a rhs
  4567. @complexity Linear.
  4568. @liveexample{The example demonstrates comparing several JSON
  4569. types.,operator__greaterequal}
  4570. @since version 1.0.0
  4571. */
  4572. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  4573. {
  4574. return not (lhs < rhs);
  4575. }
  4576. /// @}
  4577. ///////////////////
  4578. // serialization //
  4579. ///////////////////
  4580. /// @name serialization
  4581. /// @{
  4582. /*!
  4583. @brief serialize to stream
  4584. Serialize the given JSON value @a j to the output stream @a o. The JSON
  4585. value will be serialized using the @ref dump member function. The
  4586. indentation of the output can be controlled with the member variable
  4587. `width` of the output stream @a o. For instance, using the manipulator
  4588. `std::setw(4)` on @a o sets the indentation level to `4` and the
  4589. serialization result is the same as calling `dump(4)`.
  4590. @note During serializaion, the locale and the precision of the output
  4591. stream @a o are changed. The original values are restored when the
  4592. function returns.
  4593. @param[in,out] o stream to serialize to
  4594. @param[in] j JSON value to serialize
  4595. @return the stream @a o
  4596. @complexity Linear.
  4597. @liveexample{The example below shows the serialization with different
  4598. parameters to `width` to adjust the indentation level.,operator_serialize}
  4599. @since version 1.0.0
  4600. */
  4601. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  4602. {
  4603. // read width member and use it as indentation parameter if nonzero
  4604. const bool pretty_print = (o.width() > 0);
  4605. const auto indentation = (pretty_print ? o.width() : 0);
  4606. // reset width to 0 for subsequent calls to this stream
  4607. o.width(0);
  4608. // fix locale problems
  4609. const auto old_locale = o.imbue(std::locale(std::locale(), new DecimalSeparator));
  4610. // set precision
  4611. // 6, 15 or 16 digits of precision allows round-trip IEEE 754
  4612. // string->float->string, string->double->string or string->long
  4613. // double->string; to be safe, we read this value from
  4614. // std::numeric_limits<number_float_t>::digits10
  4615. const auto old_precision = o.precision(std::numeric_limits<double>::digits10);
  4616. // do the actual serialization
  4617. j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
  4618. // reset locale and precision
  4619. o.imbue(old_locale);
  4620. o.precision(old_precision);
  4621. return o;
  4622. }
  4623. /*!
  4624. @brief serialize to stream
  4625. @copydoc operator<<(std::ostream&, const basic_json&)
  4626. */
  4627. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  4628. {
  4629. return o << j;
  4630. }
  4631. /// @}
  4632. /////////////////////
  4633. // deserialization //
  4634. /////////////////////
  4635. /// @name deserialization
  4636. /// @{
  4637. /*!
  4638. @brief deserialize from an array
  4639. This function reads from an array of 1-byte values.
  4640. @pre Each element of the container has a size of 1 byte. Violating this
  4641. precondition yields undefined behavior. **This precondition is enforced
  4642. with a static assertion.**
  4643. @param[in] array array to read from
  4644. @param[in] cb a parser callback function of type @ref parser_callback_t
  4645. which is used to control the deserialization by filtering unwanted values
  4646. (optional)
  4647. @return result of the deserialization
  4648. @complexity Linear in the length of the input. The parser is a predictive
  4649. LL(1) parser. The complexity can be higher if the parser callback function
  4650. @a cb has a super-linear complexity.
  4651. @note A UTF-8 byte order mark is silently ignored.
  4652. @liveexample{The example below demonstrates the `parse()` function reading
  4653. from an array.,parse__array__parser_callback_t}
  4654. @since version 2.0.3
  4655. */
  4656. template<class T, std::size_t N>
  4657. static basic_json parse(T (&array)[N],
  4658. const parser_callback_t cb = nullptr)
  4659. {
  4660. // delegate the call to the iterator-range parse overload
  4661. return parse(std::begin(array), std::end(array), cb);
  4662. }
  4663. /*!
  4664. @brief deserialize from string literal
  4665. @tparam CharT character/literal type with size of 1 byte
  4666. @param[in] s string literal to read a serialized JSON value from
  4667. @param[in] cb a parser callback function of type @ref parser_callback_t
  4668. which is used to control the deserialization by filtering unwanted values
  4669. (optional)
  4670. @return result of the deserialization
  4671. @complexity Linear in the length of the input. The parser is a predictive
  4672. LL(1) parser. The complexity can be higher if the parser callback function
  4673. @a cb has a super-linear complexity.
  4674. @note A UTF-8 byte order mark is silently ignored.
  4675. @note String containers like `std::string` or @ref string_t can be parsed
  4676. with @ref parse(const ContiguousContainer&, const parser_callback_t)
  4677. @liveexample{The example below demonstrates the `parse()` function with
  4678. and without callback function.,parse__string__parser_callback_t}
  4679. @sa @ref parse(std::istream&, const parser_callback_t) for a version that
  4680. reads from an input stream
  4681. @since version 1.0.0 (originally for @ref string_t)
  4682. */
  4683. template<typename CharPT, typename std::enable_if<
  4684. std::is_pointer<CharPT>::value and
  4685. std::is_integral<typename std::remove_pointer<CharPT>::type>::value and
  4686. sizeof(typename std::remove_pointer<CharPT>::type) == 1, int>::type = 0>
  4687. static basic_json parse(const CharPT s,
  4688. const parser_callback_t cb = nullptr)
  4689. {
  4690. return parser(reinterpret_cast<const char*>(s), cb).parse();
  4691. }
  4692. /*!
  4693. @brief deserialize from stream
  4694. @param[in,out] i stream to read a serialized JSON value from
  4695. @param[in] cb a parser callback function of type @ref parser_callback_t
  4696. which is used to control the deserialization by filtering unwanted values
  4697. (optional)
  4698. @return result of the deserialization
  4699. @complexity Linear in the length of the input. The parser is a predictive
  4700. LL(1) parser. The complexity can be higher if the parser callback function
  4701. @a cb has a super-linear complexity.
  4702. @note A UTF-8 byte order mark is silently ignored.
  4703. @liveexample{The example below demonstrates the `parse()` function with
  4704. and without callback function.,parse__istream__parser_callback_t}
  4705. @sa @ref parse(const char*, const parser_callback_t) for a version
  4706. that reads from a string
  4707. @since version 1.0.0
  4708. */
  4709. static basic_json parse(std::istream& i,
  4710. const parser_callback_t cb = nullptr)
  4711. {
  4712. return parser(i, cb).parse();
  4713. }
  4714. /*!
  4715. @copydoc parse(std::istream&, const parser_callback_t)
  4716. */
  4717. static basic_json parse(std::istream&& i,
  4718. const parser_callback_t cb = nullptr)
  4719. {
  4720. return parser(i, cb).parse();
  4721. }
  4722. /*!
  4723. @brief deserialize from an iterator range with contiguous storage
  4724. This function reads from an iterator range of a container with contiguous
  4725. storage of 1-byte values. Compatible container types include
  4726. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  4727. `std::initializer_list`. Furthermore, C-style arrays can be used with
  4728. `std::begin()`/`std::end()`. User-defined containers can be used as long
  4729. as they implement random-access iterators and a contiguous storage.
  4730. @pre The iterator range is contiguous. Violating this precondition yields
  4731. undefined behavior. **This precondition is enforced with an assertion.**
  4732. @pre Each element in the range has a size of 1 byte. Violating this
  4733. precondition yields undefined behavior. **This precondition is enforced
  4734. with a static assertion.**
  4735. @warning There is no way to enforce all preconditions at compile-time. If
  4736. the function is called with noncompliant iterators and with
  4737. assertions switched off, the behavior is undefined and will most
  4738. likely yield segmentation violation.
  4739. @tparam IteratorType iterator of container with contiguous storage
  4740. @param[in] first begin of the range to parse (included)
  4741. @param[in] last end of the range to parse (excluded)
  4742. @param[in] cb a parser callback function of type @ref parser_callback_t
  4743. which is used to control the deserialization by filtering unwanted values
  4744. (optional)
  4745. @return result of the deserialization
  4746. @complexity Linear in the length of the input. The parser is a predictive
  4747. LL(1) parser. The complexity can be higher if the parser callback function
  4748. @a cb has a super-linear complexity.
  4749. @note A UTF-8 byte order mark is silently ignored.
  4750. @liveexample{The example below demonstrates the `parse()` function reading
  4751. from an iterator range.,parse__iteratortype__parser_callback_t}
  4752. @since version 2.0.3
  4753. */
  4754. template<class IteratorType, typename std::enable_if<
  4755. std::is_base_of<
  4756. std::random_access_iterator_tag,
  4757. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  4758. static basic_json parse(IteratorType first, IteratorType last,
  4759. const parser_callback_t cb = nullptr)
  4760. {
  4761. // assertion to check that the iterator range is indeed contiguous,
  4762. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  4763. assert(std::accumulate(first, last, std::make_pair<bool, int>(true, 0),
  4764. [&first](std::pair<bool, int> res, decltype(*first) val)
  4765. {
  4766. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  4767. return res;
  4768. }).first);
  4769. // assertion to check that each element is 1 byte long
  4770. static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  4771. "each element in the iterator range must have the size of 1 byte");
  4772. // if iterator range is empty, create a parser with an empty string
  4773. // to generate "unexpected EOF" error message
  4774. if (std::distance(first, last) <= 0)
  4775. {
  4776. return parser("").parse();
  4777. }
  4778. return parser(first, last, cb).parse();
  4779. }
  4780. /*!
  4781. @brief deserialize from a container with contiguous storage
  4782. This function reads from a container with contiguous storage of 1-byte
  4783. values. Compatible container types include `std::vector`, `std::string`,
  4784. `std::array`, and `std::initializer_list`. User-defined containers can be
  4785. used as long as they implement random-access iterators and a contiguous
  4786. storage.
  4787. @pre The container storage is contiguous. Violating this precondition
  4788. yields undefined behavior. **This precondition is enforced with an
  4789. assertion.**
  4790. @pre Each element of the container has a size of 1 byte. Violating this
  4791. precondition yields undefined behavior. **This precondition is enforced
  4792. with a static assertion.**
  4793. @warning There is no way to enforce all preconditions at compile-time. If
  4794. the function is called with a noncompliant container and with
  4795. assertions switched off, the behavior is undefined and will most
  4796. likely yield segmentation violation.
  4797. @tparam ContiguousContainer container type with contiguous storage
  4798. @param[in] c container to read from
  4799. @param[in] cb a parser callback function of type @ref parser_callback_t
  4800. which is used to control the deserialization by filtering unwanted values
  4801. (optional)
  4802. @return result of the deserialization
  4803. @complexity Linear in the length of the input. The parser is a predictive
  4804. LL(1) parser. The complexity can be higher if the parser callback function
  4805. @a cb has a super-linear complexity.
  4806. @note A UTF-8 byte order mark is silently ignored.
  4807. @liveexample{The example below demonstrates the `parse()` function reading
  4808. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  4809. @since version 2.0.3
  4810. */
  4811. template<class ContiguousContainer, typename std::enable_if<
  4812. not std::is_pointer<ContiguousContainer>::value and
  4813. std::is_base_of<
  4814. std::random_access_iterator_tag,
  4815. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
  4816. , int>::type = 0>
  4817. static basic_json parse(const ContiguousContainer& c,
  4818. const parser_callback_t cb = nullptr)
  4819. {
  4820. // delegate the call to the iterator-range parse overload
  4821. return parse(std::begin(c), std::end(c), cb);
  4822. }
  4823. /*!
  4824. @brief deserialize from stream
  4825. Deserializes an input stream to a JSON value.
  4826. @param[in,out] i input stream to read a serialized JSON value from
  4827. @param[in,out] j JSON value to write the deserialized input to
  4828. @throw std::invalid_argument in case of parse errors
  4829. @complexity Linear in the length of the input. The parser is a predictive
  4830. LL(1) parser.
  4831. @note A UTF-8 byte order mark is silently ignored.
  4832. @liveexample{The example below shows how a JSON value is constructed by
  4833. reading a serialization from a stream.,operator_deserialize}
  4834. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  4835. parser callback function to filter values while parsing
  4836. @since version 1.0.0
  4837. */
  4838. friend std::istream& operator<<(basic_json& j, std::istream& i)
  4839. {
  4840. j = parser(i).parse();
  4841. return i;
  4842. }
  4843. /*!
  4844. @brief deserialize from stream
  4845. @copydoc operator<<(basic_json&, std::istream&)
  4846. */
  4847. friend std::istream& operator>>(std::istream& i, basic_json& j)
  4848. {
  4849. j = parser(i).parse();
  4850. return i;
  4851. }
  4852. /// @}
  4853. private:
  4854. ///////////////////////////
  4855. // convenience functions //
  4856. ///////////////////////////
  4857. /*!
  4858. @brief return the type as string
  4859. Returns the type name as string to be used in error messages - usually to
  4860. indicate that a function was called on a wrong JSON type.
  4861. @return basically a string representation of a the @a m_type member
  4862. @complexity Constant.
  4863. @since version 1.0.0
  4864. */
  4865. std::string type_name() const
  4866. {
  4867. switch (m_type)
  4868. {
  4869. case value_t::null:
  4870. return "null";
  4871. case value_t::object:
  4872. return "object";
  4873. case value_t::array:
  4874. return "array";
  4875. case value_t::string:
  4876. return "string";
  4877. case value_t::boolean:
  4878. return "boolean";
  4879. case value_t::discarded:
  4880. return "discarded";
  4881. default:
  4882. return "number";
  4883. }
  4884. }
  4885. /*!
  4886. @brief calculates the extra space to escape a JSON string
  4887. @param[in] s the string to escape
  4888. @return the number of characters required to escape string @a s
  4889. @complexity Linear in the length of string @a s.
  4890. */
  4891. static std::size_t extra_space(const string_t& s) noexcept
  4892. {
  4893. return std::accumulate(s.begin(), s.end(), size_t{},
  4894. [](size_t res, typename string_t::value_type c)
  4895. {
  4896. switch (c)
  4897. {
  4898. case '"':
  4899. case '\\':
  4900. case '\b':
  4901. case '\f':
  4902. case '\n':
  4903. case '\r':
  4904. case '\t':
  4905. {
  4906. // from c (1 byte) to \x (2 bytes)
  4907. return res + 1;
  4908. }
  4909. default:
  4910. {
  4911. if (c >= 0x00 and c <= 0x1f)
  4912. {
  4913. // from c (1 byte) to \uxxxx (6 bytes)
  4914. return res + 5;
  4915. }
  4916. else
  4917. {
  4918. return res;
  4919. }
  4920. }
  4921. }
  4922. });
  4923. }
  4924. /*!
  4925. @brief escape a string
  4926. Escape a string by replacing certain special characters by a sequence of
  4927. an escape character (backslash) and another character and other control
  4928. characters by a sequence of "\u" followed by a four-digit hex
  4929. representation.
  4930. @param[in] s the string to escape
  4931. @return the escaped string
  4932. @complexity Linear in the length of string @a s.
  4933. */
  4934. static string_t escape_string(const string_t& s)
  4935. {
  4936. const auto space = extra_space(s);
  4937. if (space == 0)
  4938. {
  4939. return s;
  4940. }
  4941. // create a result string of necessary size
  4942. string_t result(s.size() + space, '\\');
  4943. std::size_t pos = 0;
  4944. for (const auto& c : s)
  4945. {
  4946. switch (c)
  4947. {
  4948. // quotation mark (0x22)
  4949. case '"':
  4950. {
  4951. result[pos + 1] = '"';
  4952. pos += 2;
  4953. break;
  4954. }
  4955. // reverse solidus (0x5c)
  4956. case '\\':
  4957. {
  4958. // nothing to change
  4959. pos += 2;
  4960. break;
  4961. }
  4962. // backspace (0x08)
  4963. case '\b':
  4964. {
  4965. result[pos + 1] = 'b';
  4966. pos += 2;
  4967. break;
  4968. }
  4969. // formfeed (0x0c)
  4970. case '\f':
  4971. {
  4972. result[pos + 1] = 'f';
  4973. pos += 2;
  4974. break;
  4975. }
  4976. // newline (0x0a)
  4977. case '\n':
  4978. {
  4979. result[pos + 1] = 'n';
  4980. pos += 2;
  4981. break;
  4982. }
  4983. // carriage return (0x0d)
  4984. case '\r':
  4985. {
  4986. result[pos + 1] = 'r';
  4987. pos += 2;
  4988. break;
  4989. }
  4990. // horizontal tab (0x09)
  4991. case '\t':
  4992. {
  4993. result[pos + 1] = 't';
  4994. pos += 2;
  4995. break;
  4996. }
  4997. default:
  4998. {
  4999. if (c >= 0x00 and c <= 0x1f)
  5000. {
  5001. // convert a number 0..15 to its hex representation
  5002. // (0..f)
  5003. static const char hexify[16] =
  5004. {
  5005. '0', '1', '2', '3', '4', '5', '6', '7',
  5006. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  5007. };
  5008. // print character c as \uxxxx
  5009. for (const char m :
  5010. { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
  5011. })
  5012. {
  5013. result[++pos] = m;
  5014. }
  5015. ++pos;
  5016. }
  5017. else
  5018. {
  5019. // all other characters are added as-is
  5020. result[pos++] = c;
  5021. }
  5022. break;
  5023. }
  5024. }
  5025. }
  5026. return result;
  5027. }
  5028. /*!
  5029. @brief internal implementation of the serialization function
  5030. This function is called by the public member function dump and organizes
  5031. the serialization internally. The indentation level is propagated as
  5032. additional parameter. In case of arrays and objects, the function is
  5033. called recursively. Note that
  5034. - strings and object keys are escaped using `escape_string()`
  5035. - integer numbers are converted implicitly via `operator<<`
  5036. - floating-point numbers are converted to a string using `"%g"` format
  5037. @param[out] o stream to write to
  5038. @param[in] pretty_print whether the output shall be pretty-printed
  5039. @param[in] indent_step the indent level
  5040. @param[in] current_indent the current indent level (only used internally)
  5041. */
  5042. void dump(std::ostream& o,
  5043. const bool pretty_print,
  5044. const unsigned int indent_step,
  5045. const unsigned int current_indent = 0) const
  5046. {
  5047. // variable to hold indentation for recursive calls
  5048. unsigned int new_indent = current_indent;
  5049. switch (m_type)
  5050. {
  5051. case value_t::object:
  5052. {
  5053. if (m_value.object->empty())
  5054. {
  5055. o << "{}";
  5056. return;
  5057. }
  5058. o << "{";
  5059. // increase indentation
  5060. if (pretty_print)
  5061. {
  5062. new_indent += indent_step;
  5063. o << "\n";
  5064. }
  5065. for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
  5066. {
  5067. if (i != m_value.object->cbegin())
  5068. {
  5069. o << (pretty_print ? ",\n" : ",");
  5070. }
  5071. o << string_t(new_indent, ' ') << "\""
  5072. << escape_string(i->first) << "\":"
  5073. << (pretty_print ? " " : "");
  5074. i->second.dump(o, pretty_print, indent_step, new_indent);
  5075. }
  5076. // decrease indentation
  5077. if (pretty_print)
  5078. {
  5079. new_indent -= indent_step;
  5080. o << "\n";
  5081. }
  5082. o << string_t(new_indent, ' ') + "}";
  5083. return;
  5084. }
  5085. case value_t::array:
  5086. {
  5087. if (m_value.array->empty())
  5088. {
  5089. o << "[]";
  5090. return;
  5091. }
  5092. o << "[";
  5093. // increase indentation
  5094. if (pretty_print)
  5095. {
  5096. new_indent += indent_step;
  5097. o << "\n";
  5098. }
  5099. for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
  5100. {
  5101. if (i != m_value.array->cbegin())
  5102. {
  5103. o << (pretty_print ? ",\n" : ",");
  5104. }
  5105. o << string_t(new_indent, ' ');
  5106. i->dump(o, pretty_print, indent_step, new_indent);
  5107. }
  5108. // decrease indentation
  5109. if (pretty_print)
  5110. {
  5111. new_indent -= indent_step;
  5112. o << "\n";
  5113. }
  5114. o << string_t(new_indent, ' ') << "]";
  5115. return;
  5116. }
  5117. case value_t::string:
  5118. {
  5119. o << string_t("\"") << escape_string(*m_value.string) << "\"";
  5120. return;
  5121. }
  5122. case value_t::boolean:
  5123. {
  5124. o << (m_value.boolean ? "true" : "false");
  5125. return;
  5126. }
  5127. case value_t::number_integer:
  5128. {
  5129. o << m_value.number_integer;
  5130. return;
  5131. }
  5132. case value_t::number_unsigned:
  5133. {
  5134. o << m_value.number_unsigned;
  5135. return;
  5136. }
  5137. case value_t::number_float:
  5138. {
  5139. if (m_value.number_float == 0)
  5140. {
  5141. // special case for zero to get "0.0"/"-0.0"
  5142. o << (std::signbit(m_value.number_float) ? "-0.0" : "0.0");
  5143. }
  5144. else
  5145. {
  5146. o << m_value.number_float;
  5147. }
  5148. return;
  5149. }
  5150. case value_t::discarded:
  5151. {
  5152. o << "<discarded>";
  5153. return;
  5154. }
  5155. case value_t::null:
  5156. {
  5157. o << "null";
  5158. return;
  5159. }
  5160. }
  5161. }
  5162. private:
  5163. //////////////////////
  5164. // member variables //
  5165. //////////////////////
  5166. /// the type of the current element
  5167. value_t m_type = value_t::null;
  5168. /// the value of the current element
  5169. json_value m_value = {};
  5170. private:
  5171. ///////////////
  5172. // iterators //
  5173. ///////////////
  5174. /*!
  5175. @brief an iterator for primitive JSON types
  5176. This class models an iterator for primitive JSON types (boolean, number,
  5177. string). It's only purpose is to allow the iterator/const_iterator classes
  5178. to "iterate" over primitive values. Internally, the iterator is modeled by
  5179. a `difference_type` variable. Value begin_value (`0`) models the begin,
  5180. end_value (`1`) models past the end.
  5181. */
  5182. class primitive_iterator_t
  5183. {
  5184. public:
  5185. /// set iterator to a defined beginning
  5186. void set_begin() noexcept
  5187. {
  5188. m_it = begin_value;
  5189. }
  5190. /// set iterator to a defined past the end
  5191. void set_end() noexcept
  5192. {
  5193. m_it = end_value;
  5194. }
  5195. /// return whether the iterator can be dereferenced
  5196. constexpr bool is_begin() const noexcept
  5197. {
  5198. return (m_it == begin_value);
  5199. }
  5200. /// return whether the iterator is at end
  5201. constexpr bool is_end() const noexcept
  5202. {
  5203. return (m_it == end_value);
  5204. }
  5205. /// return reference to the value to change and compare
  5206. operator difference_type& () noexcept
  5207. {
  5208. return m_it;
  5209. }
  5210. /// return value to compare
  5211. constexpr operator difference_type () const noexcept
  5212. {
  5213. return m_it;
  5214. }
  5215. private:
  5216. static constexpr difference_type begin_value = 0;
  5217. static constexpr difference_type end_value = begin_value + 1;
  5218. /// iterator as signed integer type
  5219. difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
  5220. };
  5221. /*!
  5222. @brief an iterator value
  5223. @note This structure could easily be a union, but MSVC currently does not
  5224. allow unions members with complex constructors, see
  5225. https://github.com/nlohmann/json/pull/105.
  5226. */
  5227. struct internal_iterator
  5228. {
  5229. /// iterator for JSON objects
  5230. typename object_t::iterator object_iterator;
  5231. /// iterator for JSON arrays
  5232. typename array_t::iterator array_iterator;
  5233. /// generic iterator for all other types
  5234. primitive_iterator_t primitive_iterator;
  5235. /// create an uninitialized internal_iterator
  5236. internal_iterator() noexcept
  5237. : object_iterator(), array_iterator(), primitive_iterator()
  5238. {}
  5239. };
  5240. /// proxy class for the iterator_wrapper functions
  5241. template<typename IteratorType>
  5242. class iteration_proxy
  5243. {
  5244. private:
  5245. /// helper class for iteration
  5246. class iteration_proxy_internal
  5247. {
  5248. private:
  5249. /// the iterator
  5250. IteratorType anchor;
  5251. /// an index for arrays (used to create key names)
  5252. size_t array_index = 0;
  5253. public:
  5254. explicit iteration_proxy_internal(IteratorType it) noexcept
  5255. : anchor(it)
  5256. {}
  5257. /// dereference operator (needed for range-based for)
  5258. iteration_proxy_internal& operator*()
  5259. {
  5260. return *this;
  5261. }
  5262. /// increment operator (needed for range-based for)
  5263. iteration_proxy_internal& operator++()
  5264. {
  5265. ++anchor;
  5266. ++array_index;
  5267. return *this;
  5268. }
  5269. /// inequality operator (needed for range-based for)
  5270. bool operator!= (const iteration_proxy_internal& o) const
  5271. {
  5272. return anchor != o.anchor;
  5273. }
  5274. /// return key of the iterator
  5275. typename basic_json::string_t key() const
  5276. {
  5277. assert(anchor.m_object != nullptr);
  5278. switch (anchor.m_object->type())
  5279. {
  5280. // use integer array index as key
  5281. case value_t::array:
  5282. {
  5283. return std::to_string(array_index);
  5284. }
  5285. // use key from the object
  5286. case value_t::object:
  5287. {
  5288. return anchor.key();
  5289. }
  5290. // use an empty key for all primitive types
  5291. default:
  5292. {
  5293. return "";
  5294. }
  5295. }
  5296. }
  5297. /// return value of the iterator
  5298. typename IteratorType::reference value() const
  5299. {
  5300. return anchor.value();
  5301. }
  5302. };
  5303. /// the container to iterate
  5304. typename IteratorType::reference container;
  5305. public:
  5306. /// construct iteration proxy from a container
  5307. explicit iteration_proxy(typename IteratorType::reference cont)
  5308. : container(cont)
  5309. {}
  5310. /// return iterator begin (needed for range-based for)
  5311. iteration_proxy_internal begin() noexcept
  5312. {
  5313. return iteration_proxy_internal(container.begin());
  5314. }
  5315. /// return iterator end (needed for range-based for)
  5316. iteration_proxy_internal end() noexcept
  5317. {
  5318. return iteration_proxy_internal(container.end());
  5319. }
  5320. };
  5321. public:
  5322. /*!
  5323. @brief a const random access iterator for the @ref basic_json class
  5324. This class implements a const iterator for the @ref basic_json class. From
  5325. this class, the @ref iterator class is derived.
  5326. @note An iterator is called *initialized* when a pointer to a JSON value
  5327. has been set (e.g., by a constructor or a copy assignment). If the
  5328. iterator is default-constructed, it is *uninitialized* and most
  5329. methods are undefined. **The library uses assertions to detect calls
  5330. on uninitialized iterators.**
  5331. @requirement The class satisfies the following concept requirements:
  5332. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  5333. The iterator that can be moved to point (forward and backward) to any
  5334. element in constant time.
  5335. @since version 1.0.0
  5336. */
  5337. class const_iterator : public std::iterator<std::random_access_iterator_tag, const basic_json>
  5338. {
  5339. /// allow basic_json to access private members
  5340. friend class basic_json;
  5341. public:
  5342. /// the type of the values when the iterator is dereferenced
  5343. using value_type = typename basic_json::value_type;
  5344. /// a type to represent differences between iterators
  5345. using difference_type = typename basic_json::difference_type;
  5346. /// defines a pointer to the type iterated over (value_type)
  5347. using pointer = typename basic_json::const_pointer;
  5348. /// defines a reference to the type iterated over (value_type)
  5349. using reference = typename basic_json::const_reference;
  5350. /// the category of the iterator
  5351. using iterator_category = std::bidirectional_iterator_tag;
  5352. /// default constructor
  5353. const_iterator() = default;
  5354. /*!
  5355. @brief constructor for a given JSON instance
  5356. @param[in] object pointer to a JSON object for this iterator
  5357. @pre object != nullptr
  5358. @post The iterator is initialized; i.e. `m_object != nullptr`.
  5359. */
  5360. explicit const_iterator(pointer object) noexcept
  5361. : m_object(object)
  5362. {
  5363. assert(m_object != nullptr);
  5364. switch (m_object->m_type)
  5365. {
  5366. case basic_json::value_t::object:
  5367. {
  5368. m_it.object_iterator = typename object_t::iterator();
  5369. break;
  5370. }
  5371. case basic_json::value_t::array:
  5372. {
  5373. m_it.array_iterator = typename array_t::iterator();
  5374. break;
  5375. }
  5376. default:
  5377. {
  5378. m_it.primitive_iterator = primitive_iterator_t();
  5379. break;
  5380. }
  5381. }
  5382. }
  5383. /*!
  5384. @brief copy constructor given a non-const iterator
  5385. @param[in] other iterator to copy from
  5386. @note It is not checked whether @a other is initialized.
  5387. */
  5388. explicit const_iterator(const iterator& other) noexcept
  5389. : m_object(other.m_object)
  5390. {
  5391. if (m_object != nullptr)
  5392. {
  5393. switch (m_object->m_type)
  5394. {
  5395. case basic_json::value_t::object:
  5396. {
  5397. m_it.object_iterator = other.m_it.object_iterator;
  5398. break;
  5399. }
  5400. case basic_json::value_t::array:
  5401. {
  5402. m_it.array_iterator = other.m_it.array_iterator;
  5403. break;
  5404. }
  5405. default:
  5406. {
  5407. m_it.primitive_iterator = other.m_it.primitive_iterator;
  5408. break;
  5409. }
  5410. }
  5411. }
  5412. }
  5413. /*!
  5414. @brief copy constructor
  5415. @param[in] other iterator to copy from
  5416. @note It is not checked whether @a other is initialized.
  5417. */
  5418. const_iterator(const const_iterator& other) noexcept
  5419. : m_object(other.m_object), m_it(other.m_it)
  5420. {}
  5421. /*!
  5422. @brief copy assignment
  5423. @param[in,out] other iterator to copy from
  5424. @note It is not checked whether @a other is initialized.
  5425. */
  5426. const_iterator& operator=(const_iterator other) noexcept(
  5427. std::is_nothrow_move_constructible<pointer>::value and
  5428. std::is_nothrow_move_assignable<pointer>::value and
  5429. std::is_nothrow_move_constructible<internal_iterator>::value and
  5430. std::is_nothrow_move_assignable<internal_iterator>::value
  5431. )
  5432. {
  5433. std::swap(m_object, other.m_object);
  5434. std::swap(m_it, other.m_it);
  5435. return *this;
  5436. }
  5437. private:
  5438. /*!
  5439. @brief set the iterator to the first value
  5440. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5441. */
  5442. void set_begin() noexcept
  5443. {
  5444. assert(m_object != nullptr);
  5445. switch (m_object->m_type)
  5446. {
  5447. case basic_json::value_t::object:
  5448. {
  5449. m_it.object_iterator = m_object->m_value.object->begin();
  5450. break;
  5451. }
  5452. case basic_json::value_t::array:
  5453. {
  5454. m_it.array_iterator = m_object->m_value.array->begin();
  5455. break;
  5456. }
  5457. case basic_json::value_t::null:
  5458. {
  5459. // set to end so begin()==end() is true: null is empty
  5460. m_it.primitive_iterator.set_end();
  5461. break;
  5462. }
  5463. default:
  5464. {
  5465. m_it.primitive_iterator.set_begin();
  5466. break;
  5467. }
  5468. }
  5469. }
  5470. /*!
  5471. @brief set the iterator past the last value
  5472. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5473. */
  5474. void set_end() noexcept
  5475. {
  5476. assert(m_object != nullptr);
  5477. switch (m_object->m_type)
  5478. {
  5479. case basic_json::value_t::object:
  5480. {
  5481. m_it.object_iterator = m_object->m_value.object->end();
  5482. break;
  5483. }
  5484. case basic_json::value_t::array:
  5485. {
  5486. m_it.array_iterator = m_object->m_value.array->end();
  5487. break;
  5488. }
  5489. default:
  5490. {
  5491. m_it.primitive_iterator.set_end();
  5492. break;
  5493. }
  5494. }
  5495. }
  5496. public:
  5497. /*!
  5498. @brief return a reference to the value pointed to by the iterator
  5499. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5500. */
  5501. reference operator*() const
  5502. {
  5503. assert(m_object != nullptr);
  5504. switch (m_object->m_type)
  5505. {
  5506. case basic_json::value_t::object:
  5507. {
  5508. assert(m_it.object_iterator != m_object->m_value.object->end());
  5509. return m_it.object_iterator->second;
  5510. }
  5511. case basic_json::value_t::array:
  5512. {
  5513. assert(m_it.array_iterator != m_object->m_value.array->end());
  5514. return *m_it.array_iterator;
  5515. }
  5516. case basic_json::value_t::null:
  5517. {
  5518. throw std::out_of_range("cannot get value");
  5519. }
  5520. default:
  5521. {
  5522. if (m_it.primitive_iterator.is_begin())
  5523. {
  5524. return *m_object;
  5525. }
  5526. else
  5527. {
  5528. throw std::out_of_range("cannot get value");
  5529. }
  5530. }
  5531. }
  5532. }
  5533. /*!
  5534. @brief dereference the iterator
  5535. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5536. */
  5537. pointer operator->() const
  5538. {
  5539. assert(m_object != nullptr);
  5540. switch (m_object->m_type)
  5541. {
  5542. case basic_json::value_t::object:
  5543. {
  5544. assert(m_it.object_iterator != m_object->m_value.object->end());
  5545. return &(m_it.object_iterator->second);
  5546. }
  5547. case basic_json::value_t::array:
  5548. {
  5549. assert(m_it.array_iterator != m_object->m_value.array->end());
  5550. return &*m_it.array_iterator;
  5551. }
  5552. default:
  5553. {
  5554. if (m_it.primitive_iterator.is_begin())
  5555. {
  5556. return m_object;
  5557. }
  5558. else
  5559. {
  5560. throw std::out_of_range("cannot get value");
  5561. }
  5562. }
  5563. }
  5564. }
  5565. /*!
  5566. @brief post-increment (it++)
  5567. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5568. */
  5569. const_iterator operator++(int)
  5570. {
  5571. auto result = *this;
  5572. ++(*this);
  5573. return result;
  5574. }
  5575. /*!
  5576. @brief pre-increment (++it)
  5577. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5578. */
  5579. const_iterator& operator++()
  5580. {
  5581. assert(m_object != nullptr);
  5582. switch (m_object->m_type)
  5583. {
  5584. case basic_json::value_t::object:
  5585. {
  5586. std::advance(m_it.object_iterator, 1);
  5587. break;
  5588. }
  5589. case basic_json::value_t::array:
  5590. {
  5591. std::advance(m_it.array_iterator, 1);
  5592. break;
  5593. }
  5594. default:
  5595. {
  5596. ++m_it.primitive_iterator;
  5597. break;
  5598. }
  5599. }
  5600. return *this;
  5601. }
  5602. /*!
  5603. @brief post-decrement (it--)
  5604. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5605. */
  5606. const_iterator operator--(int)
  5607. {
  5608. auto result = *this;
  5609. --(*this);
  5610. return result;
  5611. }
  5612. /*!
  5613. @brief pre-decrement (--it)
  5614. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5615. */
  5616. const_iterator& operator--()
  5617. {
  5618. assert(m_object != nullptr);
  5619. switch (m_object->m_type)
  5620. {
  5621. case basic_json::value_t::object:
  5622. {
  5623. std::advance(m_it.object_iterator, -1);
  5624. break;
  5625. }
  5626. case basic_json::value_t::array:
  5627. {
  5628. std::advance(m_it.array_iterator, -1);
  5629. break;
  5630. }
  5631. default:
  5632. {
  5633. --m_it.primitive_iterator;
  5634. break;
  5635. }
  5636. }
  5637. return *this;
  5638. }
  5639. /*!
  5640. @brief comparison: equal
  5641. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5642. */
  5643. bool operator==(const const_iterator& other) const
  5644. {
  5645. // if objects are not the same, the comparison is undefined
  5646. if (m_object != other.m_object)
  5647. {
  5648. throw std::domain_error("cannot compare iterators of different containers");
  5649. }
  5650. assert(m_object != nullptr);
  5651. switch (m_object->m_type)
  5652. {
  5653. case basic_json::value_t::object:
  5654. {
  5655. return (m_it.object_iterator == other.m_it.object_iterator);
  5656. }
  5657. case basic_json::value_t::array:
  5658. {
  5659. return (m_it.array_iterator == other.m_it.array_iterator);
  5660. }
  5661. default:
  5662. {
  5663. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  5664. }
  5665. }
  5666. }
  5667. /*!
  5668. @brief comparison: not equal
  5669. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5670. */
  5671. bool operator!=(const const_iterator& other) const
  5672. {
  5673. return not operator==(other);
  5674. }
  5675. /*!
  5676. @brief comparison: smaller
  5677. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5678. */
  5679. bool operator<(const const_iterator& other) const
  5680. {
  5681. // if objects are not the same, the comparison is undefined
  5682. if (m_object != other.m_object)
  5683. {
  5684. throw std::domain_error("cannot compare iterators of different containers");
  5685. }
  5686. assert(m_object != nullptr);
  5687. switch (m_object->m_type)
  5688. {
  5689. case basic_json::value_t::object:
  5690. {
  5691. throw std::domain_error("cannot compare order of object iterators");
  5692. }
  5693. case basic_json::value_t::array:
  5694. {
  5695. return (m_it.array_iterator < other.m_it.array_iterator);
  5696. }
  5697. default:
  5698. {
  5699. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  5700. }
  5701. }
  5702. }
  5703. /*!
  5704. @brief comparison: less than or equal
  5705. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5706. */
  5707. bool operator<=(const const_iterator& other) const
  5708. {
  5709. return not other.operator < (*this);
  5710. }
  5711. /*!
  5712. @brief comparison: greater than
  5713. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5714. */
  5715. bool operator>(const const_iterator& other) const
  5716. {
  5717. return not operator<=(other);
  5718. }
  5719. /*!
  5720. @brief comparison: greater than or equal
  5721. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5722. */
  5723. bool operator>=(const const_iterator& other) const
  5724. {
  5725. return not operator<(other);
  5726. }
  5727. /*!
  5728. @brief add to iterator
  5729. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5730. */
  5731. const_iterator& operator+=(difference_type i)
  5732. {
  5733. assert(m_object != nullptr);
  5734. switch (m_object->m_type)
  5735. {
  5736. case basic_json::value_t::object:
  5737. {
  5738. throw std::domain_error("cannot use offsets with object iterators");
  5739. }
  5740. case basic_json::value_t::array:
  5741. {
  5742. std::advance(m_it.array_iterator, i);
  5743. break;
  5744. }
  5745. default:
  5746. {
  5747. m_it.primitive_iterator += i;
  5748. break;
  5749. }
  5750. }
  5751. return *this;
  5752. }
  5753. /*!
  5754. @brief subtract from iterator
  5755. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5756. */
  5757. const_iterator& operator-=(difference_type i)
  5758. {
  5759. return operator+=(-i);
  5760. }
  5761. /*!
  5762. @brief add to iterator
  5763. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5764. */
  5765. const_iterator operator+(difference_type i)
  5766. {
  5767. auto result = *this;
  5768. result += i;
  5769. return result;
  5770. }
  5771. /*!
  5772. @brief subtract from iterator
  5773. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5774. */
  5775. const_iterator operator-(difference_type i)
  5776. {
  5777. auto result = *this;
  5778. result -= i;
  5779. return result;
  5780. }
  5781. /*!
  5782. @brief return difference
  5783. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5784. */
  5785. difference_type operator-(const const_iterator& other) const
  5786. {
  5787. assert(m_object != nullptr);
  5788. switch (m_object->m_type)
  5789. {
  5790. case basic_json::value_t::object:
  5791. {
  5792. throw std::domain_error("cannot use offsets with object iterators");
  5793. }
  5794. case basic_json::value_t::array:
  5795. {
  5796. return m_it.array_iterator - other.m_it.array_iterator;
  5797. }
  5798. default:
  5799. {
  5800. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  5801. }
  5802. }
  5803. }
  5804. /*!
  5805. @brief access to successor
  5806. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5807. */
  5808. reference operator[](difference_type n) const
  5809. {
  5810. assert(m_object != nullptr);
  5811. switch (m_object->m_type)
  5812. {
  5813. case basic_json::value_t::object:
  5814. {
  5815. throw std::domain_error("cannot use operator[] for object iterators");
  5816. }
  5817. case basic_json::value_t::array:
  5818. {
  5819. return *std::next(m_it.array_iterator, n);
  5820. }
  5821. case basic_json::value_t::null:
  5822. {
  5823. throw std::out_of_range("cannot get value");
  5824. }
  5825. default:
  5826. {
  5827. if (m_it.primitive_iterator == -n)
  5828. {
  5829. return *m_object;
  5830. }
  5831. else
  5832. {
  5833. throw std::out_of_range("cannot get value");
  5834. }
  5835. }
  5836. }
  5837. }
  5838. /*!
  5839. @brief return the key of an object iterator
  5840. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5841. */
  5842. typename object_t::key_type key() const
  5843. {
  5844. assert(m_object != nullptr);
  5845. if (m_object->is_object())
  5846. {
  5847. return m_it.object_iterator->first;
  5848. }
  5849. else
  5850. {
  5851. throw std::domain_error("cannot use key() for non-object iterators");
  5852. }
  5853. }
  5854. /*!
  5855. @brief return the value of an iterator
  5856. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  5857. */
  5858. reference value() const
  5859. {
  5860. return operator*();
  5861. }
  5862. private:
  5863. /// associated JSON instance
  5864. pointer m_object = nullptr;
  5865. /// the actual iterator of the associated instance
  5866. internal_iterator m_it = internal_iterator();
  5867. };
  5868. /*!
  5869. @brief a mutable random access iterator for the @ref basic_json class
  5870. @requirement The class satisfies the following concept requirements:
  5871. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  5872. The iterator that can be moved to point (forward and backward) to any
  5873. element in constant time.
  5874. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  5875. It is possible to write to the pointed-to element.
  5876. @since version 1.0.0
  5877. */
  5878. class iterator : public const_iterator
  5879. {
  5880. public:
  5881. using base_iterator = const_iterator;
  5882. using pointer = typename basic_json::pointer;
  5883. using reference = typename basic_json::reference;
  5884. /// default constructor
  5885. iterator() = default;
  5886. /// constructor for a given JSON instance
  5887. explicit iterator(pointer object) noexcept
  5888. : base_iterator(object)
  5889. {}
  5890. /// copy constructor
  5891. iterator(const iterator& other) noexcept
  5892. : base_iterator(other)
  5893. {}
  5894. /// copy assignment
  5895. iterator& operator=(iterator other) noexcept(
  5896. std::is_nothrow_move_constructible<pointer>::value and
  5897. std::is_nothrow_move_assignable<pointer>::value and
  5898. std::is_nothrow_move_constructible<internal_iterator>::value and
  5899. std::is_nothrow_move_assignable<internal_iterator>::value
  5900. )
  5901. {
  5902. base_iterator::operator=(other);
  5903. return *this;
  5904. }
  5905. /// return a reference to the value pointed to by the iterator
  5906. reference operator*() const
  5907. {
  5908. return const_cast<reference>(base_iterator::operator*());
  5909. }
  5910. /// dereference the iterator
  5911. pointer operator->() const
  5912. {
  5913. return const_cast<pointer>(base_iterator::operator->());
  5914. }
  5915. /// post-increment (it++)
  5916. iterator operator++(int)
  5917. {
  5918. iterator result = *this;
  5919. base_iterator::operator++();
  5920. return result;
  5921. }
  5922. /// pre-increment (++it)
  5923. iterator& operator++()
  5924. {
  5925. base_iterator::operator++();
  5926. return *this;
  5927. }
  5928. /// post-decrement (it--)
  5929. iterator operator--(int)
  5930. {
  5931. iterator result = *this;
  5932. base_iterator::operator--();
  5933. return result;
  5934. }
  5935. /// pre-decrement (--it)
  5936. iterator& operator--()
  5937. {
  5938. base_iterator::operator--();
  5939. return *this;
  5940. }
  5941. /// add to iterator
  5942. iterator& operator+=(difference_type i)
  5943. {
  5944. base_iterator::operator+=(i);
  5945. return *this;
  5946. }
  5947. /// subtract from iterator
  5948. iterator& operator-=(difference_type i)
  5949. {
  5950. base_iterator::operator-=(i);
  5951. return *this;
  5952. }
  5953. /// add to iterator
  5954. iterator operator+(difference_type i)
  5955. {
  5956. auto result = *this;
  5957. result += i;
  5958. return result;
  5959. }
  5960. /// subtract from iterator
  5961. iterator operator-(difference_type i)
  5962. {
  5963. auto result = *this;
  5964. result -= i;
  5965. return result;
  5966. }
  5967. /// return difference
  5968. difference_type operator-(const iterator& other) const
  5969. {
  5970. return base_iterator::operator-(other);
  5971. }
  5972. /// access to successor
  5973. reference operator[](difference_type n) const
  5974. {
  5975. return const_cast<reference>(base_iterator::operator[](n));
  5976. }
  5977. /// return the value of an iterator
  5978. reference value() const
  5979. {
  5980. return const_cast<reference>(base_iterator::value());
  5981. }
  5982. };
  5983. /*!
  5984. @brief a template for a reverse iterator class
  5985. @tparam Base the base iterator type to reverse. Valid types are @ref
  5986. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  5987. create @ref const_reverse_iterator).
  5988. @requirement The class satisfies the following concept requirements:
  5989. - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  5990. The iterator that can be moved to point (forward and backward) to any
  5991. element in constant time.
  5992. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  5993. It is possible to write to the pointed-to element (only if @a Base is
  5994. @ref iterator).
  5995. @since version 1.0.0
  5996. */
  5997. template<typename Base>
  5998. class json_reverse_iterator : public std::reverse_iterator<Base>
  5999. {
  6000. public:
  6001. /// shortcut to the reverse iterator adaptor
  6002. using base_iterator = std::reverse_iterator<Base>;
  6003. /// the reference type for the pointed-to element
  6004. using reference = typename Base::reference;
  6005. /// create reverse iterator from iterator
  6006. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  6007. : base_iterator(it)
  6008. {}
  6009. /// create reverse iterator from base class
  6010. json_reverse_iterator(const base_iterator& it) noexcept
  6011. : base_iterator(it)
  6012. {}
  6013. /// post-increment (it++)
  6014. json_reverse_iterator operator++(int)
  6015. {
  6016. return base_iterator::operator++(1);
  6017. }
  6018. /// pre-increment (++it)
  6019. json_reverse_iterator& operator++()
  6020. {
  6021. base_iterator::operator++();
  6022. return *this;
  6023. }
  6024. /// post-decrement (it--)
  6025. json_reverse_iterator operator--(int)
  6026. {
  6027. return base_iterator::operator--(1);
  6028. }
  6029. /// pre-decrement (--it)
  6030. json_reverse_iterator& operator--()
  6031. {
  6032. base_iterator::operator--();
  6033. return *this;
  6034. }
  6035. /// add to iterator
  6036. json_reverse_iterator& operator+=(difference_type i)
  6037. {
  6038. base_iterator::operator+=(i);
  6039. return *this;
  6040. }
  6041. /// add to iterator
  6042. json_reverse_iterator operator+(difference_type i) const
  6043. {
  6044. auto result = *this;
  6045. result += i;
  6046. return result;
  6047. }
  6048. /// subtract from iterator
  6049. json_reverse_iterator operator-(difference_type i) const
  6050. {
  6051. auto result = *this;
  6052. result -= i;
  6053. return result;
  6054. }
  6055. /// return difference
  6056. difference_type operator-(const json_reverse_iterator& other) const
  6057. {
  6058. return this->base() - other.base();
  6059. }
  6060. /// access to successor
  6061. reference operator[](difference_type n) const
  6062. {
  6063. return *(this->operator+(n));
  6064. }
  6065. /// return the key of an object iterator
  6066. typename object_t::key_type key() const
  6067. {
  6068. auto it = --this->base();
  6069. return it.key();
  6070. }
  6071. /// return the value of an iterator
  6072. reference value() const
  6073. {
  6074. auto it = --this->base();
  6075. return it.operator * ();
  6076. }
  6077. };
  6078. private:
  6079. //////////////////////
  6080. // lexer and parser //
  6081. //////////////////////
  6082. /*!
  6083. @brief lexical analysis
  6084. This class organizes the lexical analysis during JSON deserialization. The
  6085. core of it is a scanner generated by [re2c](http://re2c.org) that
  6086. processes a buffer and recognizes tokens according to RFC 7159.
  6087. */
  6088. class lexer
  6089. {
  6090. public:
  6091. /// token types for the parser
  6092. enum class token_type
  6093. {
  6094. uninitialized, ///< indicating the scanner is uninitialized
  6095. literal_true, ///< the `true` literal
  6096. literal_false, ///< the `false` literal
  6097. literal_null, ///< the `null` literal
  6098. value_string, ///< a string -- use get_string() for actual value
  6099. value_number, ///< a number -- use get_number() for actual value
  6100. begin_array, ///< the character for array begin `[`
  6101. begin_object, ///< the character for object begin `{`
  6102. end_array, ///< the character for array end `]`
  6103. end_object, ///< the character for object end `}`
  6104. name_separator, ///< the name separator `:`
  6105. value_separator, ///< the value separator `,`
  6106. parse_error, ///< indicating a parse error
  6107. end_of_input ///< indicating the end of the input buffer
  6108. };
  6109. /// the char type to use in the lexer
  6110. using lexer_char_t = unsigned char;
  6111. /// a lexer from a buffer with given length
  6112. lexer(const lexer_char_t* buff, const size_t len) noexcept
  6113. : m_content(buff)
  6114. {
  6115. assert(m_content != nullptr);
  6116. m_start = m_cursor = m_content;
  6117. m_limit = m_content + len;
  6118. }
  6119. /// a lexer from an input stream
  6120. explicit lexer(std::istream& s)
  6121. : m_stream(&s), m_line_buffer()
  6122. {
  6123. // fill buffer
  6124. fill_line_buffer();
  6125. // skip UTF-8 byte-order mark
  6126. if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF")
  6127. {
  6128. m_line_buffer[0] = ' ';
  6129. m_line_buffer[1] = ' ';
  6130. m_line_buffer[2] = ' ';
  6131. }
  6132. }
  6133. // switch off unwanted functions (due to pointer members)
  6134. lexer() = delete;
  6135. lexer(const lexer&) = delete;
  6136. lexer operator=(const lexer&) = delete;
  6137. /*!
  6138. @brief create a string from one or two Unicode code points
  6139. There are two cases: (1) @a codepoint1 is in the Basic Multilingual
  6140. Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2)
  6141. @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to
  6142. represent a code point above U+FFFF.
  6143. @param[in] codepoint1 the code point (can be high surrogate)
  6144. @param[in] codepoint2 the code point (can be low surrogate or 0)
  6145. @return string representation of the code point; the length of the
  6146. result string is between 1 and 4 characters.
  6147. @throw std::out_of_range if code point is > 0x10ffff; example: `"code
  6148. points above 0x10FFFF are invalid"`
  6149. @throw std::invalid_argument if the low surrogate is invalid; example:
  6150. `""missing or wrong low surrogate""`
  6151. @complexity Constant.
  6152. @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
  6153. */
  6154. static string_t to_unicode(const std::size_t codepoint1,
  6155. const std::size_t codepoint2 = 0)
  6156. {
  6157. // calculate the code point from the given code points
  6158. std::size_t codepoint = codepoint1;
  6159. // check if codepoint1 is a high surrogate
  6160. if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
  6161. {
  6162. // check if codepoint2 is a low surrogate
  6163. if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
  6164. {
  6165. codepoint =
  6166. // high surrogate occupies the most significant 22 bits
  6167. (codepoint1 << 10)
  6168. // low surrogate occupies the least significant 15 bits
  6169. + codepoint2
  6170. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  6171. // in the result so we have to subtract with:
  6172. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  6173. - 0x35FDC00;
  6174. }
  6175. else
  6176. {
  6177. throw std::invalid_argument("missing or wrong low surrogate");
  6178. }
  6179. }
  6180. string_t result;
  6181. if (codepoint < 0x80)
  6182. {
  6183. // 1-byte characters: 0xxxxxxx (ASCII)
  6184. result.append(1, static_cast<typename string_t::value_type>(codepoint));
  6185. }
  6186. else if (codepoint <= 0x7ff)
  6187. {
  6188. // 2-byte characters: 110xxxxx 10xxxxxx
  6189. result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
  6190. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  6191. }
  6192. else if (codepoint <= 0xffff)
  6193. {
  6194. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  6195. result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
  6196. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  6197. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  6198. }
  6199. else if (codepoint <= 0x10ffff)
  6200. {
  6201. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  6202. result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
  6203. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
  6204. result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
  6205. result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
  6206. }
  6207. else
  6208. {
  6209. throw std::out_of_range("code points above 0x10FFFF are invalid");
  6210. }
  6211. return result;
  6212. }
  6213. /// return name of values of type token_type (only used for errors)
  6214. static std::string token_type_name(const token_type t)
  6215. {
  6216. switch (t)
  6217. {
  6218. case token_type::uninitialized:
  6219. return "<uninitialized>";
  6220. case token_type::literal_true:
  6221. return "true literal";
  6222. case token_type::literal_false:
  6223. return "false literal";
  6224. case token_type::literal_null:
  6225. return "null literal";
  6226. case token_type::value_string:
  6227. return "string literal";
  6228. case token_type::value_number:
  6229. return "number literal";
  6230. case token_type::begin_array:
  6231. return "'['";
  6232. case token_type::begin_object:
  6233. return "'{'";
  6234. case token_type::end_array:
  6235. return "']'";
  6236. case token_type::end_object:
  6237. return "'}'";
  6238. case token_type::name_separator:
  6239. return "':'";
  6240. case token_type::value_separator:
  6241. return "','";
  6242. case token_type::parse_error:
  6243. return "<parse error>";
  6244. case token_type::end_of_input:
  6245. return "end of input";
  6246. default:
  6247. {
  6248. // catch non-enum values
  6249. return "unknown token"; // LCOV_EXCL_LINE
  6250. }
  6251. }
  6252. }
  6253. /*!
  6254. This function implements a scanner for JSON. It is specified using
  6255. regular expressions that try to follow RFC 7159 as close as possible.
  6256. These regular expressions are then translated into a minimized
  6257. deterministic finite automaton (DFA) by the tool
  6258. [re2c](http://re2c.org). As a result, the translated code for this
  6259. function consists of a large block of code with `goto` jumps.
  6260. @return the class of the next token read from the buffer
  6261. @complexity Linear in the length of the input.\n
  6262. Proposition: The loop below will always terminate for finite input.\n
  6263. Proof (by contradiction): Assume a finite input. To loop forever, the
  6264. loop must never hit code with a `break` statement. The only code
  6265. snippets without a `break` statement are the continue statements for
  6266. whitespace and byte-order-marks. To loop forever, the input must be an
  6267. infinite sequence of whitespace or byte-order-marks. This contradicts
  6268. the assumption of finite input, q.e.d.
  6269. */
  6270. token_type scan()
  6271. {
  6272. while (true)
  6273. {
  6274. // pointer for backtracking information
  6275. m_marker = nullptr;
  6276. // remember the begin of the token
  6277. m_start = m_cursor;
  6278. assert(m_start != nullptr);
  6279. {
  6280. lexer_char_t yych;
  6281. unsigned int yyaccept = 0;
  6282. static const unsigned char yybm[] =
  6283. {
  6284. 0, 0, 0, 0, 0, 0, 0, 0,
  6285. 0, 32, 32, 0, 0, 32, 0, 0,
  6286. 0, 0, 0, 0, 0, 0, 0, 0,
  6287. 0, 0, 0, 0, 0, 0, 0, 0,
  6288. 160, 128, 0, 128, 128, 128, 128, 128,
  6289. 128, 128, 128, 128, 128, 128, 128, 128,
  6290. 192, 192, 192, 192, 192, 192, 192, 192,
  6291. 192, 192, 128, 128, 128, 128, 128, 128,
  6292. 128, 128, 128, 128, 128, 128, 128, 128,
  6293. 128, 128, 128, 128, 128, 128, 128, 128,
  6294. 128, 128, 128, 128, 128, 128, 128, 128,
  6295. 128, 128, 128, 128, 0, 128, 128, 128,
  6296. 128, 128, 128, 128, 128, 128, 128, 128,
  6297. 128, 128, 128, 128, 128, 128, 128, 128,
  6298. 128, 128, 128, 128, 128, 128, 128, 128,
  6299. 128, 128, 128, 128, 128, 128, 128, 128,
  6300. 0, 0, 0, 0, 0, 0, 0, 0,
  6301. 0, 0, 0, 0, 0, 0, 0, 0,
  6302. 0, 0, 0, 0, 0, 0, 0, 0,
  6303. 0, 0, 0, 0, 0, 0, 0, 0,
  6304. 0, 0, 0, 0, 0, 0, 0, 0,
  6305. 0, 0, 0, 0, 0, 0, 0, 0,
  6306. 0, 0, 0, 0, 0, 0, 0, 0,
  6307. 0, 0, 0, 0, 0, 0, 0, 0,
  6308. 0, 0, 0, 0, 0, 0, 0, 0,
  6309. 0, 0, 0, 0, 0, 0, 0, 0,
  6310. 0, 0, 0, 0, 0, 0, 0, 0,
  6311. 0, 0, 0, 0, 0, 0, 0, 0,
  6312. 0, 0, 0, 0, 0, 0, 0, 0,
  6313. 0, 0, 0, 0, 0, 0, 0, 0,
  6314. 0, 0, 0, 0, 0, 0, 0, 0,
  6315. 0, 0, 0, 0, 0, 0, 0, 0,
  6316. };
  6317. if ((m_limit - m_cursor) < 5)
  6318. {
  6319. fill_line_buffer(5); // LCOV_EXCL_LINE
  6320. }
  6321. yych = *m_cursor;
  6322. if (yybm[0 + yych] & 32)
  6323. {
  6324. goto basic_json_parser_6;
  6325. }
  6326. if (yych <= '[')
  6327. {
  6328. if (yych <= '-')
  6329. {
  6330. if (yych <= '"')
  6331. {
  6332. if (yych <= 0x00)
  6333. {
  6334. goto basic_json_parser_2;
  6335. }
  6336. if (yych <= '!')
  6337. {
  6338. goto basic_json_parser_4;
  6339. }
  6340. goto basic_json_parser_9;
  6341. }
  6342. else
  6343. {
  6344. if (yych <= '+')
  6345. {
  6346. goto basic_json_parser_4;
  6347. }
  6348. if (yych <= ',')
  6349. {
  6350. goto basic_json_parser_10;
  6351. }
  6352. goto basic_json_parser_12;
  6353. }
  6354. }
  6355. else
  6356. {
  6357. if (yych <= '9')
  6358. {
  6359. if (yych <= '/')
  6360. {
  6361. goto basic_json_parser_4;
  6362. }
  6363. if (yych <= '0')
  6364. {
  6365. goto basic_json_parser_13;
  6366. }
  6367. goto basic_json_parser_15;
  6368. }
  6369. else
  6370. {
  6371. if (yych <= ':')
  6372. {
  6373. goto basic_json_parser_17;
  6374. }
  6375. if (yych <= 'Z')
  6376. {
  6377. goto basic_json_parser_4;
  6378. }
  6379. goto basic_json_parser_19;
  6380. }
  6381. }
  6382. }
  6383. else
  6384. {
  6385. if (yych <= 'n')
  6386. {
  6387. if (yych <= 'e')
  6388. {
  6389. if (yych == ']')
  6390. {
  6391. goto basic_json_parser_21;
  6392. }
  6393. goto basic_json_parser_4;
  6394. }
  6395. else
  6396. {
  6397. if (yych <= 'f')
  6398. {
  6399. goto basic_json_parser_23;
  6400. }
  6401. if (yych <= 'm')
  6402. {
  6403. goto basic_json_parser_4;
  6404. }
  6405. goto basic_json_parser_24;
  6406. }
  6407. }
  6408. else
  6409. {
  6410. if (yych <= 'z')
  6411. {
  6412. if (yych == 't')
  6413. {
  6414. goto basic_json_parser_25;
  6415. }
  6416. goto basic_json_parser_4;
  6417. }
  6418. else
  6419. {
  6420. if (yych <= '{')
  6421. {
  6422. goto basic_json_parser_26;
  6423. }
  6424. if (yych == '}')
  6425. {
  6426. goto basic_json_parser_28;
  6427. }
  6428. goto basic_json_parser_4;
  6429. }
  6430. }
  6431. }
  6432. basic_json_parser_2:
  6433. ++m_cursor;
  6434. {
  6435. last_token_type = token_type::end_of_input;
  6436. break;
  6437. }
  6438. basic_json_parser_4:
  6439. ++m_cursor;
  6440. basic_json_parser_5:
  6441. {
  6442. last_token_type = token_type::parse_error;
  6443. break;
  6444. }
  6445. basic_json_parser_6:
  6446. ++m_cursor;
  6447. if (m_limit <= m_cursor)
  6448. {
  6449. fill_line_buffer(1); // LCOV_EXCL_LINE
  6450. }
  6451. yych = *m_cursor;
  6452. if (yybm[0 + yych] & 32)
  6453. {
  6454. goto basic_json_parser_6;
  6455. }
  6456. {
  6457. continue;
  6458. }
  6459. basic_json_parser_9:
  6460. yyaccept = 0;
  6461. yych = *(m_marker = ++m_cursor);
  6462. if (yych <= 0x1F)
  6463. {
  6464. goto basic_json_parser_5;
  6465. }
  6466. if (yych <= 0x7F)
  6467. {
  6468. goto basic_json_parser_31;
  6469. }
  6470. if (yych <= 0xC1)
  6471. {
  6472. goto basic_json_parser_5;
  6473. }
  6474. if (yych <= 0xF4)
  6475. {
  6476. goto basic_json_parser_31;
  6477. }
  6478. goto basic_json_parser_5;
  6479. basic_json_parser_10:
  6480. ++m_cursor;
  6481. {
  6482. last_token_type = token_type::value_separator;
  6483. break;
  6484. }
  6485. basic_json_parser_12:
  6486. yych = *++m_cursor;
  6487. if (yych <= '/')
  6488. {
  6489. goto basic_json_parser_5;
  6490. }
  6491. if (yych <= '0')
  6492. {
  6493. goto basic_json_parser_13;
  6494. }
  6495. if (yych <= '9')
  6496. {
  6497. goto basic_json_parser_15;
  6498. }
  6499. goto basic_json_parser_5;
  6500. basic_json_parser_13:
  6501. yyaccept = 1;
  6502. yych = *(m_marker = ++m_cursor);
  6503. if (yych <= 'D')
  6504. {
  6505. if (yych == '.')
  6506. {
  6507. goto basic_json_parser_43;
  6508. }
  6509. }
  6510. else
  6511. {
  6512. if (yych <= 'E')
  6513. {
  6514. goto basic_json_parser_44;
  6515. }
  6516. if (yych == 'e')
  6517. {
  6518. goto basic_json_parser_44;
  6519. }
  6520. }
  6521. basic_json_parser_14:
  6522. {
  6523. last_token_type = token_type::value_number;
  6524. break;
  6525. }
  6526. basic_json_parser_15:
  6527. yyaccept = 1;
  6528. m_marker = ++m_cursor;
  6529. if ((m_limit - m_cursor) < 3)
  6530. {
  6531. fill_line_buffer(3); // LCOV_EXCL_LINE
  6532. }
  6533. yych = *m_cursor;
  6534. if (yybm[0 + yych] & 64)
  6535. {
  6536. goto basic_json_parser_15;
  6537. }
  6538. if (yych <= 'D')
  6539. {
  6540. if (yych == '.')
  6541. {
  6542. goto basic_json_parser_43;
  6543. }
  6544. goto basic_json_parser_14;
  6545. }
  6546. else
  6547. {
  6548. if (yych <= 'E')
  6549. {
  6550. goto basic_json_parser_44;
  6551. }
  6552. if (yych == 'e')
  6553. {
  6554. goto basic_json_parser_44;
  6555. }
  6556. goto basic_json_parser_14;
  6557. }
  6558. basic_json_parser_17:
  6559. ++m_cursor;
  6560. {
  6561. last_token_type = token_type::name_separator;
  6562. break;
  6563. }
  6564. basic_json_parser_19:
  6565. ++m_cursor;
  6566. {
  6567. last_token_type = token_type::begin_array;
  6568. break;
  6569. }
  6570. basic_json_parser_21:
  6571. ++m_cursor;
  6572. {
  6573. last_token_type = token_type::end_array;
  6574. break;
  6575. }
  6576. basic_json_parser_23:
  6577. yyaccept = 0;
  6578. yych = *(m_marker = ++m_cursor);
  6579. if (yych == 'a')
  6580. {
  6581. goto basic_json_parser_45;
  6582. }
  6583. goto basic_json_parser_5;
  6584. basic_json_parser_24:
  6585. yyaccept = 0;
  6586. yych = *(m_marker = ++m_cursor);
  6587. if (yych == 'u')
  6588. {
  6589. goto basic_json_parser_46;
  6590. }
  6591. goto basic_json_parser_5;
  6592. basic_json_parser_25:
  6593. yyaccept = 0;
  6594. yych = *(m_marker = ++m_cursor);
  6595. if (yych == 'r')
  6596. {
  6597. goto basic_json_parser_47;
  6598. }
  6599. goto basic_json_parser_5;
  6600. basic_json_parser_26:
  6601. ++m_cursor;
  6602. {
  6603. last_token_type = token_type::begin_object;
  6604. break;
  6605. }
  6606. basic_json_parser_28:
  6607. ++m_cursor;
  6608. {
  6609. last_token_type = token_type::end_object;
  6610. break;
  6611. }
  6612. basic_json_parser_30:
  6613. ++m_cursor;
  6614. if (m_limit <= m_cursor)
  6615. {
  6616. fill_line_buffer(1); // LCOV_EXCL_LINE
  6617. }
  6618. yych = *m_cursor;
  6619. basic_json_parser_31:
  6620. if (yybm[0 + yych] & 128)
  6621. {
  6622. goto basic_json_parser_30;
  6623. }
  6624. if (yych <= 0xE0)
  6625. {
  6626. if (yych <= '\\')
  6627. {
  6628. if (yych <= 0x1F)
  6629. {
  6630. goto basic_json_parser_32;
  6631. }
  6632. if (yych <= '"')
  6633. {
  6634. goto basic_json_parser_33;
  6635. }
  6636. goto basic_json_parser_35;
  6637. }
  6638. else
  6639. {
  6640. if (yych <= 0xC1)
  6641. {
  6642. goto basic_json_parser_32;
  6643. }
  6644. if (yych <= 0xDF)
  6645. {
  6646. goto basic_json_parser_36;
  6647. }
  6648. goto basic_json_parser_37;
  6649. }
  6650. }
  6651. else
  6652. {
  6653. if (yych <= 0xEF)
  6654. {
  6655. if (yych == 0xED)
  6656. {
  6657. goto basic_json_parser_39;
  6658. }
  6659. goto basic_json_parser_38;
  6660. }
  6661. else
  6662. {
  6663. if (yych <= 0xF0)
  6664. {
  6665. goto basic_json_parser_40;
  6666. }
  6667. if (yych <= 0xF3)
  6668. {
  6669. goto basic_json_parser_41;
  6670. }
  6671. if (yych <= 0xF4)
  6672. {
  6673. goto basic_json_parser_42;
  6674. }
  6675. }
  6676. }
  6677. basic_json_parser_32:
  6678. m_cursor = m_marker;
  6679. if (yyaccept == 0)
  6680. {
  6681. goto basic_json_parser_5;
  6682. }
  6683. else
  6684. {
  6685. goto basic_json_parser_14;
  6686. }
  6687. basic_json_parser_33:
  6688. ++m_cursor;
  6689. {
  6690. last_token_type = token_type::value_string;
  6691. break;
  6692. }
  6693. basic_json_parser_35:
  6694. ++m_cursor;
  6695. if (m_limit <= m_cursor)
  6696. {
  6697. fill_line_buffer(1); // LCOV_EXCL_LINE
  6698. }
  6699. yych = *m_cursor;
  6700. if (yych <= 'e')
  6701. {
  6702. if (yych <= '/')
  6703. {
  6704. if (yych == '"')
  6705. {
  6706. goto basic_json_parser_30;
  6707. }
  6708. if (yych <= '.')
  6709. {
  6710. goto basic_json_parser_32;
  6711. }
  6712. goto basic_json_parser_30;
  6713. }
  6714. else
  6715. {
  6716. if (yych <= '\\')
  6717. {
  6718. if (yych <= '[')
  6719. {
  6720. goto basic_json_parser_32;
  6721. }
  6722. goto basic_json_parser_30;
  6723. }
  6724. else
  6725. {
  6726. if (yych == 'b')
  6727. {
  6728. goto basic_json_parser_30;
  6729. }
  6730. goto basic_json_parser_32;
  6731. }
  6732. }
  6733. }
  6734. else
  6735. {
  6736. if (yych <= 'q')
  6737. {
  6738. if (yych <= 'f')
  6739. {
  6740. goto basic_json_parser_30;
  6741. }
  6742. if (yych == 'n')
  6743. {
  6744. goto basic_json_parser_30;
  6745. }
  6746. goto basic_json_parser_32;
  6747. }
  6748. else
  6749. {
  6750. if (yych <= 's')
  6751. {
  6752. if (yych <= 'r')
  6753. {
  6754. goto basic_json_parser_30;
  6755. }
  6756. goto basic_json_parser_32;
  6757. }
  6758. else
  6759. {
  6760. if (yych <= 't')
  6761. {
  6762. goto basic_json_parser_30;
  6763. }
  6764. if (yych <= 'u')
  6765. {
  6766. goto basic_json_parser_48;
  6767. }
  6768. goto basic_json_parser_32;
  6769. }
  6770. }
  6771. }
  6772. basic_json_parser_36:
  6773. ++m_cursor;
  6774. if (m_limit <= m_cursor)
  6775. {
  6776. fill_line_buffer(1); // LCOV_EXCL_LINE
  6777. }
  6778. yych = *m_cursor;
  6779. if (yych <= 0x7F)
  6780. {
  6781. goto basic_json_parser_32;
  6782. }
  6783. if (yych <= 0xBF)
  6784. {
  6785. goto basic_json_parser_30;
  6786. }
  6787. goto basic_json_parser_32;
  6788. basic_json_parser_37:
  6789. ++m_cursor;
  6790. if (m_limit <= m_cursor)
  6791. {
  6792. fill_line_buffer(1); // LCOV_EXCL_LINE
  6793. }
  6794. yych = *m_cursor;
  6795. if (yych <= 0x9F)
  6796. {
  6797. goto basic_json_parser_32;
  6798. }
  6799. if (yych <= 0xBF)
  6800. {
  6801. goto basic_json_parser_36;
  6802. }
  6803. goto basic_json_parser_32;
  6804. basic_json_parser_38:
  6805. ++m_cursor;
  6806. if (m_limit <= m_cursor)
  6807. {
  6808. fill_line_buffer(1); // LCOV_EXCL_LINE
  6809. }
  6810. yych = *m_cursor;
  6811. if (yych <= 0x7F)
  6812. {
  6813. goto basic_json_parser_32;
  6814. }
  6815. if (yych <= 0xBF)
  6816. {
  6817. goto basic_json_parser_36;
  6818. }
  6819. goto basic_json_parser_32;
  6820. basic_json_parser_39:
  6821. ++m_cursor;
  6822. if (m_limit <= m_cursor)
  6823. {
  6824. fill_line_buffer(1); // LCOV_EXCL_LINE
  6825. }
  6826. yych = *m_cursor;
  6827. if (yych <= 0x7F)
  6828. {
  6829. goto basic_json_parser_32;
  6830. }
  6831. if (yych <= 0x9F)
  6832. {
  6833. goto basic_json_parser_36;
  6834. }
  6835. goto basic_json_parser_32;
  6836. basic_json_parser_40:
  6837. ++m_cursor;
  6838. if (m_limit <= m_cursor)
  6839. {
  6840. fill_line_buffer(1); // LCOV_EXCL_LINE
  6841. }
  6842. yych = *m_cursor;
  6843. if (yych <= 0x8F)
  6844. {
  6845. goto basic_json_parser_32;
  6846. }
  6847. if (yych <= 0xBF)
  6848. {
  6849. goto basic_json_parser_38;
  6850. }
  6851. goto basic_json_parser_32;
  6852. basic_json_parser_41:
  6853. ++m_cursor;
  6854. if (m_limit <= m_cursor)
  6855. {
  6856. fill_line_buffer(1); // LCOV_EXCL_LINE
  6857. }
  6858. yych = *m_cursor;
  6859. if (yych <= 0x7F)
  6860. {
  6861. goto basic_json_parser_32;
  6862. }
  6863. if (yych <= 0xBF)
  6864. {
  6865. goto basic_json_parser_38;
  6866. }
  6867. goto basic_json_parser_32;
  6868. basic_json_parser_42:
  6869. ++m_cursor;
  6870. if (m_limit <= m_cursor)
  6871. {
  6872. fill_line_buffer(1); // LCOV_EXCL_LINE
  6873. }
  6874. yych = *m_cursor;
  6875. if (yych <= 0x7F)
  6876. {
  6877. goto basic_json_parser_32;
  6878. }
  6879. if (yych <= 0x8F)
  6880. {
  6881. goto basic_json_parser_38;
  6882. }
  6883. goto basic_json_parser_32;
  6884. basic_json_parser_43:
  6885. yych = *++m_cursor;
  6886. if (yych <= '/')
  6887. {
  6888. goto basic_json_parser_32;
  6889. }
  6890. if (yych <= '9')
  6891. {
  6892. goto basic_json_parser_49;
  6893. }
  6894. goto basic_json_parser_32;
  6895. basic_json_parser_44:
  6896. yych = *++m_cursor;
  6897. if (yych <= ',')
  6898. {
  6899. if (yych == '+')
  6900. {
  6901. goto basic_json_parser_51;
  6902. }
  6903. goto basic_json_parser_32;
  6904. }
  6905. else
  6906. {
  6907. if (yych <= '-')
  6908. {
  6909. goto basic_json_parser_51;
  6910. }
  6911. if (yych <= '/')
  6912. {
  6913. goto basic_json_parser_32;
  6914. }
  6915. if (yych <= '9')
  6916. {
  6917. goto basic_json_parser_52;
  6918. }
  6919. goto basic_json_parser_32;
  6920. }
  6921. basic_json_parser_45:
  6922. yych = *++m_cursor;
  6923. if (yych == 'l')
  6924. {
  6925. goto basic_json_parser_54;
  6926. }
  6927. goto basic_json_parser_32;
  6928. basic_json_parser_46:
  6929. yych = *++m_cursor;
  6930. if (yych == 'l')
  6931. {
  6932. goto basic_json_parser_55;
  6933. }
  6934. goto basic_json_parser_32;
  6935. basic_json_parser_47:
  6936. yych = *++m_cursor;
  6937. if (yych == 'u')
  6938. {
  6939. goto basic_json_parser_56;
  6940. }
  6941. goto basic_json_parser_32;
  6942. basic_json_parser_48:
  6943. ++m_cursor;
  6944. if (m_limit <= m_cursor)
  6945. {
  6946. fill_line_buffer(1); // LCOV_EXCL_LINE
  6947. }
  6948. yych = *m_cursor;
  6949. if (yych <= '@')
  6950. {
  6951. if (yych <= '/')
  6952. {
  6953. goto basic_json_parser_32;
  6954. }
  6955. if (yych <= '9')
  6956. {
  6957. goto basic_json_parser_57;
  6958. }
  6959. goto basic_json_parser_32;
  6960. }
  6961. else
  6962. {
  6963. if (yych <= 'F')
  6964. {
  6965. goto basic_json_parser_57;
  6966. }
  6967. if (yych <= '`')
  6968. {
  6969. goto basic_json_parser_32;
  6970. }
  6971. if (yych <= 'f')
  6972. {
  6973. goto basic_json_parser_57;
  6974. }
  6975. goto basic_json_parser_32;
  6976. }
  6977. basic_json_parser_49:
  6978. yyaccept = 1;
  6979. m_marker = ++m_cursor;
  6980. if ((m_limit - m_cursor) < 3)
  6981. {
  6982. fill_line_buffer(3); // LCOV_EXCL_LINE
  6983. }
  6984. yych = *m_cursor;
  6985. if (yych <= 'D')
  6986. {
  6987. if (yych <= '/')
  6988. {
  6989. goto basic_json_parser_14;
  6990. }
  6991. if (yych <= '9')
  6992. {
  6993. goto basic_json_parser_49;
  6994. }
  6995. goto basic_json_parser_14;
  6996. }
  6997. else
  6998. {
  6999. if (yych <= 'E')
  7000. {
  7001. goto basic_json_parser_44;
  7002. }
  7003. if (yych == 'e')
  7004. {
  7005. goto basic_json_parser_44;
  7006. }
  7007. goto basic_json_parser_14;
  7008. }
  7009. basic_json_parser_51:
  7010. yych = *++m_cursor;
  7011. if (yych <= '/')
  7012. {
  7013. goto basic_json_parser_32;
  7014. }
  7015. if (yych >= ':')
  7016. {
  7017. goto basic_json_parser_32;
  7018. }
  7019. basic_json_parser_52:
  7020. ++m_cursor;
  7021. if (m_limit <= m_cursor)
  7022. {
  7023. fill_line_buffer(1); // LCOV_EXCL_LINE
  7024. }
  7025. yych = *m_cursor;
  7026. if (yych <= '/')
  7027. {
  7028. goto basic_json_parser_14;
  7029. }
  7030. if (yych <= '9')
  7031. {
  7032. goto basic_json_parser_52;
  7033. }
  7034. goto basic_json_parser_14;
  7035. basic_json_parser_54:
  7036. yych = *++m_cursor;
  7037. if (yych == 's')
  7038. {
  7039. goto basic_json_parser_58;
  7040. }
  7041. goto basic_json_parser_32;
  7042. basic_json_parser_55:
  7043. yych = *++m_cursor;
  7044. if (yych == 'l')
  7045. {
  7046. goto basic_json_parser_59;
  7047. }
  7048. goto basic_json_parser_32;
  7049. basic_json_parser_56:
  7050. yych = *++m_cursor;
  7051. if (yych == 'e')
  7052. {
  7053. goto basic_json_parser_61;
  7054. }
  7055. goto basic_json_parser_32;
  7056. basic_json_parser_57:
  7057. ++m_cursor;
  7058. if (m_limit <= m_cursor)
  7059. {
  7060. fill_line_buffer(1); // LCOV_EXCL_LINE
  7061. }
  7062. yych = *m_cursor;
  7063. if (yych <= '@')
  7064. {
  7065. if (yych <= '/')
  7066. {
  7067. goto basic_json_parser_32;
  7068. }
  7069. if (yych <= '9')
  7070. {
  7071. goto basic_json_parser_63;
  7072. }
  7073. goto basic_json_parser_32;
  7074. }
  7075. else
  7076. {
  7077. if (yych <= 'F')
  7078. {
  7079. goto basic_json_parser_63;
  7080. }
  7081. if (yych <= '`')
  7082. {
  7083. goto basic_json_parser_32;
  7084. }
  7085. if (yych <= 'f')
  7086. {
  7087. goto basic_json_parser_63;
  7088. }
  7089. goto basic_json_parser_32;
  7090. }
  7091. basic_json_parser_58:
  7092. yych = *++m_cursor;
  7093. if (yych == 'e')
  7094. {
  7095. goto basic_json_parser_64;
  7096. }
  7097. goto basic_json_parser_32;
  7098. basic_json_parser_59:
  7099. ++m_cursor;
  7100. {
  7101. last_token_type = token_type::literal_null;
  7102. break;
  7103. }
  7104. basic_json_parser_61:
  7105. ++m_cursor;
  7106. {
  7107. last_token_type = token_type::literal_true;
  7108. break;
  7109. }
  7110. basic_json_parser_63:
  7111. ++m_cursor;
  7112. if (m_limit <= m_cursor)
  7113. {
  7114. fill_line_buffer(1); // LCOV_EXCL_LINE
  7115. }
  7116. yych = *m_cursor;
  7117. if (yych <= '@')
  7118. {
  7119. if (yych <= '/')
  7120. {
  7121. goto basic_json_parser_32;
  7122. }
  7123. if (yych <= '9')
  7124. {
  7125. goto basic_json_parser_66;
  7126. }
  7127. goto basic_json_parser_32;
  7128. }
  7129. else
  7130. {
  7131. if (yych <= 'F')
  7132. {
  7133. goto basic_json_parser_66;
  7134. }
  7135. if (yych <= '`')
  7136. {
  7137. goto basic_json_parser_32;
  7138. }
  7139. if (yych <= 'f')
  7140. {
  7141. goto basic_json_parser_66;
  7142. }
  7143. goto basic_json_parser_32;
  7144. }
  7145. basic_json_parser_64:
  7146. ++m_cursor;
  7147. {
  7148. last_token_type = token_type::literal_false;
  7149. break;
  7150. }
  7151. basic_json_parser_66:
  7152. ++m_cursor;
  7153. if (m_limit <= m_cursor)
  7154. {
  7155. fill_line_buffer(1); // LCOV_EXCL_LINE
  7156. }
  7157. yych = *m_cursor;
  7158. if (yych <= '@')
  7159. {
  7160. if (yych <= '/')
  7161. {
  7162. goto basic_json_parser_32;
  7163. }
  7164. if (yych <= '9')
  7165. {
  7166. goto basic_json_parser_30;
  7167. }
  7168. goto basic_json_parser_32;
  7169. }
  7170. else
  7171. {
  7172. if (yych <= 'F')
  7173. {
  7174. goto basic_json_parser_30;
  7175. }
  7176. if (yych <= '`')
  7177. {
  7178. goto basic_json_parser_32;
  7179. }
  7180. if (yych <= 'f')
  7181. {
  7182. goto basic_json_parser_30;
  7183. }
  7184. goto basic_json_parser_32;
  7185. }
  7186. }
  7187. }
  7188. return last_token_type;
  7189. }
  7190. /*!
  7191. @brief append data from the stream to the line buffer
  7192. This function is called by the scan() function when the end of the
  7193. buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be
  7194. incremented without leaving the limits of the line buffer. Note re2c
  7195. decides when to call this function.
  7196. If the lexer reads from contiguous storage, there is no trailing null
  7197. byte. Therefore, this function must make sure to add these padding
  7198. null bytes.
  7199. If the lexer reads from an input stream, this function reads the next
  7200. line of the input.
  7201. @pre
  7202. p p p p p p u u u u u x . . . . . .
  7203. ^ ^ ^ ^
  7204. m_content m_start | m_limit
  7205. m_cursor
  7206. @post
  7207. u u u u u x x x x x x x . . . . . .
  7208. ^ ^ ^
  7209. | m_cursor m_limit
  7210. m_start
  7211. m_content
  7212. */
  7213. void fill_line_buffer(size_t n = 0)
  7214. {
  7215. // number of processed characters (p)
  7216. const auto offset_start = m_start - m_content;
  7217. // offset for m_marker wrt. to m_start
  7218. const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start;
  7219. // number of unprocessed characters (u)
  7220. const auto offset_cursor = m_cursor - m_start;
  7221. // no stream is used or end of file is reached
  7222. if (m_stream == nullptr or m_stream->eof())
  7223. {
  7224. // skip this part if we are already using the line buffer
  7225. if (m_start != reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()))
  7226. {
  7227. // copy unprocessed characters to line buffer
  7228. m_line_buffer.clear();
  7229. for (m_cursor = m_start; m_cursor != m_limit; ++m_cursor)
  7230. {
  7231. m_line_buffer.append(1, static_cast<const char>(*m_cursor));
  7232. }
  7233. }
  7234. // append n characters to make sure that there is sufficient
  7235. // space between m_cursor and m_limit
  7236. m_line_buffer.append(1, '\x00');
  7237. m_line_buffer.append(n - 1, '\x01');
  7238. }
  7239. else
  7240. {
  7241. // delete processed characters from line buffer
  7242. m_line_buffer.erase(0, static_cast<size_t>(offset_start));
  7243. // read next line from input stream
  7244. std::string line;
  7245. std::getline(*m_stream, line, '\n');
  7246. // add line with newline symbol to the line buffer
  7247. m_line_buffer += line + "\n";
  7248. }
  7249. // set pointers
  7250. m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.c_str());
  7251. assert(m_content != nullptr);
  7252. m_start = m_content;
  7253. m_marker = m_start + offset_marker;
  7254. m_cursor = m_start + offset_cursor;
  7255. m_limit = m_start + m_line_buffer.size();
  7256. }
  7257. /// return string representation of last read token
  7258. string_t get_token_string() const
  7259. {
  7260. assert(m_start != nullptr);
  7261. return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
  7262. static_cast<size_t>(m_cursor - m_start));
  7263. }
  7264. /*!
  7265. @brief return string value for string tokens
  7266. The function iterates the characters between the opening and closing
  7267. quotes of the string value. The complete string is the range
  7268. [m_start,m_cursor). Consequently, we iterate from m_start+1 to
  7269. m_cursor-1.
  7270. We differentiate two cases:
  7271. 1. Escaped characters. In this case, a new character is constructed
  7272. according to the nature of the escape. Some escapes create new
  7273. characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied
  7274. as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape
  7275. `"\\uxxxx"` need special care. In this case, to_unicode takes care
  7276. of the construction of the values.
  7277. 2. Unescaped characters are copied as is.
  7278. @pre `m_cursor - m_start >= 2`, meaning the length of the last token
  7279. is at least 2 bytes which is trivially true for any string (which
  7280. consists of at least two quotes).
  7281. " c1 c2 c3 ... "
  7282. ^ ^
  7283. m_start m_cursor
  7284. @complexity Linear in the length of the string.\n
  7285. Lemma: The loop body will always terminate.\n
  7286. Proof (by contradiction): Assume the loop body does not terminate. As
  7287. the loop body does not contain another loop, one of the called
  7288. functions must never return. The called functions are `std::strtoul`
  7289. and to_unicode. Neither function can loop forever, so the loop body
  7290. will never loop forever which contradicts the assumption that the loop
  7291. body does not terminate, q.e.d.\n
  7292. Lemma: The loop condition for the for loop is eventually false.\n
  7293. Proof (by contradiction): Assume the loop does not terminate. Due to
  7294. the above lemma, this can only be due to a tautological loop
  7295. condition; that is, the loop condition i < m_cursor - 1 must always be
  7296. true. Let x be the change of i for any loop iteration. Then
  7297. m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This
  7298. can be rephrased to m_cursor - m_start - 2 > x. With the
  7299. precondition, we x <= 0, meaning that the loop condition holds
  7300. indefinitly if i is always decreased. However, observe that the value
  7301. of i is strictly increasing with each iteration, as it is incremented
  7302. by 1 in the iteration expression and never decremented inside the loop
  7303. body. Hence, the loop condition will eventually be false which
  7304. contradicts the assumption that the loop condition is a tautology,
  7305. q.e.d.
  7306. @return string value of current token without opening and closing
  7307. quotes
  7308. @throw std::out_of_range if to_unicode fails
  7309. */
  7310. string_t get_string() const
  7311. {
  7312. assert(m_cursor - m_start >= 2);
  7313. string_t result;
  7314. result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
  7315. // iterate the result between the quotes
  7316. for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
  7317. {
  7318. // process escaped characters
  7319. if (*i == '\\')
  7320. {
  7321. // read next character
  7322. ++i;
  7323. switch (*i)
  7324. {
  7325. // the default escapes
  7326. case 't':
  7327. {
  7328. result += "\t";
  7329. break;
  7330. }
  7331. case 'b':
  7332. {
  7333. result += "\b";
  7334. break;
  7335. }
  7336. case 'f':
  7337. {
  7338. result += "\f";
  7339. break;
  7340. }
  7341. case 'n':
  7342. {
  7343. result += "\n";
  7344. break;
  7345. }
  7346. case 'r':
  7347. {
  7348. result += "\r";
  7349. break;
  7350. }
  7351. case '\\':
  7352. {
  7353. result += "\\";
  7354. break;
  7355. }
  7356. case '/':
  7357. {
  7358. result += "/";
  7359. break;
  7360. }
  7361. case '"':
  7362. {
  7363. result += "\"";
  7364. break;
  7365. }
  7366. // unicode
  7367. case 'u':
  7368. {
  7369. // get code xxxx from uxxxx
  7370. auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
  7371. 4).c_str(), nullptr, 16);
  7372. // check if codepoint is a high surrogate
  7373. if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
  7374. {
  7375. // make sure there is a subsequent unicode
  7376. if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
  7377. {
  7378. throw std::invalid_argument("missing low surrogate");
  7379. }
  7380. // get code yyyy from uxxxx\uyyyy
  7381. auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
  7382. (i + 7), 4).c_str(), nullptr, 16);
  7383. result += to_unicode(codepoint, codepoint2);
  7384. // skip the next 10 characters (xxxx\uyyyy)
  7385. i += 10;
  7386. }
  7387. else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF)
  7388. {
  7389. // we found a lone low surrogate
  7390. throw std::invalid_argument("missing high surrogate");
  7391. }
  7392. else
  7393. {
  7394. // add unicode character(s)
  7395. result += to_unicode(codepoint);
  7396. // skip the next four characters (xxxx)
  7397. i += 4;
  7398. }
  7399. break;
  7400. }
  7401. }
  7402. }
  7403. else
  7404. {
  7405. // all other characters are just copied to the end of the
  7406. // string
  7407. result.append(1, static_cast<typename string_t::value_type>(*i));
  7408. }
  7409. }
  7410. return result;
  7411. }
  7412. /*!
  7413. @brief parse floating point number
  7414. This function (and its overloads) serves to select the most approprate
  7415. standard floating point number parsing function based on the type
  7416. supplied via the first parameter. Set this to @a
  7417. static_cast<number_float_t*>(nullptr).
  7418. @param[in] type the @ref number_float_t in use
  7419. @param[in,out] endptr recieves a pointer to the first character after
  7420. the number
  7421. @return the floating point number
  7422. */
  7423. long double str_to_float_t(long double* /* type */, char** endptr) const
  7424. {
  7425. return std::strtold(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  7426. }
  7427. /*!
  7428. @brief parse floating point number
  7429. This function (and its overloads) serves to select the most approprate
  7430. standard floating point number parsing function based on the type
  7431. supplied via the first parameter. Set this to @a
  7432. static_cast<number_float_t*>(nullptr).
  7433. @param[in] type the @ref number_float_t in use
  7434. @param[in,out] endptr recieves a pointer to the first character after
  7435. the number
  7436. @return the floating point number
  7437. */
  7438. double str_to_float_t(double* /* type */, char** endptr) const
  7439. {
  7440. return std::strtod(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  7441. }
  7442. /*!
  7443. @brief parse floating point number
  7444. This function (and its overloads) serves to select the most approprate
  7445. standard floating point number parsing function based on the type
  7446. supplied via the first parameter. Set this to @a
  7447. static_cast<number_float_t*>(nullptr).
  7448. @param[in] type the @ref number_float_t in use
  7449. @param[in,out] endptr recieves a pointer to the first character after
  7450. the number
  7451. @return the floating point number
  7452. */
  7453. float str_to_float_t(float* /* type */, char** endptr) const
  7454. {
  7455. return std::strtof(reinterpret_cast<typename string_t::const_pointer>(m_start), endptr);
  7456. }
  7457. /*!
  7458. @brief return number value for number tokens
  7459. This function translates the last token into the most appropriate
  7460. number type (either integer, unsigned integer or floating point),
  7461. which is passed back to the caller via the result parameter.
  7462. This function parses the integer component up to the radix point or
  7463. exponent while collecting information about the 'floating point
  7464. representation', which it stores in the result parameter. If there is
  7465. no radix point or exponent, and the number can fit into a @ref
  7466. number_integer_t or @ref number_unsigned_t then it sets the result
  7467. parameter accordingly.
  7468. If the number is a floating point number the number is then parsed
  7469. using @a std:strtod (or @a std:strtof or @a std::strtold).
  7470. @param[out] result @ref basic_json object to receive the number, or
  7471. NAN if the conversion read past the current token. The latter case
  7472. needs to be treated by the caller function.
  7473. */
  7474. void get_number(basic_json& result) const
  7475. {
  7476. assert(m_start != nullptr);
  7477. const lexer::lexer_char_t* curptr = m_start;
  7478. // accumulate the integer conversion result (unsigned for now)
  7479. number_unsigned_t value = 0;
  7480. // maximum absolute value of the relevant integer type
  7481. number_unsigned_t max;
  7482. // temporarily store the type to avoid unecessary bitfield access
  7483. value_t type;
  7484. // look for sign
  7485. if (*curptr == '-')
  7486. {
  7487. type = value_t::number_integer;
  7488. max = static_cast<uint64_t>((std::numeric_limits<number_integer_t>::max)()) + 1;
  7489. curptr++;
  7490. }
  7491. else
  7492. {
  7493. type = value_t::number_unsigned;
  7494. max = static_cast<uint64_t>((std::numeric_limits<number_unsigned_t>::max)());
  7495. }
  7496. // count the significant figures
  7497. for (; curptr < m_cursor; curptr++)
  7498. {
  7499. // quickly skip tests if a digit
  7500. if (*curptr < '0' || *curptr > '9')
  7501. {
  7502. if (*curptr == '.')
  7503. {
  7504. // don't count '.' but change to float
  7505. type = value_t::number_float;
  7506. continue;
  7507. }
  7508. // assume exponent (if not then will fail parse): change to
  7509. // float, stop counting and record exponent details
  7510. type = value_t::number_float;
  7511. break;
  7512. }
  7513. // skip if definitely not an integer
  7514. if (type != value_t::number_float)
  7515. {
  7516. // multiply last value by ten and add the new digit
  7517. auto temp = value * 10 + *curptr - '0';
  7518. // test for overflow
  7519. if (temp < value || temp > max)
  7520. {
  7521. // overflow
  7522. type = value_t::number_float;
  7523. }
  7524. else
  7525. {
  7526. // no overflow - save it
  7527. value = temp;
  7528. }
  7529. }
  7530. }
  7531. // save the value (if not a float)
  7532. if (type == value_t::number_unsigned)
  7533. {
  7534. result.m_value.number_unsigned = value;
  7535. }
  7536. else if (type == value_t::number_integer)
  7537. {
  7538. result.m_value.number_integer = -static_cast<number_integer_t>(value);
  7539. }
  7540. else
  7541. {
  7542. // parse with strtod
  7543. result.m_value.number_float = str_to_float_t(static_cast<number_float_t*>(nullptr), NULL);
  7544. // replace infinity and NAN by null
  7545. if (not std::isfinite(result.m_value.number_float))
  7546. {
  7547. type = value_t::null;
  7548. result.m_value = basic_json::json_value();
  7549. }
  7550. }
  7551. // save the type
  7552. result.m_type = type;
  7553. }
  7554. private:
  7555. /// optional input stream
  7556. std::istream* m_stream = nullptr;
  7557. /// line buffer buffer for m_stream
  7558. string_t m_line_buffer {};
  7559. /// the buffer pointer
  7560. const lexer_char_t* m_content = nullptr;
  7561. /// pointer to the beginning of the current symbol
  7562. const lexer_char_t* m_start = nullptr;
  7563. /// pointer for backtracking information
  7564. const lexer_char_t* m_marker = nullptr;
  7565. /// pointer to the current symbol
  7566. const lexer_char_t* m_cursor = nullptr;
  7567. /// pointer to the end of the buffer
  7568. const lexer_char_t* m_limit = nullptr;
  7569. /// the last token type
  7570. token_type last_token_type = token_type::end_of_input;
  7571. };
  7572. /*!
  7573. @brief syntax analysis
  7574. This class implements a recursive decent parser.
  7575. */
  7576. class parser
  7577. {
  7578. public:
  7579. /// a parser reading from a string literal
  7580. parser(const char* buff, const parser_callback_t cb = nullptr)
  7581. : callback(cb),
  7582. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff))
  7583. {}
  7584. /// a parser reading from an input stream
  7585. parser(std::istream& is, const parser_callback_t cb = nullptr)
  7586. : callback(cb), m_lexer(is)
  7587. {}
  7588. /// a parser reading from an iterator range with contiguous storage
  7589. template<class IteratorType, typename std::enable_if<
  7590. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value
  7591. , int>::type
  7592. = 0>
  7593. parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr)
  7594. : callback(cb),
  7595. m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)),
  7596. static_cast<size_t>(std::distance(first, last)))
  7597. {}
  7598. /// public parser interface
  7599. basic_json parse()
  7600. {
  7601. // read first token
  7602. get_token();
  7603. basic_json result = parse_internal(true);
  7604. result.assert_invariant();
  7605. expect(lexer::token_type::end_of_input);
  7606. // return parser result and replace it with null in case the
  7607. // top-level value was discarded by the callback function
  7608. return result.is_discarded() ? basic_json() : std::move(result);
  7609. }
  7610. private:
  7611. /// the actual parser
  7612. basic_json parse_internal(bool keep)
  7613. {
  7614. auto result = basic_json(value_t::discarded);
  7615. switch (last_token)
  7616. {
  7617. case lexer::token_type::begin_object:
  7618. {
  7619. if (keep and (not callback
  7620. or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0)))
  7621. {
  7622. // explicitly set result to object to cope with {}
  7623. result.m_type = value_t::object;
  7624. result.m_value = value_t::object;
  7625. }
  7626. // read next token
  7627. get_token();
  7628. // closing } -> we are done
  7629. if (last_token == lexer::token_type::end_object)
  7630. {
  7631. get_token();
  7632. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  7633. {
  7634. result = basic_json(value_t::discarded);
  7635. }
  7636. return result;
  7637. }
  7638. // no comma is expected here
  7639. unexpect(lexer::token_type::value_separator);
  7640. // otherwise: parse key-value pairs
  7641. do
  7642. {
  7643. // ugly, but could be fixed with loop reorganization
  7644. if (last_token == lexer::token_type::value_separator)
  7645. {
  7646. get_token();
  7647. }
  7648. // store key
  7649. expect(lexer::token_type::value_string);
  7650. const auto key = m_lexer.get_string();
  7651. bool keep_tag = false;
  7652. if (keep)
  7653. {
  7654. if (callback)
  7655. {
  7656. basic_json k(key);
  7657. keep_tag = callback(depth, parse_event_t::key, k);
  7658. }
  7659. else
  7660. {
  7661. keep_tag = true;
  7662. }
  7663. }
  7664. // parse separator (:)
  7665. get_token();
  7666. expect(lexer::token_type::name_separator);
  7667. // parse and add value
  7668. get_token();
  7669. auto value = parse_internal(keep);
  7670. if (keep and keep_tag and not value.is_discarded())
  7671. {
  7672. result[key] = std::move(value);
  7673. }
  7674. }
  7675. while (last_token == lexer::token_type::value_separator);
  7676. // closing }
  7677. expect(lexer::token_type::end_object);
  7678. get_token();
  7679. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  7680. {
  7681. result = basic_json(value_t::discarded);
  7682. }
  7683. return result;
  7684. }
  7685. case lexer::token_type::begin_array:
  7686. {
  7687. if (keep and (not callback
  7688. or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0)))
  7689. {
  7690. // explicitly set result to object to cope with []
  7691. result.m_type = value_t::array;
  7692. result.m_value = value_t::array;
  7693. }
  7694. // read next token
  7695. get_token();
  7696. // closing ] -> we are done
  7697. if (last_token == lexer::token_type::end_array)
  7698. {
  7699. get_token();
  7700. if (callback and not callback(--depth, parse_event_t::array_end, result))
  7701. {
  7702. result = basic_json(value_t::discarded);
  7703. }
  7704. return result;
  7705. }
  7706. // no comma is expected here
  7707. unexpect(lexer::token_type::value_separator);
  7708. // otherwise: parse values
  7709. do
  7710. {
  7711. // ugly, but could be fixed with loop reorganization
  7712. if (last_token == lexer::token_type::value_separator)
  7713. {
  7714. get_token();
  7715. }
  7716. // parse value
  7717. auto value = parse_internal(keep);
  7718. if (keep and not value.is_discarded())
  7719. {
  7720. result.push_back(std::move(value));
  7721. }
  7722. }
  7723. while (last_token == lexer::token_type::value_separator);
  7724. // closing ]
  7725. expect(lexer::token_type::end_array);
  7726. get_token();
  7727. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  7728. {
  7729. result = basic_json(value_t::discarded);
  7730. }
  7731. return result;
  7732. }
  7733. case lexer::token_type::literal_null:
  7734. {
  7735. get_token();
  7736. result.m_type = value_t::null;
  7737. break;
  7738. }
  7739. case lexer::token_type::value_string:
  7740. {
  7741. const auto s = m_lexer.get_string();
  7742. get_token();
  7743. result = basic_json(s);
  7744. break;
  7745. }
  7746. case lexer::token_type::literal_true:
  7747. {
  7748. get_token();
  7749. result.m_type = value_t::boolean;
  7750. result.m_value = true;
  7751. break;
  7752. }
  7753. case lexer::token_type::literal_false:
  7754. {
  7755. get_token();
  7756. result.m_type = value_t::boolean;
  7757. result.m_value = false;
  7758. break;
  7759. }
  7760. case lexer::token_type::value_number:
  7761. {
  7762. m_lexer.get_number(result);
  7763. get_token();
  7764. break;
  7765. }
  7766. default:
  7767. {
  7768. // the last token was unexpected
  7769. unexpect(last_token);
  7770. }
  7771. }
  7772. if (keep and callback and not callback(depth, parse_event_t::value, result))
  7773. {
  7774. result = basic_json(value_t::discarded);
  7775. }
  7776. return result;
  7777. }
  7778. /// get next token from lexer
  7779. typename lexer::token_type get_token()
  7780. {
  7781. last_token = m_lexer.scan();
  7782. return last_token;
  7783. }
  7784. void expect(typename lexer::token_type t) const
  7785. {
  7786. if (t != last_token)
  7787. {
  7788. std::string error_msg = "parse error - unexpected ";
  7789. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  7790. "'") :
  7791. lexer::token_type_name(last_token));
  7792. error_msg += "; expected " + lexer::token_type_name(t);
  7793. throw std::invalid_argument(error_msg);
  7794. }
  7795. }
  7796. void unexpect(typename lexer::token_type t) const
  7797. {
  7798. if (t == last_token)
  7799. {
  7800. std::string error_msg = "parse error - unexpected ";
  7801. error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
  7802. "'") :
  7803. lexer::token_type_name(last_token));
  7804. throw std::invalid_argument(error_msg);
  7805. }
  7806. }
  7807. private:
  7808. /// current level of recursion
  7809. int depth = 0;
  7810. /// callback function
  7811. const parser_callback_t callback = nullptr;
  7812. /// the type of the last read token
  7813. typename lexer::token_type last_token = lexer::token_type::uninitialized;
  7814. /// the lexer
  7815. lexer m_lexer;
  7816. };
  7817. public:
  7818. /*!
  7819. @brief JSON Pointer
  7820. A JSON pointer defines a string syntax for identifying a specific value
  7821. within a JSON document. It can be used with functions `at` and
  7822. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  7823. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  7824. @since version 2.0.0
  7825. */
  7826. class json_pointer
  7827. {
  7828. /// allow basic_json to access private members
  7829. friend class basic_json;
  7830. public:
  7831. /*!
  7832. @brief create JSON pointer
  7833. Create a JSON pointer according to the syntax described in
  7834. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  7835. @param[in] s string representing the JSON pointer; if omitted, the
  7836. empty string is assumed which references the whole JSON
  7837. value
  7838. @throw std::domain_error if reference token is nonempty and does not
  7839. begin with a slash (`/`); example: `"JSON pointer must be empty or
  7840. begin with /"`
  7841. @throw std::domain_error if a tilde (`~`) is not followed by `0`
  7842. (representing `~`) or `1` (representing `/`); example: `"escape error:
  7843. ~ must be followed with 0 or 1"`
  7844. @liveexample{The example shows the construction several valid JSON
  7845. pointers as well as the exceptional behavior.,json_pointer}
  7846. @since version 2.0.0
  7847. */
  7848. explicit json_pointer(const std::string& s = "")
  7849. : reference_tokens(split(s))
  7850. {}
  7851. /*!
  7852. @brief return a string representation of the JSON pointer
  7853. @invariant For each JSON pointer `ptr`, it holds:
  7854. @code {.cpp}
  7855. ptr == json_pointer(ptr.to_string());
  7856. @endcode
  7857. @return a string representation of the JSON pointer
  7858. @liveexample{The example shows the result of `to_string`.,
  7859. json_pointer__to_string}
  7860. @since version 2.0.0
  7861. */
  7862. std::string to_string() const noexcept
  7863. {
  7864. return std::accumulate(reference_tokens.begin(),
  7865. reference_tokens.end(), std::string{},
  7866. [](const std::string & a, const std::string & b)
  7867. {
  7868. return a + "/" + escape(b);
  7869. });
  7870. }
  7871. /// @copydoc to_string()
  7872. operator std::string() const
  7873. {
  7874. return to_string();
  7875. }
  7876. private:
  7877. /// remove and return last reference pointer
  7878. std::string pop_back()
  7879. {
  7880. if (is_root())
  7881. {
  7882. throw std::domain_error("JSON pointer has no parent");
  7883. }
  7884. auto last = reference_tokens.back();
  7885. reference_tokens.pop_back();
  7886. return last;
  7887. }
  7888. /// return whether pointer points to the root document
  7889. bool is_root() const
  7890. {
  7891. return reference_tokens.empty();
  7892. }
  7893. json_pointer top() const
  7894. {
  7895. if (is_root())
  7896. {
  7897. throw std::domain_error("JSON pointer has no parent");
  7898. }
  7899. json_pointer result = *this;
  7900. result.reference_tokens = {reference_tokens[0]};
  7901. return result;
  7902. }
  7903. /*!
  7904. @brief create and return a reference to the pointed to value
  7905. @complexity Linear in the number of reference tokens.
  7906. */
  7907. reference get_and_create(reference j) const
  7908. {
  7909. pointer result = &j;
  7910. // in case no reference tokens exist, return a reference to the
  7911. // JSON value j which will be overwritten by a primitive value
  7912. for (const auto& reference_token : reference_tokens)
  7913. {
  7914. switch (result->m_type)
  7915. {
  7916. case value_t::null:
  7917. {
  7918. if (reference_token == "0")
  7919. {
  7920. // start a new array if reference token is 0
  7921. result = &result->operator[](0);
  7922. }
  7923. else
  7924. {
  7925. // start a new object otherwise
  7926. result = &result->operator[](reference_token);
  7927. }
  7928. break;
  7929. }
  7930. case value_t::object:
  7931. {
  7932. // create an entry in the object
  7933. result = &result->operator[](reference_token);
  7934. break;
  7935. }
  7936. case value_t::array:
  7937. {
  7938. // create an entry in the array
  7939. result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
  7940. break;
  7941. }
  7942. /*
  7943. The following code is only reached if there exists a
  7944. reference token _and_ the current value is primitive. In
  7945. this case, we have an error situation, because primitive
  7946. values may only occur as single value; that is, with an
  7947. empty list of reference tokens.
  7948. */
  7949. default:
  7950. {
  7951. throw std::domain_error("invalid value to unflatten");
  7952. }
  7953. }
  7954. }
  7955. return *result;
  7956. }
  7957. /*!
  7958. @brief return a reference to the pointed to value
  7959. @note This version does not throw if a value is not present, but tries
  7960. to create nested values instead. For instance, calling this function
  7961. with pointer `"/this/that"` on a null value is equivalent to calling
  7962. `operator[]("this").operator[]("that")` on that value, effectively
  7963. changing the null value to an object.
  7964. @param[in] ptr a JSON value
  7965. @return reference to the JSON value pointed to by the JSON pointer
  7966. @complexity Linear in the length of the JSON pointer.
  7967. @throw std::out_of_range if the JSON pointer can not be resolved
  7968. @throw std::domain_error if an array index begins with '0'
  7969. @throw std::invalid_argument if an array index was not a number
  7970. */
  7971. reference get_unchecked(pointer ptr) const
  7972. {
  7973. for (const auto& reference_token : reference_tokens)
  7974. {
  7975. // convert null values to arrays or objects before continuing
  7976. if (ptr->m_type == value_t::null)
  7977. {
  7978. // check if reference token is a number
  7979. const bool nums = std::all_of(reference_token.begin(),
  7980. reference_token.end(),
  7981. [](const char x)
  7982. {
  7983. return std::isdigit(x);
  7984. });
  7985. // change value to array for numbers or "-" or to object
  7986. // otherwise
  7987. if (nums or reference_token == "-")
  7988. {
  7989. *ptr = value_t::array;
  7990. }
  7991. else
  7992. {
  7993. *ptr = value_t::object;
  7994. }
  7995. }
  7996. switch (ptr->m_type)
  7997. {
  7998. case value_t::object:
  7999. {
  8000. // use unchecked object access
  8001. ptr = &ptr->operator[](reference_token);
  8002. break;
  8003. }
  8004. case value_t::array:
  8005. {
  8006. // error condition (cf. RFC 6901, Sect. 4)
  8007. if (reference_token.size() > 1 and reference_token[0] == '0')
  8008. {
  8009. throw std::domain_error("array index must not begin with '0'");
  8010. }
  8011. if (reference_token == "-")
  8012. {
  8013. // explicityly treat "-" as index beyond the end
  8014. ptr = &ptr->operator[](ptr->m_value.array->size());
  8015. }
  8016. else
  8017. {
  8018. // convert array index to number; unchecked access
  8019. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  8020. }
  8021. break;
  8022. }
  8023. default:
  8024. {
  8025. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  8026. }
  8027. }
  8028. }
  8029. return *ptr;
  8030. }
  8031. reference get_checked(pointer ptr) const
  8032. {
  8033. for (const auto& reference_token : reference_tokens)
  8034. {
  8035. switch (ptr->m_type)
  8036. {
  8037. case value_t::object:
  8038. {
  8039. // note: at performs range check
  8040. ptr = &ptr->at(reference_token);
  8041. break;
  8042. }
  8043. case value_t::array:
  8044. {
  8045. if (reference_token == "-")
  8046. {
  8047. // "-" always fails the range check
  8048. throw std::out_of_range("array index '-' (" +
  8049. std::to_string(ptr->m_value.array->size()) +
  8050. ") is out of range");
  8051. }
  8052. // error condition (cf. RFC 6901, Sect. 4)
  8053. if (reference_token.size() > 1 and reference_token[0] == '0')
  8054. {
  8055. throw std::domain_error("array index must not begin with '0'");
  8056. }
  8057. // note: at performs range check
  8058. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  8059. break;
  8060. }
  8061. default:
  8062. {
  8063. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  8064. }
  8065. }
  8066. }
  8067. return *ptr;
  8068. }
  8069. /*!
  8070. @brief return a const reference to the pointed to value
  8071. @param[in] ptr a JSON value
  8072. @return const reference to the JSON value pointed to by the JSON
  8073. pointer
  8074. */
  8075. const_reference get_unchecked(const_pointer ptr) const
  8076. {
  8077. for (const auto& reference_token : reference_tokens)
  8078. {
  8079. switch (ptr->m_type)
  8080. {
  8081. case value_t::object:
  8082. {
  8083. // use unchecked object access
  8084. ptr = &ptr->operator[](reference_token);
  8085. break;
  8086. }
  8087. case value_t::array:
  8088. {
  8089. if (reference_token == "-")
  8090. {
  8091. // "-" cannot be used for const access
  8092. throw std::out_of_range("array index '-' (" +
  8093. std::to_string(ptr->m_value.array->size()) +
  8094. ") is out of range");
  8095. }
  8096. // error condition (cf. RFC 6901, Sect. 4)
  8097. if (reference_token.size() > 1 and reference_token[0] == '0')
  8098. {
  8099. throw std::domain_error("array index must not begin with '0'");
  8100. }
  8101. // use unchecked array access
  8102. ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
  8103. break;
  8104. }
  8105. default:
  8106. {
  8107. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  8108. }
  8109. }
  8110. }
  8111. return *ptr;
  8112. }
  8113. const_reference get_checked(const_pointer ptr) const
  8114. {
  8115. for (const auto& reference_token : reference_tokens)
  8116. {
  8117. switch (ptr->m_type)
  8118. {
  8119. case value_t::object:
  8120. {
  8121. // note: at performs range check
  8122. ptr = &ptr->at(reference_token);
  8123. break;
  8124. }
  8125. case value_t::array:
  8126. {
  8127. if (reference_token == "-")
  8128. {
  8129. // "-" always fails the range check
  8130. throw std::out_of_range("array index '-' (" +
  8131. std::to_string(ptr->m_value.array->size()) +
  8132. ") is out of range");
  8133. }
  8134. // error condition (cf. RFC 6901, Sect. 4)
  8135. if (reference_token.size() > 1 and reference_token[0] == '0')
  8136. {
  8137. throw std::domain_error("array index must not begin with '0'");
  8138. }
  8139. // note: at performs range check
  8140. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  8141. break;
  8142. }
  8143. default:
  8144. {
  8145. throw std::out_of_range("unresolved reference token '" + reference_token + "'");
  8146. }
  8147. }
  8148. }
  8149. return *ptr;
  8150. }
  8151. /// split the string input to reference tokens
  8152. static std::vector<std::string> split(const std::string& reference_string)
  8153. {
  8154. std::vector<std::string> result;
  8155. // special case: empty reference string -> no reference tokens
  8156. if (reference_string.empty())
  8157. {
  8158. return result;
  8159. }
  8160. // check if nonempty reference string begins with slash
  8161. if (reference_string[0] != '/')
  8162. {
  8163. throw std::domain_error("JSON pointer must be empty or begin with '/'");
  8164. }
  8165. // extract the reference tokens:
  8166. // - slash: position of the last read slash (or end of string)
  8167. // - start: position after the previous slash
  8168. for (
  8169. // search for the first slash after the first character
  8170. size_t slash = reference_string.find_first_of("/", 1),
  8171. // set the beginning of the first reference token
  8172. start = 1;
  8173. // we can stop if start == string::npos+1 = 0
  8174. start != 0;
  8175. // set the beginning of the next reference token
  8176. // (will eventually be 0 if slash == std::string::npos)
  8177. start = slash + 1,
  8178. // find next slash
  8179. slash = reference_string.find_first_of("/", start))
  8180. {
  8181. // use the text between the beginning of the reference token
  8182. // (start) and the last slash (slash).
  8183. auto reference_token = reference_string.substr(start, slash - start);
  8184. // check reference tokens are properly escaped
  8185. for (size_t pos = reference_token.find_first_of("~");
  8186. pos != std::string::npos;
  8187. pos = reference_token.find_first_of("~", pos + 1))
  8188. {
  8189. assert(reference_token[pos] == '~');
  8190. // ~ must be followed by 0 or 1
  8191. if (pos == reference_token.size() - 1 or
  8192. (reference_token[pos + 1] != '0' and
  8193. reference_token[pos + 1] != '1'))
  8194. {
  8195. throw std::domain_error("escape error: '~' must be followed with '0' or '1'");
  8196. }
  8197. }
  8198. // finally, store the reference token
  8199. unescape(reference_token);
  8200. result.push_back(reference_token);
  8201. }
  8202. return result;
  8203. }
  8204. private:
  8205. /*!
  8206. @brief replace all occurrences of a substring by another string
  8207. @param[in,out] s the string to manipulate
  8208. @param[in] f the substring to replace with @a t
  8209. @param[in] t the string to replace @a f
  8210. @return The string @a s where all occurrences of @a f are replaced
  8211. with @a t.
  8212. @pre The search string @a f must not be empty.
  8213. @since version 2.0.0
  8214. */
  8215. static void replace_substring(std::string& s,
  8216. const std::string& f,
  8217. const std::string& t)
  8218. {
  8219. assert(not f.empty());
  8220. for (
  8221. size_t pos = s.find(f); // find first occurrence of f
  8222. pos != std::string::npos; // make sure f was found
  8223. s.replace(pos, f.size(), t), // replace with t
  8224. pos = s.find(f, pos + t.size()) // find next occurrence of f
  8225. );
  8226. }
  8227. /// escape tilde and slash
  8228. static std::string escape(std::string s)
  8229. {
  8230. // escape "~"" to "~0" and "/" to "~1"
  8231. replace_substring(s, "~", "~0");
  8232. replace_substring(s, "/", "~1");
  8233. return s;
  8234. }
  8235. /// unescape tilde and slash
  8236. static void unescape(std::string& s)
  8237. {
  8238. // first transform any occurrence of the sequence '~1' to '/'
  8239. replace_substring(s, "~1", "/");
  8240. // then transform any occurrence of the sequence '~0' to '~'
  8241. replace_substring(s, "~0", "~");
  8242. }
  8243. /*!
  8244. @param[in] reference_string the reference string to the current value
  8245. @param[in] value the value to consider
  8246. @param[in,out] result the result object to insert values to
  8247. @note Empty objects or arrays are flattened to `null`.
  8248. */
  8249. static void flatten(const std::string& reference_string,
  8250. const basic_json& value,
  8251. basic_json& result)
  8252. {
  8253. switch (value.m_type)
  8254. {
  8255. case value_t::array:
  8256. {
  8257. if (value.m_value.array->empty())
  8258. {
  8259. // flatten empty array as null
  8260. result[reference_string] = nullptr;
  8261. }
  8262. else
  8263. {
  8264. // iterate array and use index as reference string
  8265. for (size_t i = 0; i < value.m_value.array->size(); ++i)
  8266. {
  8267. flatten(reference_string + "/" + std::to_string(i),
  8268. value.m_value.array->operator[](i), result);
  8269. }
  8270. }
  8271. break;
  8272. }
  8273. case value_t::object:
  8274. {
  8275. if (value.m_value.object->empty())
  8276. {
  8277. // flatten empty object as null
  8278. result[reference_string] = nullptr;
  8279. }
  8280. else
  8281. {
  8282. // iterate object and use keys as reference string
  8283. for (const auto& element : *value.m_value.object)
  8284. {
  8285. flatten(reference_string + "/" + escape(element.first),
  8286. element.second, result);
  8287. }
  8288. }
  8289. break;
  8290. }
  8291. default:
  8292. {
  8293. // add primitive value with its reference string
  8294. result[reference_string] = value;
  8295. break;
  8296. }
  8297. }
  8298. }
  8299. /*!
  8300. @param[in] value flattened JSON
  8301. @return unflattened JSON
  8302. */
  8303. static basic_json unflatten(const basic_json& value)
  8304. {
  8305. if (not value.is_object())
  8306. {
  8307. throw std::domain_error("only objects can be unflattened");
  8308. }
  8309. basic_json result;
  8310. // iterate the JSON object values
  8311. for (const auto& element : *value.m_value.object)
  8312. {
  8313. if (not element.second.is_primitive())
  8314. {
  8315. throw std::domain_error("values in object must be primitive");
  8316. }
  8317. // assign value to reference pointed to by JSON pointer; Note
  8318. // that if the JSON pointer is "" (i.e., points to the whole
  8319. // value), function get_and_create returns a reference to
  8320. // result itself. An assignment will then create a primitive
  8321. // value.
  8322. json_pointer(element.first).get_and_create(result) = element.second;
  8323. }
  8324. return result;
  8325. }
  8326. private:
  8327. /// the reference tokens
  8328. std::vector<std::string> reference_tokens {};
  8329. };
  8330. //////////////////////////
  8331. // JSON Pointer support //
  8332. //////////////////////////
  8333. /// @name JSON Pointer functions
  8334. /// @{
  8335. /*!
  8336. @brief access specified element via JSON Pointer
  8337. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  8338. No bound checking is performed. Similar to @ref operator[](const typename
  8339. object_t::key_type&), `null` values are created in arrays and objects if
  8340. necessary.
  8341. In particular:
  8342. - If the JSON pointer points to an object key that does not exist, it
  8343. is created an filled with a `null` value before a reference to it
  8344. is returned.
  8345. - If the JSON pointer points to an array index that does not exist, it
  8346. is created an filled with a `null` value before a reference to it
  8347. is returned. All indices between the current maximum and the given
  8348. index are also filled with `null`.
  8349. - The special value `-` is treated as a synonym for the index past the
  8350. end.
  8351. @param[in] ptr a JSON pointer
  8352. @return reference to the element pointed to by @a ptr
  8353. @complexity Constant.
  8354. @throw std::out_of_range if the JSON pointer can not be resolved
  8355. @throw std::domain_error if an array index begins with '0'
  8356. @throw std::invalid_argument if an array index was not a number
  8357. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  8358. @since version 2.0.0
  8359. */
  8360. reference operator[](const json_pointer& ptr)
  8361. {
  8362. return ptr.get_unchecked(this);
  8363. }
  8364. /*!
  8365. @brief access specified element via JSON Pointer
  8366. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  8367. No bound checking is performed. The function does not change the JSON
  8368. value; no `null` values are created. In particular, the the special value
  8369. `-` yields an exception.
  8370. @param[in] ptr JSON pointer to the desired element
  8371. @return const reference to the element pointed to by @a ptr
  8372. @complexity Constant.
  8373. @throw std::out_of_range if the JSON pointer can not be resolved
  8374. @throw std::domain_error if an array index begins with '0'
  8375. @throw std::invalid_argument if an array index was not a number
  8376. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  8377. @since version 2.0.0
  8378. */
  8379. const_reference operator[](const json_pointer& ptr) const
  8380. {
  8381. return ptr.get_unchecked(this);
  8382. }
  8383. /*!
  8384. @brief access specified element via JSON Pointer
  8385. Returns a reference to the element at with specified JSON pointer @a ptr,
  8386. with bounds checking.
  8387. @param[in] ptr JSON pointer to the desired element
  8388. @return reference to the element pointed to by @a ptr
  8389. @complexity Constant.
  8390. @throw std::out_of_range if the JSON pointer can not be resolved
  8391. @throw std::domain_error if an array index begins with '0'
  8392. @throw std::invalid_argument if an array index was not a number
  8393. @liveexample{The behavior is shown in the example.,at_json_pointer}
  8394. @since version 2.0.0
  8395. */
  8396. reference at(const json_pointer& ptr)
  8397. {
  8398. return ptr.get_checked(this);
  8399. }
  8400. /*!
  8401. @brief access specified element via JSON Pointer
  8402. Returns a const reference to the element at with specified JSON pointer @a
  8403. ptr, with bounds checking.
  8404. @param[in] ptr JSON pointer to the desired element
  8405. @return reference to the element pointed to by @a ptr
  8406. @complexity Constant.
  8407. @throw std::out_of_range if the JSON pointer can not be resolved
  8408. @throw std::domain_error if an array index begins with '0'
  8409. @throw std::invalid_argument if an array index was not a number
  8410. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  8411. @since version 2.0.0
  8412. */
  8413. const_reference at(const json_pointer& ptr) const
  8414. {
  8415. return ptr.get_checked(this);
  8416. }
  8417. /*!
  8418. @brief return flattened JSON value
  8419. The function creates a JSON object whose keys are JSON pointers (see [RFC
  8420. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  8421. primitive. The original JSON value can be restored using the @ref
  8422. unflatten() function.
  8423. @return an object that maps JSON pointers to primitve values
  8424. @note Empty objects and arrays are flattened to `null` and will not be
  8425. reconstructed correctly by the @ref unflatten() function.
  8426. @complexity Linear in the size the JSON value.
  8427. @liveexample{The following code shows how a JSON object is flattened to an
  8428. object whose keys consist of JSON pointers.,flatten}
  8429. @sa @ref unflatten() for the reverse function
  8430. @since version 2.0.0
  8431. */
  8432. basic_json flatten() const
  8433. {
  8434. basic_json result(value_t::object);
  8435. json_pointer::flatten("", *this, result);
  8436. return result;
  8437. }
  8438. /*!
  8439. @brief unflatten a previously flattened JSON value
  8440. The function restores the arbitrary nesting of a JSON value that has been
  8441. flattened before using the @ref flatten() function. The JSON value must
  8442. meet certain constraints:
  8443. 1. The value must be an object.
  8444. 2. The keys must be JSON pointers (see
  8445. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  8446. 3. The mapped values must be primitive JSON types.
  8447. @return the original JSON from a flattened version
  8448. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  8449. values and can not unflattened to their original type. Apart from
  8450. this example, for a JSON value `j`, the following is always true:
  8451. `j == j.flatten().unflatten()`.
  8452. @complexity Linear in the size the JSON value.
  8453. @liveexample{The following code shows how a flattened JSON object is
  8454. unflattened into the original nested JSON object.,unflatten}
  8455. @sa @ref flatten() for the reverse function
  8456. @since version 2.0.0
  8457. */
  8458. basic_json unflatten() const
  8459. {
  8460. return json_pointer::unflatten(*this);
  8461. }
  8462. /// @}
  8463. //////////////////////////
  8464. // JSON Patch functions //
  8465. //////////////////////////
  8466. /// @name JSON Patch functions
  8467. /// @{
  8468. /*!
  8469. @brief applies a JSON patch
  8470. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  8471. expressing a sequence of operations to apply to a JSON) document. With
  8472. this funcion, a JSON Patch is applied to the current JSON value by
  8473. executing all operations from the patch.
  8474. @param[in] json_patch JSON patch document
  8475. @return patched document
  8476. @note The application of a patch is atomic: Either all operations succeed
  8477. and the patched document is returned or an exception is thrown. In
  8478. any case, the original value is not changed: the patch is applied
  8479. to a copy of the value.
  8480. @throw std::out_of_range if a JSON pointer inside the patch could not
  8481. be resolved successfully in the current JSON value; example: `"key baz
  8482. not found"`
  8483. @throw invalid_argument if the JSON patch is malformed (e.g., mandatory
  8484. attributes are missing); example: `"operation add must have member path"`
  8485. @complexity Linear in the size of the JSON value and the length of the
  8486. JSON patch. As usually only a fraction of the JSON value is affected by
  8487. the patch, the complexity can usually be neglected.
  8488. @liveexample{The following code shows how a JSON patch is applied to a
  8489. value.,patch}
  8490. @sa @ref diff -- create a JSON patch by comparing two JSON values
  8491. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  8492. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  8493. @since version 2.0.0
  8494. */
  8495. basic_json patch(const basic_json& json_patch) const
  8496. {
  8497. // make a working copy to apply the patch to
  8498. basic_json result = *this;
  8499. // the valid JSON Patch operations
  8500. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  8501. const auto get_op = [](const std::string op)
  8502. {
  8503. if (op == "add")
  8504. {
  8505. return patch_operations::add;
  8506. }
  8507. if (op == "remove")
  8508. {
  8509. return patch_operations::remove;
  8510. }
  8511. if (op == "replace")
  8512. {
  8513. return patch_operations::replace;
  8514. }
  8515. if (op == "move")
  8516. {
  8517. return patch_operations::move;
  8518. }
  8519. if (op == "copy")
  8520. {
  8521. return patch_operations::copy;
  8522. }
  8523. if (op == "test")
  8524. {
  8525. return patch_operations::test;
  8526. }
  8527. return patch_operations::invalid;
  8528. };
  8529. // wrapper for "add" operation; add value at ptr
  8530. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  8531. {
  8532. // adding to the root of the target document means replacing it
  8533. if (ptr.is_root())
  8534. {
  8535. result = val;
  8536. }
  8537. else
  8538. {
  8539. // make sure the top element of the pointer exists
  8540. json_pointer top_pointer = ptr.top();
  8541. if (top_pointer != ptr)
  8542. {
  8543. result.at(top_pointer);
  8544. }
  8545. // get reference to parent of JSON pointer ptr
  8546. const auto last_path = ptr.pop_back();
  8547. basic_json& parent = result[ptr];
  8548. switch (parent.m_type)
  8549. {
  8550. case value_t::null:
  8551. case value_t::object:
  8552. {
  8553. // use operator[] to add value
  8554. parent[last_path] = val;
  8555. break;
  8556. }
  8557. case value_t::array:
  8558. {
  8559. if (last_path == "-")
  8560. {
  8561. // special case: append to back
  8562. parent.push_back(val);
  8563. }
  8564. else
  8565. {
  8566. const auto idx = std::stoi(last_path);
  8567. if (static_cast<size_type>(idx) > parent.size())
  8568. {
  8569. // avoid undefined behavior
  8570. throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
  8571. }
  8572. else
  8573. {
  8574. // default case: insert add offset
  8575. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  8576. }
  8577. }
  8578. break;
  8579. }
  8580. default:
  8581. {
  8582. // if there exists a parent it cannot be primitive
  8583. assert(false); // LCOV_EXCL_LINE
  8584. }
  8585. }
  8586. }
  8587. };
  8588. // wrapper for "remove" operation; remove value at ptr
  8589. const auto operation_remove = [&result](json_pointer & ptr)
  8590. {
  8591. // get reference to parent of JSON pointer ptr
  8592. const auto last_path = ptr.pop_back();
  8593. basic_json& parent = result.at(ptr);
  8594. // remove child
  8595. if (parent.is_object())
  8596. {
  8597. // perform range check
  8598. auto it = parent.find(last_path);
  8599. if (it != parent.end())
  8600. {
  8601. parent.erase(it);
  8602. }
  8603. else
  8604. {
  8605. throw std::out_of_range("key '" + last_path + "' not found");
  8606. }
  8607. }
  8608. else if (parent.is_array())
  8609. {
  8610. // note erase performs range check
  8611. parent.erase(static_cast<size_type>(std::stoi(last_path)));
  8612. }
  8613. };
  8614. // type check
  8615. if (not json_patch.is_array())
  8616. {
  8617. // a JSON patch must be an array of objects
  8618. throw std::invalid_argument("JSON patch must be an array of objects");
  8619. }
  8620. // iterate and apply th eoperations
  8621. for (const auto& val : json_patch)
  8622. {
  8623. // wrapper to get a value for an operation
  8624. const auto get_value = [&val](const std::string & op,
  8625. const std::string & member,
  8626. bool string_type) -> basic_json&
  8627. {
  8628. // find value
  8629. auto it = val.m_value.object->find(member);
  8630. // context-sensitive error message
  8631. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  8632. // check if desired value is present
  8633. if (it == val.m_value.object->end())
  8634. {
  8635. throw std::invalid_argument(error_msg + " must have member '" + member + "'");
  8636. }
  8637. // check if result is of type string
  8638. if (string_type and not it->second.is_string())
  8639. {
  8640. throw std::invalid_argument(error_msg + " must have string member '" + member + "'");
  8641. }
  8642. // no error: return value
  8643. return it->second;
  8644. };
  8645. // type check
  8646. if (not val.is_object())
  8647. {
  8648. throw std::invalid_argument("JSON patch must be an array of objects");
  8649. }
  8650. // collect mandatory members
  8651. const std::string op = get_value("op", "op", true);
  8652. const std::string path = get_value(op, "path", true);
  8653. json_pointer ptr(path);
  8654. switch (get_op(op))
  8655. {
  8656. case patch_operations::add:
  8657. {
  8658. operation_add(ptr, get_value("add", "value", false));
  8659. break;
  8660. }
  8661. case patch_operations::remove:
  8662. {
  8663. operation_remove(ptr);
  8664. break;
  8665. }
  8666. case patch_operations::replace:
  8667. {
  8668. // the "path" location must exist - use at()
  8669. result.at(ptr) = get_value("replace", "value", false);
  8670. break;
  8671. }
  8672. case patch_operations::move:
  8673. {
  8674. const std::string from_path = get_value("move", "from", true);
  8675. json_pointer from_ptr(from_path);
  8676. // the "from" location must exist - use at()
  8677. basic_json v = result.at(from_ptr);
  8678. // The move operation is functionally identical to a
  8679. // "remove" operation on the "from" location, followed
  8680. // immediately by an "add" operation at the target
  8681. // location with the value that was just removed.
  8682. operation_remove(from_ptr);
  8683. operation_add(ptr, v);
  8684. break;
  8685. }
  8686. case patch_operations::copy:
  8687. {
  8688. const std::string from_path = get_value("copy", "from", true);;
  8689. const json_pointer from_ptr(from_path);
  8690. // the "from" location must exist - use at()
  8691. result[ptr] = result.at(from_ptr);
  8692. break;
  8693. }
  8694. case patch_operations::test:
  8695. {
  8696. bool success = false;
  8697. try
  8698. {
  8699. // check if "value" matches the one at "path"
  8700. // the "path" location must exist - use at()
  8701. success = (result.at(ptr) == get_value("test", "value", false));
  8702. }
  8703. catch (std::out_of_range&)
  8704. {
  8705. // ignore out of range errors: success remains false
  8706. }
  8707. // throw an exception if test fails
  8708. if (not success)
  8709. {
  8710. throw std::domain_error("unsuccessful: " + val.dump());
  8711. }
  8712. break;
  8713. }
  8714. case patch_operations::invalid:
  8715. {
  8716. // op must be "add", "remove", "replace", "move", "copy", or
  8717. // "test"
  8718. throw std::invalid_argument("operation value '" + op + "' is invalid");
  8719. }
  8720. }
  8721. }
  8722. return result;
  8723. }
  8724. /*!
  8725. @brief creates a diff as a JSON patch
  8726. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  8727. be changed into the value @a target by calling @ref patch function.
  8728. @invariant For two JSON values @a source and @a target, the following code
  8729. yields always `true`:
  8730. @code {.cpp}
  8731. source.patch(diff(source, target)) == target;
  8732. @endcode
  8733. @note Currently, only `remove`, `add`, and `replace` operations are
  8734. generated.
  8735. @param[in] source JSON value to copare from
  8736. @param[in] target JSON value to copare against
  8737. @param[in] path helper value to create JSON pointers
  8738. @return a JSON patch to convert the @a source to @a target
  8739. @complexity Linear in the lengths of @a source and @a target.
  8740. @liveexample{The following code shows how a JSON patch is created as a
  8741. diff for two JSON values.,diff}
  8742. @sa @ref patch -- apply a JSON patch
  8743. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  8744. @since version 2.0.0
  8745. */
  8746. static basic_json diff(const basic_json& source,
  8747. const basic_json& target,
  8748. const std::string& path = "")
  8749. {
  8750. // the patch
  8751. basic_json result(value_t::array);
  8752. // if the values are the same, return empty patch
  8753. if (source == target)
  8754. {
  8755. return result;
  8756. }
  8757. if (source.type() != target.type())
  8758. {
  8759. // different types: replace value
  8760. result.push_back(
  8761. {
  8762. {"op", "replace"},
  8763. {"path", path},
  8764. {"value", target}
  8765. });
  8766. }
  8767. else
  8768. {
  8769. switch (source.type())
  8770. {
  8771. case value_t::array:
  8772. {
  8773. // first pass: traverse common elements
  8774. size_t i = 0;
  8775. while (i < source.size() and i < target.size())
  8776. {
  8777. // recursive call to compare array values at index i
  8778. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  8779. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  8780. ++i;
  8781. }
  8782. // i now reached the end of at least one array
  8783. // in a second pass, traverse the remaining elements
  8784. // remove my remaining elements
  8785. const auto end_index = static_cast<difference_type>(result.size());
  8786. while (i < source.size())
  8787. {
  8788. // add operations in reverse order to avoid invalid
  8789. // indices
  8790. result.insert(result.begin() + end_index, object(
  8791. {
  8792. {"op", "remove"},
  8793. {"path", path + "/" + std::to_string(i)}
  8794. }));
  8795. ++i;
  8796. }
  8797. // add other remaining elements
  8798. while (i < target.size())
  8799. {
  8800. result.push_back(
  8801. {
  8802. {"op", "add"},
  8803. {"path", path + "/" + std::to_string(i)},
  8804. {"value", target[i]}
  8805. });
  8806. ++i;
  8807. }
  8808. break;
  8809. }
  8810. case value_t::object:
  8811. {
  8812. // first pass: traverse this object's elements
  8813. for (auto it = source.begin(); it != source.end(); ++it)
  8814. {
  8815. // escape the key name to be used in a JSON patch
  8816. const auto key = json_pointer::escape(it.key());
  8817. if (target.find(it.key()) != target.end())
  8818. {
  8819. // recursive call to compare object values at key it
  8820. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  8821. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  8822. }
  8823. else
  8824. {
  8825. // found a key that is not in o -> remove it
  8826. result.push_back(object(
  8827. {
  8828. {"op", "remove"},
  8829. {"path", path + "/" + key}
  8830. }));
  8831. }
  8832. }
  8833. // second pass: traverse other object's elements
  8834. for (auto it = target.begin(); it != target.end(); ++it)
  8835. {
  8836. if (source.find(it.key()) == source.end())
  8837. {
  8838. // found a key that is not in this -> add it
  8839. const auto key = json_pointer::escape(it.key());
  8840. result.push_back(
  8841. {
  8842. {"op", "add"},
  8843. {"path", path + "/" + key},
  8844. {"value", it.value()}
  8845. });
  8846. }
  8847. }
  8848. break;
  8849. }
  8850. default:
  8851. {
  8852. // both primitive type: replace value
  8853. result.push_back(
  8854. {
  8855. {"op", "replace"},
  8856. {"path", path},
  8857. {"value", target}
  8858. });
  8859. break;
  8860. }
  8861. }
  8862. }
  8863. return result;
  8864. }
  8865. /// @}
  8866. };
  8867. /////////////
  8868. // presets //
  8869. /////////////
  8870. /*!
  8871. @brief default JSON class
  8872. This type is the default specialization of the @ref basic_json class which
  8873. uses the standard template types.
  8874. @since version 1.0.0
  8875. */
  8876. using json = basic_json<>;
  8877. }
  8878. ///////////////////////
  8879. // nonmember support //
  8880. ///////////////////////
  8881. // specialization of std::swap, and std::hash
  8882. namespace std
  8883. {
  8884. /*!
  8885. @brief exchanges the values of two JSON objects
  8886. @since version 1.0.0
  8887. */
  8888. template<>
  8889. inline void swap(nlohmann::json& j1,
  8890. nlohmann::json& j2) noexcept(
  8891. is_nothrow_move_constructible<nlohmann::json>::value and
  8892. is_nothrow_move_assignable<nlohmann::json>::value
  8893. )
  8894. {
  8895. j1.swap(j2);
  8896. }
  8897. /// hash value for JSON objects
  8898. template<>
  8899. struct hash<nlohmann::json>
  8900. {
  8901. /*!
  8902. @brief return a hash value for a JSON object
  8903. @since version 1.0.0
  8904. */
  8905. std::size_t operator()(const nlohmann::json& j) const
  8906. {
  8907. // a naive hashing via the string representation
  8908. const auto& h = hash<nlohmann::json::string_t>();
  8909. return h(j.dump());
  8910. }
  8911. };
  8912. }
  8913. /*!
  8914. @brief user-defined string literal for JSON values
  8915. This operator implements a user-defined string literal for JSON objects. It
  8916. can be used by adding `"_json"` to a string literal and returns a JSON object
  8917. if no parse error occurred.
  8918. @param[in] s a string representation of a JSON object
  8919. @param[in] n the length of string @a s
  8920. @return a JSON object
  8921. @since version 1.0.0
  8922. */
  8923. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  8924. {
  8925. return nlohmann::json::parse(s, s + n);
  8926. }
  8927. /*!
  8928. @brief user-defined string literal for JSON pointer
  8929. This operator implements a user-defined string literal for JSON Pointers. It
  8930. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  8931. object if no parse error occurred.
  8932. @param[in] s a string representation of a JSON Pointer
  8933. @param[in] n the length of string @a s
  8934. @return a JSON pointer object
  8935. @since version 2.0.0
  8936. */
  8937. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  8938. {
  8939. return nlohmann::json::json_pointer(std::string(s, n));
  8940. }
  8941. // restore GCC/clang diagnostic settings
  8942. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  8943. #pragma GCC diagnostic pop
  8944. #endif
  8945. #endif