json.hpp 493 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 2.1.1
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
  8. Permission is hereby granted, free of charge, to any person obtaining a copy
  9. of this software and associated documentation files (the "Software"), to deal
  10. in the Software without restriction, including without limitation the rights
  11. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. copies of the Software, and to permit persons to whom the Software is
  13. furnished to do so, subject to the following conditions:
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. SOFTWARE.
  23. */
  24. #ifndef NLOHMANN_JSON_HPP
  25. #define NLOHMANN_JSON_HPP
  26. #include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform
  27. #include <array> // array
  28. #include <cassert> // assert
  29. #include <ciso646> // and, not, or
  30. #include <clocale> // lconv, localeconv
  31. #include <cmath> // isfinite, labs, ldexp, signbit
  32. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  33. #include <cstdint> // int64_t, uint64_t
  34. #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
  35. #include <cstring> // memcpy, strlen
  36. #include <forward_list> // forward_list
  37. #include <functional> // function, hash, less
  38. #include <initializer_list> // initializer_list
  39. #include <iomanip> // hex
  40. #include <iosfwd> // istream, ostream
  41. #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
  42. #include <limits> // numeric_limits
  43. #include <locale> // locale
  44. #include <map> // map
  45. #include <memory> // addressof, allocator, allocator_traits, unique_ptr
  46. #include <numeric> // accumulate
  47. #include <sstream> // stringstream
  48. #include <string> // getline, stoi, string, to_string
  49. #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
  50. #include <utility> // declval, forward, make_pair, move, pair, swap
  51. #include <valarray> // valarray
  52. #include <vector> // vector
  53. // exclude unsupported compilers
  54. #if defined(__clang__)
  55. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  56. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  57. #endif
  58. #elif defined(__GNUC__)
  59. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  60. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  61. #endif
  62. #endif
  63. // disable float-equal warnings on GCC/clang
  64. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  65. #pragma GCC diagnostic push
  66. #pragma GCC diagnostic ignored "-Wfloat-equal"
  67. #endif
  68. // disable documentation warnings on clang
  69. #if defined(__clang__)
  70. #pragma GCC diagnostic push
  71. #pragma GCC diagnostic ignored "-Wdocumentation"
  72. #endif
  73. // allow for portable deprecation warnings
  74. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  75. #define JSON_DEPRECATED __attribute__((deprecated))
  76. #elif defined(_MSC_VER)
  77. #define JSON_DEPRECATED __declspec(deprecated)
  78. #else
  79. #define JSON_DEPRECATED
  80. #endif
  81. // allow to disable exceptions
  82. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)
  83. #define JSON_THROW(exception) throw exception
  84. #define JSON_TRY try
  85. #define JSON_CATCH(exception) catch(exception)
  86. #else
  87. #define JSON_THROW(exception) std::abort()
  88. #define JSON_TRY if(true)
  89. #define JSON_CATCH(exception) if(false)
  90. #endif
  91. // manual branch prediction
  92. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  93. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  94. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  95. #else
  96. #define JSON_LIKELY(x) x
  97. #define JSON_UNLIKELY(x) x
  98. #endif
  99. /*!
  100. @brief namespace for Niels Lohmann
  101. @see https://github.com/nlohmann
  102. @since version 1.0.0
  103. */
  104. namespace nlohmann
  105. {
  106. template<typename = void, typename = void>
  107. struct adl_serializer;
  108. // forward declaration of basic_json (required to split the class)
  109. template<template<typename U, typename V, typename... Args> class ObjectType =
  110. std::map,
  111. template<typename U, typename... Args> class ArrayType = std::vector,
  112. class StringType = std::string, class BooleanType = bool,
  113. class NumberIntegerType = std::int64_t,
  114. class NumberUnsignedType = std::uint64_t,
  115. class NumberFloatType = double,
  116. template<typename U> class AllocatorType = std::allocator,
  117. template<typename T, typename SFINAE = void> class JSONSerializer =
  118. adl_serializer>
  119. class basic_json;
  120. // Ugly macros to avoid uglier copy-paste when specializing basic_json
  121. // This is only temporary and will be removed in 3.0
  122. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  123. template<template<typename, typename, typename...> class ObjectType, \
  124. template<typename, typename...> class ArrayType, \
  125. class StringType, class BooleanType, class NumberIntegerType, \
  126. class NumberUnsignedType, class NumberFloatType, \
  127. template<typename> class AllocatorType, \
  128. template<typename, typename = void> class JSONSerializer>
  129. #define NLOHMANN_BASIC_JSON_TPL \
  130. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  131. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  132. AllocatorType, JSONSerializer>
  133. /*!
  134. @brief unnamed namespace with internal helper functions
  135. This namespace collects some functions that could not be defined inside the
  136. @ref basic_json class.
  137. @since version 2.1.0
  138. */
  139. namespace detail
  140. {
  141. ////////////////
  142. // exceptions //
  143. ////////////////
  144. /*!
  145. @brief general exception of the @ref basic_json class
  146. This class is an extension of `std::exception` objects with a member @a id for
  147. exception ids. It is used as the base class for all exceptions thrown by the
  148. @ref basic_json class. This class can hence be used as "wildcard" to catch
  149. exceptions.
  150. Subclasses:
  151. - @ref parse_error for exceptions indicating a parse error
  152. - @ref invalid_iterator for exceptions indicating errors with iterators
  153. - @ref type_error for exceptions indicating executing a member function with
  154. a wrong type
  155. - @ref out_of_range for exceptions indicating access out of the defined range
  156. - @ref other_error for exceptions indicating other library errors
  157. @internal
  158. @note To have nothrow-copy-constructible exceptions, we internally use
  159. `std::runtime_error` which can cope with arbitrary-length error messages.
  160. Intermediate strings are built with static functions and then passed to
  161. the actual constructor.
  162. @endinternal
  163. @liveexample{The following code shows how arbitrary library exceptions can be
  164. caught.,exception}
  165. @since version 3.0.0
  166. */
  167. class exception : public std::exception
  168. {
  169. public:
  170. /// returns the explanatory string
  171. const char* what() const noexcept override
  172. {
  173. return m.what();
  174. }
  175. /// the id of the exception
  176. const int id;
  177. protected:
  178. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  179. static std::string name(const std::string& ename, int id)
  180. {
  181. return "[json.exception." + ename + "." + std::to_string(id) + "] ";
  182. }
  183. private:
  184. /// an exception object as storage for error messages
  185. std::runtime_error m;
  186. };
  187. /*!
  188. @brief exception indicating a parse error
  189. This excpetion is thrown by the library when a parse error occurs. Parse errors
  190. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  191. as when using JSON Patch.
  192. Member @a byte holds the byte index of the last read character in the input
  193. file.
  194. Exceptions have ids 1xx.
  195. name / id | example message | description
  196. ------------------------------ | --------------- | -------------------------
  197. json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
  198. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
  199. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
  200. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
  201. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
  202. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number wihtout a leading `0`.
  203. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
  204. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
  205. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  206. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
  207. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xf8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
  208. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
  209. @note For an input with n bytes, 1 is the index of the first character and n+1
  210. is the index of the terminating null byte or the end of file. This also
  211. holds true when reading a byte vector (CBOR or MessagePack).
  212. @liveexample{The following code shows how a `parse_error` exception can be
  213. caught.,parse_error}
  214. @sa @ref exception for the base class of the library exceptions
  215. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  216. @sa @ref type_error for exceptions indicating executing a member function with
  217. a wrong type
  218. @sa @ref out_of_range for exceptions indicating access out of the defined range
  219. @sa @ref other_error for exceptions indicating other library errors
  220. @since version 3.0.0
  221. */
  222. class parse_error : public exception
  223. {
  224. public:
  225. /*!
  226. @brief create a parse error exception
  227. @param[in] id the id of the exception
  228. @param[in] byte_ the byte index where the error occurred (or 0 if the
  229. position cannot be determined)
  230. @param[in] what_arg the explanatory string
  231. @return parse_error object
  232. */
  233. static parse_error create(int id, std::size_t byte_, const std::string& what_arg)
  234. {
  235. std::string w = exception::name("parse_error", id) + "parse error" +
  236. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  237. ": " + what_arg;
  238. return parse_error(id, byte_, w.c_str());
  239. }
  240. /*!
  241. @brief byte index of the parse error
  242. The byte index of the last read character in the input file.
  243. @note For an input with n bytes, 1 is the index of the first character and
  244. n+1 is the index of the terminating null byte or the end of file.
  245. This also holds true when reading a byte vector (CBOR or MessagePack).
  246. */
  247. const std::size_t byte;
  248. private:
  249. parse_error(int id_, std::size_t byte_, const char* what_arg)
  250. : exception(id_, what_arg), byte(byte_) {}
  251. };
  252. /*!
  253. @brief exception indicating errors with iterators
  254. This exception is thrown if iterators passed to a library function do not match
  255. the expected semantics.
  256. Exceptions have ids 2xx.
  257. name / id | example message | description
  258. ----------------------------------- | --------------- | -------------------------
  259. json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  260. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
  261. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
  262. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
  263. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
  264. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
  265. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
  266. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  267. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  268. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  269. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
  270. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  271. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  272. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
  273. @liveexample{The following code shows how an `invalid_iterator` exception can be
  274. caught.,invalid_iterator}
  275. @sa @ref exception for the base class of the library exceptions
  276. @sa @ref parse_error for exceptions indicating a parse error
  277. @sa @ref type_error for exceptions indicating executing a member function with
  278. a wrong type
  279. @sa @ref out_of_range for exceptions indicating access out of the defined range
  280. @sa @ref other_error for exceptions indicating other library errors
  281. @since version 3.0.0
  282. */
  283. class invalid_iterator : public exception
  284. {
  285. public:
  286. static invalid_iterator create(int id, const std::string& what_arg)
  287. {
  288. std::string w = exception::name("invalid_iterator", id) + what_arg;
  289. return invalid_iterator(id, w.c_str());
  290. }
  291. private:
  292. invalid_iterator(int id_, const char* what_arg)
  293. : exception(id_, what_arg) {}
  294. };
  295. /*!
  296. @brief exception indicating executing a member function with a wrong type
  297. This exception is thrown in case of a type error; that is, a library function is
  298. executed on a JSON value whose type does not match the expected semantics.
  299. Exceptions have ids 3xx.
  300. name / id | example message | description
  301. ----------------------------- | --------------- | -------------------------
  302. json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
  303. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
  304. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
  305. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  306. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  307. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  308. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  309. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
  310. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  311. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  312. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
  313. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  314. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
  315. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  316. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
  317. @liveexample{The following code shows how a `type_error` exception can be
  318. caught.,type_error}
  319. @sa @ref exception for the base class of the library exceptions
  320. @sa @ref parse_error for exceptions indicating a parse error
  321. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  322. @sa @ref out_of_range for exceptions indicating access out of the defined range
  323. @sa @ref other_error for exceptions indicating other library errors
  324. @since version 3.0.0
  325. */
  326. class type_error : public exception
  327. {
  328. public:
  329. static type_error create(int id, const std::string& what_arg)
  330. {
  331. std::string w = exception::name("type_error", id) + what_arg;
  332. return type_error(id, w.c_str());
  333. }
  334. private:
  335. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  336. };
  337. /*!
  338. @brief exception indicating access out of the defined range
  339. This exception is thrown in case a library function is called on an input
  340. parameter that exceeds the expected range, for instance in case of array
  341. indices or nonexisting object keys.
  342. Exceptions have ids 4xx.
  343. name / id | example message | description
  344. ------------------------------- | --------------- | -------------------------
  345. json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
  346. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
  347. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  348. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  349. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
  350. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
  351. @liveexample{The following code shows how an `out_of_range` exception can be
  352. caught.,out_of_range}
  353. @sa @ref exception for the base class of the library exceptions
  354. @sa @ref parse_error for exceptions indicating a parse error
  355. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  356. @sa @ref type_error for exceptions indicating executing a member function with
  357. a wrong type
  358. @sa @ref other_error for exceptions indicating other library errors
  359. @since version 3.0.0
  360. */
  361. class out_of_range : public exception
  362. {
  363. public:
  364. static out_of_range create(int id, const std::string& what_arg)
  365. {
  366. std::string w = exception::name("out_of_range", id) + what_arg;
  367. return out_of_range(id, w.c_str());
  368. }
  369. private:
  370. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  371. };
  372. /*!
  373. @brief exception indicating other library errors
  374. This exception is thrown in case of errors that cannot be classified with the
  375. other exception types.
  376. Exceptions have ids 5xx.
  377. name / id | example message | description
  378. ------------------------------ | --------------- | -------------------------
  379. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  380. json.exception.other_error.502 | invalid object size for conversion | Some conversions to user-defined types impose constraints on the object size (e.g. std::pair)
  381. @sa @ref exception for the base class of the library exceptions
  382. @sa @ref parse_error for exceptions indicating a parse error
  383. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  384. @sa @ref type_error for exceptions indicating executing a member function with
  385. a wrong type
  386. @sa @ref out_of_range for exceptions indicating access out of the defined range
  387. @liveexample{The following code shows how an `other_error` exception can be
  388. caught.,other_error}
  389. @since version 3.0.0
  390. */
  391. class other_error : public exception
  392. {
  393. public:
  394. static other_error create(int id, const std::string& what_arg)
  395. {
  396. std::string w = exception::name("other_error", id) + what_arg;
  397. return other_error(id, w.c_str());
  398. }
  399. private:
  400. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  401. };
  402. ///////////////////////////
  403. // JSON type enumeration //
  404. ///////////////////////////
  405. /*!
  406. @brief the JSON type enumeration
  407. This enumeration collects the different JSON types. It is internally used to
  408. distinguish the stored values, and the functions @ref basic_json::is_null(),
  409. @ref basic_json::is_object(), @ref basic_json::is_array(),
  410. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  411. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  412. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  413. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  414. @ref basic_json::is_structured() rely on it.
  415. @note There are three enumeration entries (number_integer, number_unsigned, and
  416. number_float), because the library distinguishes these three types for numbers:
  417. @ref basic_json::number_unsigned_t is used for unsigned integers,
  418. @ref basic_json::number_integer_t is used for signed integers, and
  419. @ref basic_json::number_float_t is used for floating-point numbers or to
  420. approximate integers which do not fit in the limits of their respective type.
  421. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  422. value with the default value for a given type
  423. @since version 1.0.0
  424. */
  425. enum class value_t : uint8_t
  426. {
  427. null, ///< null value
  428. object, ///< object (unordered set of name/value pairs)
  429. array, ///< array (ordered collection of values)
  430. string, ///< string value
  431. boolean, ///< boolean value
  432. number_integer, ///< number value (signed integer)
  433. number_unsigned, ///< number value (unsigned integer)
  434. number_float, ///< number value (floating-point)
  435. discarded ///< discarded by the the parser callback function
  436. };
  437. /*!
  438. @brief comparison operator for JSON types
  439. Returns an ordering that is similar to Python:
  440. - order: null < boolean < number < object < array < string
  441. - furthermore, each type is not smaller than itself
  442. @since version 1.0.0
  443. */
  444. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  445. {
  446. static constexpr std::array<uint8_t, 8> order = {{
  447. 0, // null
  448. 3, // object
  449. 4, // array
  450. 5, // string
  451. 1, // boolean
  452. 2, // integer
  453. 2, // unsigned
  454. 2, // float
  455. }
  456. };
  457. // discarded values are not comparable
  458. return lhs != value_t::discarded and rhs != value_t::discarded and
  459. order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
  460. }
  461. /////////////
  462. // helpers //
  463. /////////////
  464. template<typename> struct is_basic_json : std::false_type {};
  465. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  466. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  467. // alias templates to reduce boilerplate
  468. template<bool B, typename T = void>
  469. using enable_if_t = typename std::enable_if<B, T>::type;
  470. template<typename T>
  471. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  472. // implementation of C++14 index_sequence and affiliates
  473. // source: https://stackoverflow.com/a/32223343
  474. template<std::size_t... Ints>
  475. struct index_sequence
  476. {
  477. using type = index_sequence;
  478. using value_type = std::size_t;
  479. static constexpr std::size_t size() noexcept
  480. {
  481. return sizeof...(Ints);
  482. }
  483. };
  484. template<class Sequence1, class Sequence2>
  485. struct merge_and_renumber;
  486. template<std::size_t... I1, std::size_t... I2>
  487. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  488. : index_sequence < I1..., (sizeof...(I1) + I2)... >
  489. {};
  490. template<std::size_t N>
  491. struct make_index_sequence
  492. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  493. typename make_index_sequence < N - N / 2 >::type >
  494. {};
  495. template<> struct make_index_sequence<0> : index_sequence<> { };
  496. template<> struct make_index_sequence<1> : index_sequence<0> { };
  497. template<typename... Ts>
  498. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  499. /*
  500. Implementation of two C++17 constructs: conjunction, negation. This is needed
  501. to avoid evaluating all the traits in a condition
  502. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  503. will not compile when T = void (on MSVC at least). Whereas
  504. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  505. stop evaluating if negation<...>::value == false
  506. Please note that those constructs must be used with caution, since symbols can
  507. become very long quickly (which can slow down compilation and cause MSVC
  508. internal compiler errors). Only use it when you have to (see example ahead).
  509. */
  510. template<class...> struct conjunction : std::true_type {};
  511. template<class B1> struct conjunction<B1> : B1 {};
  512. template<class B1, class... Bn>
  513. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  514. template<class B> struct negation : std::integral_constant < bool, !B::value > {};
  515. // dispatch utility (taken from ranges-v3)
  516. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  517. template<> struct priority_tag<0> {};
  518. //////////////////
  519. // constructors //
  520. //////////////////
  521. template<value_t> struct external_constructor;
  522. template<>
  523. struct external_constructor<value_t::boolean>
  524. {
  525. template<typename BasicJsonType>
  526. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  527. {
  528. j.m_type = value_t::boolean;
  529. j.m_value = b;
  530. j.assert_invariant();
  531. }
  532. };
  533. template<>
  534. struct external_constructor<value_t::string>
  535. {
  536. template<typename BasicJsonType>
  537. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  538. {
  539. j.m_type = value_t::string;
  540. j.m_value = s;
  541. j.assert_invariant();
  542. }
  543. template<typename BasicJsonType>
  544. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  545. {
  546. j.m_type = value_t::string;
  547. j.m_value = std::move(s);
  548. j.assert_invariant();
  549. }
  550. };
  551. template<>
  552. struct external_constructor<value_t::number_float>
  553. {
  554. template<typename BasicJsonType>
  555. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  556. {
  557. j.m_type = value_t::number_float;
  558. j.m_value = val;
  559. j.assert_invariant();
  560. }
  561. };
  562. template<>
  563. struct external_constructor<value_t::number_unsigned>
  564. {
  565. template<typename BasicJsonType>
  566. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  567. {
  568. j.m_type = value_t::number_unsigned;
  569. j.m_value = val;
  570. j.assert_invariant();
  571. }
  572. };
  573. template<>
  574. struct external_constructor<value_t::number_integer>
  575. {
  576. template<typename BasicJsonType>
  577. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  578. {
  579. j.m_type = value_t::number_integer;
  580. j.m_value = val;
  581. j.assert_invariant();
  582. }
  583. };
  584. template<>
  585. struct external_constructor<value_t::array>
  586. {
  587. template<typename BasicJsonType>
  588. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  589. {
  590. j.m_type = value_t::array;
  591. j.m_value = arr;
  592. j.assert_invariant();
  593. }
  594. template<typename BasicJsonType>
  595. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  596. {
  597. j.m_type = value_t::array;
  598. j.m_value = std::move(arr);
  599. j.assert_invariant();
  600. }
  601. template<typename BasicJsonType, typename CompatibleArrayType,
  602. enable_if_t<not std::is_same<CompatibleArrayType,
  603. typename BasicJsonType::array_t>::value,
  604. int> = 0>
  605. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  606. {
  607. using std::begin;
  608. using std::end;
  609. j.m_type = value_t::array;
  610. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  611. j.assert_invariant();
  612. }
  613. template<typename BasicJsonType>
  614. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  615. {
  616. j.m_type = value_t::array;
  617. j.m_value = value_t::array;
  618. j.m_value.array->reserve(arr.size());
  619. for (bool x : arr)
  620. {
  621. j.m_value.array->push_back(x);
  622. }
  623. j.assert_invariant();
  624. }
  625. template<typename BasicJsonType, typename T,
  626. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  627. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  628. {
  629. using std::begin;
  630. using std::end;
  631. j.m_type = value_t::array;
  632. j.m_value = value_t::array;
  633. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  634. j.assert_invariant();
  635. }
  636. };
  637. template<>
  638. struct external_constructor<value_t::object>
  639. {
  640. template<typename BasicJsonType>
  641. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  642. {
  643. j.m_type = value_t::object;
  644. j.m_value = obj;
  645. j.assert_invariant();
  646. }
  647. template<typename BasicJsonType>
  648. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  649. {
  650. j.m_type = value_t::object;
  651. j.m_value = std::move(obj);
  652. j.assert_invariant();
  653. }
  654. template<typename BasicJsonType, typename CompatibleObjectType,
  655. enable_if_t<not std::is_same<CompatibleObjectType,
  656. typename BasicJsonType::object_t>::value, int> = 0>
  657. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  658. {
  659. using std::begin;
  660. using std::end;
  661. j.m_type = value_t::object;
  662. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  663. j.assert_invariant();
  664. }
  665. };
  666. ////////////////////////
  667. // has_/is_ functions //
  668. ////////////////////////
  669. /*!
  670. @brief Helper to determine whether there's a key_type for T.
  671. This helper is used to tell associative containers apart from other containers
  672. such as sequence containers. For instance, `std::map` passes the test as it
  673. contains a `mapped_type`, whereas `std::vector` fails the test.
  674. @sa http://stackoverflow.com/a/7728728/266378
  675. @since version 1.0.0, overworked in version 2.0.6
  676. */
  677. #define NLOHMANN_JSON_HAS_HELPER(type) \
  678. template<typename T> struct has_##type { \
  679. private: \
  680. template<typename U, typename = typename U::type> \
  681. static int detect(U &&); \
  682. static void detect(...); \
  683. public: \
  684. static constexpr bool value = \
  685. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  686. }
  687. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  688. NLOHMANN_JSON_HAS_HELPER(key_type);
  689. NLOHMANN_JSON_HAS_HELPER(value_type);
  690. NLOHMANN_JSON_HAS_HELPER(iterator);
  691. #undef NLOHMANN_JSON_HAS_HELPER
  692. template<bool B, class RealType, class CompatibleObjectType>
  693. struct is_compatible_object_type_impl : std::false_type {};
  694. template<class RealType, class CompatibleObjectType>
  695. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  696. {
  697. static constexpr auto value =
  698. std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
  699. std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
  700. };
  701. template<class BasicJsonType, class CompatibleObjectType>
  702. struct is_compatible_object_type
  703. {
  704. static auto constexpr value = is_compatible_object_type_impl <
  705. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  706. has_mapped_type<CompatibleObjectType>,
  707. has_key_type<CompatibleObjectType>>::value,
  708. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  709. };
  710. template<typename BasicJsonType, typename T>
  711. struct is_basic_json_nested_type
  712. {
  713. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  714. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  715. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  716. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
  717. };
  718. template<class BasicJsonType, class CompatibleArrayType>
  719. struct is_compatible_array_type
  720. {
  721. static auto constexpr value =
  722. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  723. negation<is_compatible_object_type<
  724. BasicJsonType, CompatibleArrayType>>,
  725. negation<std::is_constructible<typename BasicJsonType::string_t,
  726. CompatibleArrayType>>,
  727. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  728. has_value_type<CompatibleArrayType>,
  729. has_iterator<CompatibleArrayType>>::value;
  730. };
  731. template<bool, typename, typename>
  732. struct is_compatible_integer_type_impl : std::false_type {};
  733. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  734. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  735. {
  736. // is there an assert somewhere on overflows?
  737. using RealLimits = std::numeric_limits<RealIntegerType>;
  738. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  739. static constexpr auto value =
  740. std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
  741. CompatibleLimits::is_integer and
  742. RealLimits::is_signed == CompatibleLimits::is_signed;
  743. };
  744. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  745. struct is_compatible_integer_type
  746. {
  747. static constexpr auto value =
  748. is_compatible_integer_type_impl <
  749. std::is_integral<CompatibleNumberIntegerType>::value and
  750. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  751. RealIntegerType, CompatibleNumberIntegerType > ::value;
  752. };
  753. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  754. template<typename BasicJsonType, typename T>
  755. struct has_from_json
  756. {
  757. private:
  758. // also check the return type of from_json
  759. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  760. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  761. static int detect(U&&);
  762. static void detect(...);
  763. public:
  764. static constexpr bool value = std::is_integral<decltype(
  765. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  766. };
  767. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  768. // this overload is used for non-default-constructible user-defined-types
  769. template<typename BasicJsonType, typename T>
  770. struct has_non_default_from_json
  771. {
  772. private:
  773. template <
  774. typename U,
  775. typename = enable_if_t<std::is_same<
  776. T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
  777. static int detect(U&&);
  778. static void detect(...);
  779. public:
  780. static constexpr bool value = std::is_integral<decltype(detect(
  781. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  782. };
  783. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  784. template<typename BasicJsonType, typename T>
  785. struct has_to_json
  786. {
  787. private:
  788. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  789. std::declval<BasicJsonType&>(), std::declval<T>()))>
  790. static int detect(U&&);
  791. static void detect(...);
  792. public:
  793. static constexpr bool value = std::is_integral<decltype(detect(
  794. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  795. };
  796. /////////////
  797. // to_json //
  798. /////////////
  799. template<typename BasicJsonType, typename T, enable_if_t<
  800. std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  801. void to_json(BasicJsonType& j, T b) noexcept
  802. {
  803. external_constructor<value_t::boolean>::construct(j, b);
  804. }
  805. template<typename BasicJsonType, typename CompatibleString,
  806. enable_if_t<std::is_constructible<typename BasicJsonType::string_t,
  807. CompatibleString>::value, int> = 0>
  808. void to_json(BasicJsonType& j, const CompatibleString& s)
  809. {
  810. external_constructor<value_t::string>::construct(j, s);
  811. }
  812. template <typename BasicJsonType>
  813. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  814. {
  815. external_constructor<value_t::string>::construct(j, std::move(s));
  816. }
  817. template<typename BasicJsonType, typename FloatType,
  818. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  819. void to_json(BasicJsonType& j, FloatType val) noexcept
  820. {
  821. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  822. }
  823. template <
  824. typename BasicJsonType, typename CompatibleNumberUnsignedType,
  825. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
  826. CompatibleNumberUnsignedType>::value, int> = 0 >
  827. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  828. {
  829. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  830. }
  831. template <
  832. typename BasicJsonType, typename CompatibleNumberIntegerType,
  833. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t,
  834. CompatibleNumberIntegerType>::value, int> = 0 >
  835. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  836. {
  837. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  838. }
  839. template<typename BasicJsonType, typename EnumType,
  840. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  841. void to_json(BasicJsonType& j, EnumType e) noexcept
  842. {
  843. using underlying_type = typename std::underlying_type<EnumType>::type;
  844. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  845. }
  846. template<typename BasicJsonType>
  847. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  848. {
  849. external_constructor<value_t::array>::construct(j, e);
  850. }
  851. template <
  852. typename BasicJsonType, typename CompatibleArrayType,
  853. enable_if_t <
  854. is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  855. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  856. int > = 0 >
  857. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  858. {
  859. external_constructor<value_t::array>::construct(j, arr);
  860. }
  861. template <typename BasicJsonType, typename T,
  862. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  863. void to_json(BasicJsonType& j, std::valarray<T> arr)
  864. {
  865. external_constructor<value_t::array>::construct(j, std::move(arr));
  866. }
  867. template <typename BasicJsonType>
  868. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  869. {
  870. external_constructor<value_t::array>::construct(j, std::move(arr));
  871. }
  872. template <
  873. typename BasicJsonType, typename CompatibleObjectType,
  874. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value,
  875. int> = 0 >
  876. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  877. {
  878. external_constructor<value_t::object>::construct(j, obj);
  879. }
  880. template <typename BasicJsonType>
  881. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  882. {
  883. external_constructor<value_t::object>::construct(j, std::move(obj));
  884. }
  885. template<typename BasicJsonType, typename T, std::size_t N,
  886. enable_if_t<not std::is_constructible<
  887. typename BasicJsonType::string_t, T (&)[N]>::value,
  888. int> = 0>
  889. void to_json(BasicJsonType& j, T (&arr)[N])
  890. {
  891. external_constructor<value_t::array>::construct(j, arr);
  892. }
  893. template<typename BasicJsonType, typename... Args>
  894. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  895. {
  896. j = {p.first, p.second};
  897. }
  898. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  899. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
  900. {
  901. j = {std::get<Idx>(t)...};
  902. }
  903. template<typename BasicJsonType, typename... Args>
  904. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  905. {
  906. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  907. }
  908. ///////////////
  909. // from_json //
  910. ///////////////
  911. // overloads for basic_json template parameters
  912. template<typename BasicJsonType, typename ArithmeticType,
  913. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  914. not std::is_same<ArithmeticType,
  915. typename BasicJsonType::boolean_t>::value,
  916. int> = 0>
  917. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  918. {
  919. switch (static_cast<value_t>(j))
  920. {
  921. case value_t::number_unsigned:
  922. {
  923. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  924. break;
  925. }
  926. case value_t::number_integer:
  927. {
  928. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  929. break;
  930. }
  931. case value_t::number_float:
  932. {
  933. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  934. break;
  935. }
  936. default:
  937. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  938. }
  939. }
  940. template<typename BasicJsonType>
  941. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  942. {
  943. if (JSON_UNLIKELY(not j.is_boolean()))
  944. {
  945. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  946. }
  947. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  948. }
  949. template<typename BasicJsonType>
  950. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  951. {
  952. if (JSON_UNLIKELY(not j.is_string()))
  953. {
  954. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  955. }
  956. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  957. }
  958. template<typename BasicJsonType>
  959. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  960. {
  961. get_arithmetic_value(j, val);
  962. }
  963. template<typename BasicJsonType>
  964. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  965. {
  966. get_arithmetic_value(j, val);
  967. }
  968. template<typename BasicJsonType>
  969. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  970. {
  971. get_arithmetic_value(j, val);
  972. }
  973. template<typename BasicJsonType, typename EnumType,
  974. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  975. void from_json(const BasicJsonType& j, EnumType& e)
  976. {
  977. typename std::underlying_type<EnumType>::type val;
  978. get_arithmetic_value(j, val);
  979. e = static_cast<EnumType>(val);
  980. }
  981. template<typename BasicJsonType>
  982. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  983. {
  984. if (JSON_UNLIKELY(not j.is_array()))
  985. {
  986. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  987. }
  988. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  989. }
  990. // forward_list doesn't have an insert method
  991. template<typename BasicJsonType, typename T, typename Allocator,
  992. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  993. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  994. {
  995. if (JSON_UNLIKELY(not j.is_array()))
  996. {
  997. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  998. }
  999. std::transform(j.rbegin(), j.rend(),
  1000. std::front_inserter(l), [](const BasicJsonType & i)
  1001. {
  1002. return i.template get<T>();
  1003. });
  1004. }
  1005. // valarray doesn't have an insert method
  1006. template<typename BasicJsonType, typename T,
  1007. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  1008. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  1009. {
  1010. if (JSON_UNLIKELY(not j.is_array()))
  1011. {
  1012. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1013. }
  1014. l.resize(j.size());
  1015. for (size_t i = 0; i < j.size(); ++i)
  1016. {
  1017. l[i] = j[i];
  1018. }
  1019. }
  1020. template<typename BasicJsonType, typename CompatibleArrayType>
  1021. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
  1022. {
  1023. using std::end;
  1024. std::transform(j.begin(), j.end(),
  1025. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1026. {
  1027. // get<BasicJsonType>() returns *this, this won't call a from_json
  1028. // method when value_type is BasicJsonType
  1029. return i.template get<typename CompatibleArrayType::value_type>();
  1030. });
  1031. }
  1032. template<typename BasicJsonType, typename CompatibleArrayType>
  1033. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
  1034. -> decltype(
  1035. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  1036. void())
  1037. {
  1038. using std::end;
  1039. arr.reserve(j.size());
  1040. std::transform(j.begin(), j.end(),
  1041. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  1042. {
  1043. // get<BasicJsonType>() returns *this, this won't call a from_json
  1044. // method when value_type is BasicJsonType
  1045. return i.template get<typename CompatibleArrayType::value_type>();
  1046. });
  1047. }
  1048. template<typename BasicJsonType, typename T, std::size_t N>
  1049. void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
  1050. {
  1051. for (std::size_t i = 0; i < N; ++i)
  1052. {
  1053. arr[i] = j.at(i).template get<T>();
  1054. }
  1055. }
  1056. template<typename BasicJsonType, typename CompatibleArrayType,
  1057. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  1058. std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and
  1059. not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
  1060. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  1061. {
  1062. if (JSON_UNLIKELY(not j.is_array()))
  1063. {
  1064. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1065. }
  1066. from_json_array_impl(j, arr, priority_tag<2> {});
  1067. }
  1068. template<typename BasicJsonType, typename CompatibleObjectType,
  1069. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  1070. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  1071. {
  1072. if (JSON_UNLIKELY(not j.is_object()))
  1073. {
  1074. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  1075. }
  1076. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  1077. using value_type = typename CompatibleObjectType::value_type;
  1078. std::transform(
  1079. inner_object->begin(), inner_object->end(),
  1080. std::inserter(obj, obj.begin()),
  1081. [](typename BasicJsonType::object_t::value_type const & p)
  1082. {
  1083. return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
  1084. });
  1085. }
  1086. // overload for arithmetic types, not chosen for basic_json template arguments
  1087. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1088. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1089. // an arithmetic type?
  1090. template<typename BasicJsonType, typename ArithmeticType,
  1091. enable_if_t <
  1092. std::is_arithmetic<ArithmeticType>::value and
  1093. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1094. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1095. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1096. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1097. int> = 0>
  1098. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1099. {
  1100. switch (static_cast<value_t>(j))
  1101. {
  1102. case value_t::number_unsigned:
  1103. {
  1104. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1105. break;
  1106. }
  1107. case value_t::number_integer:
  1108. {
  1109. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1110. break;
  1111. }
  1112. case value_t::number_float:
  1113. {
  1114. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1115. break;
  1116. }
  1117. case value_t::boolean:
  1118. {
  1119. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1120. break;
  1121. }
  1122. default:
  1123. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1124. }
  1125. }
  1126. template<typename BasicJsonType, typename A1, typename A2>
  1127. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1128. {
  1129. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1130. }
  1131. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1132. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
  1133. {
  1134. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1135. }
  1136. template<typename BasicJsonType, typename... Args>
  1137. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1138. {
  1139. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1140. }
  1141. struct to_json_fn
  1142. {
  1143. private:
  1144. template<typename BasicJsonType, typename T>
  1145. auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1146. -> decltype(to_json(j, std::forward<T>(val)), void())
  1147. {
  1148. return to_json(j, std::forward<T>(val));
  1149. }
  1150. template<typename BasicJsonType, typename T>
  1151. void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1152. {
  1153. static_assert(sizeof(BasicJsonType) == 0,
  1154. "could not find to_json() method in T's namespace");
  1155. }
  1156. public:
  1157. template<typename BasicJsonType, typename T>
  1158. void operator()(BasicJsonType& j, T&& val) const
  1159. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  1160. {
  1161. return call(j, std::forward<T>(val), priority_tag<1> {});
  1162. }
  1163. };
  1164. struct from_json_fn
  1165. {
  1166. private:
  1167. template<typename BasicJsonType, typename T>
  1168. auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
  1169. noexcept(noexcept(from_json(j, val)))
  1170. -> decltype(from_json(j, val), void())
  1171. {
  1172. return from_json(j, val);
  1173. }
  1174. template<typename BasicJsonType, typename T>
  1175. void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1176. {
  1177. static_assert(sizeof(BasicJsonType) == 0,
  1178. "could not find from_json() method in T's namespace");
  1179. }
  1180. public:
  1181. template<typename BasicJsonType, typename T>
  1182. void operator()(const BasicJsonType& j, T& val) const
  1183. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  1184. {
  1185. return call(j, val, priority_tag<1> {});
  1186. }
  1187. };
  1188. // taken from ranges-v3
  1189. template<typename T>
  1190. struct static_const
  1191. {
  1192. static constexpr T value{};
  1193. };
  1194. template<typename T>
  1195. constexpr T static_const<T>::value;
  1196. ////////////////////
  1197. // input adapters //
  1198. ////////////////////
  1199. /// abstract input adapter interface
  1200. struct input_adapter_protocol
  1201. {
  1202. virtual int get_character() = 0;
  1203. virtual std::string read(std::size_t offset, std::size_t length) = 0;
  1204. virtual ~input_adapter_protocol() = default;
  1205. };
  1206. /// a type to simplify interfaces
  1207. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1208. /// input adapter for cached stream input
  1209. template<std::size_t BufferSize>
  1210. class cached_input_stream_adapter : public input_adapter_protocol
  1211. {
  1212. public:
  1213. explicit cached_input_stream_adapter(std::istream& i)
  1214. : is(i), start_position(is.tellg())
  1215. {
  1216. fill_buffer();
  1217. // skip byte order mark
  1218. if (fill_size >= 3 and buffer[0] == '\xEF' and buffer[1] == '\xBB' and buffer[2] == '\xBF')
  1219. {
  1220. buffer_pos += 3;
  1221. processed_chars += 3;
  1222. }
  1223. }
  1224. ~cached_input_stream_adapter() override
  1225. {
  1226. // clear stream flags
  1227. is.clear();
  1228. // We initially read a lot of characters into the buffer, and we may
  1229. // not have processed all of them. Therefore, we need to "rewind" the
  1230. // stream after the last processed char.
  1231. is.seekg(start_position);
  1232. is.ignore(static_cast<std::streamsize>(processed_chars));
  1233. // clear stream flags
  1234. is.clear();
  1235. }
  1236. int get_character() override
  1237. {
  1238. // check if refilling is necessary and possible
  1239. if (buffer_pos == fill_size and not eof)
  1240. {
  1241. fill_buffer();
  1242. // check and remember that filling did not yield new input
  1243. if (fill_size == 0)
  1244. {
  1245. eof = true;
  1246. return std::char_traits<char>::eof();
  1247. }
  1248. // the buffer is ready
  1249. buffer_pos = 0;
  1250. }
  1251. ++processed_chars;
  1252. assert(buffer_pos < buffer.size());
  1253. return buffer[buffer_pos++] & 0xFF;
  1254. }
  1255. std::string read(std::size_t offset, std::size_t length) override
  1256. {
  1257. // create buffer
  1258. std::string result(length, '\0');
  1259. // save stream position
  1260. const auto current_pos = is.tellg();
  1261. // save stream flags
  1262. const auto flags = is.rdstate();
  1263. // clear stream flags
  1264. is.clear();
  1265. // set stream position
  1266. is.seekg(static_cast<std::streamoff>(offset));
  1267. // read bytes
  1268. is.read(&result[0], static_cast<std::streamsize>(length));
  1269. // reset stream position
  1270. is.seekg(current_pos);
  1271. // reset stream flags
  1272. is.setstate(flags);
  1273. return result;
  1274. }
  1275. private:
  1276. void fill_buffer()
  1277. {
  1278. // fill
  1279. is.read(buffer.data(), static_cast<std::streamsize>(buffer.size()));
  1280. // store number of bytes in the buffer
  1281. fill_size = static_cast<size_t>(is.gcount());
  1282. }
  1283. /// the associated input stream
  1284. std::istream& is;
  1285. /// chars returned via get_character()
  1286. std::size_t processed_chars = 0;
  1287. /// chars processed in the current buffer
  1288. std::size_t buffer_pos = 0;
  1289. /// whether stream reached eof
  1290. bool eof = false;
  1291. /// how many chars have been copied to the buffer by last (re)fill
  1292. std::size_t fill_size = 0;
  1293. /// position of the stream when we started
  1294. const std::streampos start_position;
  1295. /// internal buffer
  1296. std::array<char, BufferSize> buffer{{}};
  1297. };
  1298. /// input adapter for buffer input
  1299. class input_buffer_adapter : public input_adapter_protocol
  1300. {
  1301. public:
  1302. input_buffer_adapter(const char* b, const std::size_t l)
  1303. : cursor(b), limit(b + l), start(b)
  1304. {
  1305. // skip byte order mark
  1306. if (l >= 3 and b[0] == '\xEF' and b[1] == '\xBB' and b[2] == '\xBF')
  1307. {
  1308. cursor += 3;
  1309. }
  1310. }
  1311. // delete because of pointer members
  1312. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1313. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1314. int get_character() noexcept override
  1315. {
  1316. if (JSON_LIKELY(cursor < limit))
  1317. {
  1318. return *(cursor++) & 0xFF;
  1319. }
  1320. return std::char_traits<char>::eof();
  1321. }
  1322. std::string read(std::size_t offset, std::size_t length) override
  1323. {
  1324. // avoid reading too many characters
  1325. const auto max_length = static_cast<size_t>(limit - start);
  1326. return std::string(start + offset, (std::min)(length, max_length - offset));
  1327. }
  1328. private:
  1329. /// pointer to the current character
  1330. const char* cursor;
  1331. /// pointer past the last character
  1332. const char* limit;
  1333. /// pointer to the first character
  1334. const char* start;
  1335. };
  1336. class input_adapter
  1337. {
  1338. public:
  1339. // native support
  1340. /// input adapter for input stream
  1341. input_adapter(std::istream& i)
  1342. : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {}
  1343. /// input adapter for input stream
  1344. input_adapter(std::istream&& i)
  1345. : ia(std::make_shared<cached_input_stream_adapter<16384>>(i)) {}
  1346. /// input adapter for buffer
  1347. template<typename CharT,
  1348. typename std::enable_if<
  1349. std::is_pointer<CharT>::value and
  1350. std::is_integral<
  1351. typename std::remove_pointer<CharT>::type>::value and
  1352. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1353. int>::type = 0>
  1354. input_adapter(CharT b, std::size_t l)
  1355. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  1356. // derived support
  1357. /// input adapter for string literal
  1358. template<typename CharT,
  1359. typename std::enable_if<
  1360. std::is_pointer<CharT>::value and
  1361. std::is_integral<
  1362. typename std::remove_pointer<CharT>::type>::value and
  1363. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1364. int>::type = 0>
  1365. input_adapter(CharT b)
  1366. : input_adapter(reinterpret_cast<const char*>(b),
  1367. std::strlen(reinterpret_cast<const char*>(b))) {}
  1368. /// input adapter for iterator range with contiguous storage
  1369. template<class IteratorType,
  1370. typename std::enable_if<
  1371. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category,
  1372. std::random_access_iterator_tag>::value,
  1373. int>::type = 0>
  1374. input_adapter(IteratorType first, IteratorType last)
  1375. {
  1376. // assertion to check that the iterator range is indeed contiguous,
  1377. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  1378. assert(std::accumulate(
  1379. first, last, std::pair<bool, int>(true, 0),
  1380. [&first](std::pair<bool, int> res, decltype(*first) val)
  1381. {
  1382. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  1383. return res;
  1384. }).first);
  1385. // assertion to check that each element is 1 byte long
  1386. static_assert(
  1387. sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  1388. "each element in the iterator range must have the size of 1 byte");
  1389. const auto len = static_cast<size_t>(std::distance(first, last));
  1390. if (JSON_LIKELY(len > 0))
  1391. {
  1392. // there is at least one element: use the address of first
  1393. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  1394. }
  1395. else
  1396. {
  1397. // the address of first cannot be used: use nullptr
  1398. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  1399. }
  1400. }
  1401. /// input adapter for array
  1402. template<class T, std::size_t N>
  1403. input_adapter(T (&array)[N])
  1404. : input_adapter(std::begin(array), std::end(array)) {}
  1405. /// input adapter for contiguous container
  1406. template <
  1407. class ContiguousContainer,
  1408. typename std::enable_if <
  1409. not std::is_pointer<ContiguousContainer>::value and
  1410. std::is_base_of<std::random_access_iterator_tag,
  1411. typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  1412. int >::type = 0 >
  1413. input_adapter(const ContiguousContainer& c)
  1414. : input_adapter(std::begin(c), std::end(c)) {}
  1415. operator input_adapter_t()
  1416. {
  1417. return ia;
  1418. }
  1419. private:
  1420. /// the actual adapter
  1421. input_adapter_t ia = nullptr;
  1422. };
  1423. //////////////////////
  1424. // lexer and parser //
  1425. //////////////////////
  1426. /*!
  1427. @brief lexical analysis
  1428. This class organizes the lexical analysis during JSON deserialization.
  1429. */
  1430. template<typename BasicJsonType>
  1431. class lexer
  1432. {
  1433. using number_integer_t = typename BasicJsonType::number_integer_t;
  1434. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  1435. using number_float_t = typename BasicJsonType::number_float_t;
  1436. public:
  1437. /// token types for the parser
  1438. enum class token_type
  1439. {
  1440. uninitialized, ///< indicating the scanner is uninitialized
  1441. literal_true, ///< the `true` literal
  1442. literal_false, ///< the `false` literal
  1443. literal_null, ///< the `null` literal
  1444. value_string, ///< a string -- use get_string() for actual value
  1445. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  1446. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  1447. value_float, ///< an floating point number -- use get_number_float() for actual value
  1448. begin_array, ///< the character for array begin `[`
  1449. begin_object, ///< the character for object begin `{`
  1450. end_array, ///< the character for array end `]`
  1451. end_object, ///< the character for object end `}`
  1452. name_separator, ///< the name separator `:`
  1453. value_separator, ///< the value separator `,`
  1454. parse_error, ///< indicating a parse error
  1455. end_of_input, ///< indicating the end of the input buffer
  1456. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  1457. };
  1458. /// return name of values of type token_type (only used for errors)
  1459. static const char* token_type_name(const token_type t) noexcept
  1460. {
  1461. switch (t)
  1462. {
  1463. case token_type::uninitialized:
  1464. return "<uninitialized>";
  1465. case token_type::literal_true:
  1466. return "true literal";
  1467. case token_type::literal_false:
  1468. return "false literal";
  1469. case token_type::literal_null:
  1470. return "null literal";
  1471. case token_type::value_string:
  1472. return "string literal";
  1473. case lexer::token_type::value_unsigned:
  1474. case lexer::token_type::value_integer:
  1475. case lexer::token_type::value_float:
  1476. return "number literal";
  1477. case token_type::begin_array:
  1478. return "'['";
  1479. case token_type::begin_object:
  1480. return "'{'";
  1481. case token_type::end_array:
  1482. return "']'";
  1483. case token_type::end_object:
  1484. return "'}'";
  1485. case token_type::name_separator:
  1486. return "':'";
  1487. case token_type::value_separator:
  1488. return "','";
  1489. case token_type::parse_error:
  1490. return "<parse error>";
  1491. case token_type::end_of_input:
  1492. return "end of input";
  1493. case token_type::literal_or_value:
  1494. return "'[', '{', or a literal";
  1495. default: // catch non-enum values
  1496. return "unknown token"; // LCOV_EXCL_LINE
  1497. }
  1498. }
  1499. explicit lexer(detail::input_adapter_t adapter)
  1500. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  1501. // delete because of pointer members
  1502. lexer(const lexer&) = delete;
  1503. lexer& operator=(lexer&) = delete;
  1504. private:
  1505. /////////////////////
  1506. // locales
  1507. /////////////////////
  1508. /// return the locale-dependent decimal point
  1509. static char get_decimal_point() noexcept
  1510. {
  1511. const auto loc = localeconv();
  1512. assert(loc != nullptr);
  1513. return (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0];
  1514. }
  1515. /////////////////////
  1516. // scan functions
  1517. /////////////////////
  1518. /*!
  1519. @brief get codepoint from 4 hex characters following `\u`
  1520. For input "\u c1 c2 c3 c4" the codepoint is:
  1521. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  1522. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  1523. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  1524. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  1525. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  1526. between the ASCII value of the character and the desired integer value.
  1527. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  1528. non-hex character)
  1529. */
  1530. int get_codepoint()
  1531. {
  1532. // this function only makes sense after reading `\u`
  1533. assert(current == 'u');
  1534. int codepoint = 0;
  1535. const auto factors = { 12, 8, 4, 0 };
  1536. for (const auto factor : factors)
  1537. {
  1538. get();
  1539. if (current >= '0' and current <= '9')
  1540. {
  1541. codepoint += ((current - 0x30) << factor);
  1542. }
  1543. else if (current >= 'A' and current <= 'F')
  1544. {
  1545. codepoint += ((current - 0x37) << factor);
  1546. }
  1547. else if (current >= 'a' and current <= 'f')
  1548. {
  1549. codepoint += ((current - 0x57) << factor);
  1550. }
  1551. else
  1552. {
  1553. return -1;
  1554. }
  1555. }
  1556. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  1557. return codepoint;
  1558. }
  1559. /*!
  1560. @brief check if the next byte(s) are inside a given range
  1561. Adds the current byte and, for each passed range, reads a new byte and
  1562. checks if it is inside the range. If a violation was detected, set up an
  1563. error message and return false. Otherwise, return true.
  1564. @return true if and only if no range violation was detected
  1565. */
  1566. bool next_byte_in_range(std::initializer_list<int> ranges)
  1567. {
  1568. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  1569. add(current);
  1570. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  1571. {
  1572. get();
  1573. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  1574. {
  1575. add(current);
  1576. }
  1577. else
  1578. {
  1579. error_message = "invalid string: ill-formed UTF-8 byte";
  1580. return false;
  1581. }
  1582. }
  1583. return true;
  1584. }
  1585. /*!
  1586. @brief scan a string literal
  1587. This function scans a string according to Sect. 7 of RFC 7159. While
  1588. scanning, bytes are escaped and copied into buffer yytext. Then the
  1589. function returns successfully, yytext is null-terminated and yylen
  1590. contains the number of bytes in the string.
  1591. @return token_type::value_string if string could be successfully scanned,
  1592. token_type::parse_error otherwise
  1593. @note In case of errors, variable error_message contains a textual
  1594. description.
  1595. */
  1596. token_type scan_string()
  1597. {
  1598. // reset yytext (ignore opening quote)
  1599. reset();
  1600. // we entered the function by reading an open quote
  1601. assert(current == '\"');
  1602. while (true)
  1603. {
  1604. // get next character
  1605. switch (get())
  1606. {
  1607. // end of file while parsing string
  1608. case std::char_traits<char>::eof():
  1609. {
  1610. error_message = "invalid string: missing closing quote";
  1611. return token_type::parse_error;
  1612. }
  1613. // closing quote
  1614. case '\"':
  1615. {
  1616. // terminate yytext
  1617. add('\0');
  1618. --yylen;
  1619. return token_type::value_string;
  1620. }
  1621. // escapes
  1622. case '\\':
  1623. {
  1624. switch (get())
  1625. {
  1626. // quotation mark
  1627. case '\"':
  1628. add('\"');
  1629. break;
  1630. // reverse solidus
  1631. case '\\':
  1632. add('\\');
  1633. break;
  1634. // solidus
  1635. case '/':
  1636. add('/');
  1637. break;
  1638. // backspace
  1639. case 'b':
  1640. add('\b');
  1641. break;
  1642. // form feed
  1643. case 'f':
  1644. add('\f');
  1645. break;
  1646. // line feed
  1647. case 'n':
  1648. add('\n');
  1649. break;
  1650. // carriage return
  1651. case 'r':
  1652. add('\r');
  1653. break;
  1654. // tab
  1655. case 't':
  1656. add('\t');
  1657. break;
  1658. // unicode escapes
  1659. case 'u':
  1660. {
  1661. int codepoint;
  1662. const int codepoint1 = get_codepoint();
  1663. if (JSON_UNLIKELY(codepoint1 == -1))
  1664. {
  1665. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1666. return token_type::parse_error;
  1667. }
  1668. // check if code point is a high surrogate
  1669. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  1670. {
  1671. // expect next \uxxxx entry
  1672. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  1673. {
  1674. const int codepoint2 = get_codepoint();
  1675. if (JSON_UNLIKELY(codepoint2 == -1))
  1676. {
  1677. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  1678. return token_type::parse_error;
  1679. }
  1680. // check if codepoint2 is a low surrogate
  1681. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  1682. {
  1683. codepoint =
  1684. // high surrogate occupies the most significant 22 bits
  1685. (codepoint1 << 10)
  1686. // low surrogate occupies the least significant 15 bits
  1687. + codepoint2
  1688. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  1689. // in the result so we have to subtract with:
  1690. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  1691. - 0x35FDC00;
  1692. }
  1693. else
  1694. {
  1695. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1696. return token_type::parse_error;
  1697. }
  1698. }
  1699. else
  1700. {
  1701. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  1702. return token_type::parse_error;
  1703. }
  1704. }
  1705. else
  1706. {
  1707. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  1708. {
  1709. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  1710. return token_type::parse_error;
  1711. }
  1712. // only work with first code point
  1713. codepoint = codepoint1;
  1714. }
  1715. // result of the above calculation yields a proper codepoint
  1716. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  1717. // translate code point to bytes
  1718. if (codepoint < 0x80)
  1719. {
  1720. // 1-byte characters: 0xxxxxxx (ASCII)
  1721. add(codepoint);
  1722. }
  1723. else if (codepoint <= 0x7ff)
  1724. {
  1725. // 2-byte characters: 110xxxxx 10xxxxxx
  1726. add(0xC0 | (codepoint >> 6));
  1727. add(0x80 | (codepoint & 0x3F));
  1728. }
  1729. else if (codepoint <= 0xffff)
  1730. {
  1731. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  1732. add(0xE0 | (codepoint >> 12));
  1733. add(0x80 | ((codepoint >> 6) & 0x3F));
  1734. add(0x80 | (codepoint & 0x3F));
  1735. }
  1736. else
  1737. {
  1738. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  1739. add(0xF0 | (codepoint >> 18));
  1740. add(0x80 | ((codepoint >> 12) & 0x3F));
  1741. add(0x80 | ((codepoint >> 6) & 0x3F));
  1742. add(0x80 | (codepoint & 0x3F));
  1743. }
  1744. break;
  1745. }
  1746. // other characters after escape
  1747. default:
  1748. error_message = "invalid string: forbidden character after backslash";
  1749. return token_type::parse_error;
  1750. }
  1751. break;
  1752. }
  1753. // invalid control characters
  1754. case 0x00:
  1755. case 0x01:
  1756. case 0x02:
  1757. case 0x03:
  1758. case 0x04:
  1759. case 0x05:
  1760. case 0x06:
  1761. case 0x07:
  1762. case 0x08:
  1763. case 0x09:
  1764. case 0x0a:
  1765. case 0x0b:
  1766. case 0x0c:
  1767. case 0x0d:
  1768. case 0x0e:
  1769. case 0x0f:
  1770. case 0x10:
  1771. case 0x11:
  1772. case 0x12:
  1773. case 0x13:
  1774. case 0x14:
  1775. case 0x15:
  1776. case 0x16:
  1777. case 0x17:
  1778. case 0x18:
  1779. case 0x19:
  1780. case 0x1a:
  1781. case 0x1b:
  1782. case 0x1c:
  1783. case 0x1d:
  1784. case 0x1e:
  1785. case 0x1f:
  1786. {
  1787. error_message = "invalid string: control character must be escaped";
  1788. return token_type::parse_error;
  1789. }
  1790. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  1791. case 0x20:
  1792. case 0x21:
  1793. case 0x23:
  1794. case 0x24:
  1795. case 0x25:
  1796. case 0x26:
  1797. case 0x27:
  1798. case 0x28:
  1799. case 0x29:
  1800. case 0x2a:
  1801. case 0x2b:
  1802. case 0x2c:
  1803. case 0x2d:
  1804. case 0x2e:
  1805. case 0x2f:
  1806. case 0x30:
  1807. case 0x31:
  1808. case 0x32:
  1809. case 0x33:
  1810. case 0x34:
  1811. case 0x35:
  1812. case 0x36:
  1813. case 0x37:
  1814. case 0x38:
  1815. case 0x39:
  1816. case 0x3a:
  1817. case 0x3b:
  1818. case 0x3c:
  1819. case 0x3d:
  1820. case 0x3e:
  1821. case 0x3f:
  1822. case 0x40:
  1823. case 0x41:
  1824. case 0x42:
  1825. case 0x43:
  1826. case 0x44:
  1827. case 0x45:
  1828. case 0x46:
  1829. case 0x47:
  1830. case 0x48:
  1831. case 0x49:
  1832. case 0x4a:
  1833. case 0x4b:
  1834. case 0x4c:
  1835. case 0x4d:
  1836. case 0x4e:
  1837. case 0x4f:
  1838. case 0x50:
  1839. case 0x51:
  1840. case 0x52:
  1841. case 0x53:
  1842. case 0x54:
  1843. case 0x55:
  1844. case 0x56:
  1845. case 0x57:
  1846. case 0x58:
  1847. case 0x59:
  1848. case 0x5a:
  1849. case 0x5b:
  1850. case 0x5d:
  1851. case 0x5e:
  1852. case 0x5f:
  1853. case 0x60:
  1854. case 0x61:
  1855. case 0x62:
  1856. case 0x63:
  1857. case 0x64:
  1858. case 0x65:
  1859. case 0x66:
  1860. case 0x67:
  1861. case 0x68:
  1862. case 0x69:
  1863. case 0x6a:
  1864. case 0x6b:
  1865. case 0x6c:
  1866. case 0x6d:
  1867. case 0x6e:
  1868. case 0x6f:
  1869. case 0x70:
  1870. case 0x71:
  1871. case 0x72:
  1872. case 0x73:
  1873. case 0x74:
  1874. case 0x75:
  1875. case 0x76:
  1876. case 0x77:
  1877. case 0x78:
  1878. case 0x79:
  1879. case 0x7a:
  1880. case 0x7b:
  1881. case 0x7c:
  1882. case 0x7d:
  1883. case 0x7e:
  1884. case 0x7f:
  1885. {
  1886. add(current);
  1887. break;
  1888. }
  1889. // U+0080..U+07FF: bytes C2..DF 80..BF
  1890. case 0xc2:
  1891. case 0xc3:
  1892. case 0xc4:
  1893. case 0xc5:
  1894. case 0xc6:
  1895. case 0xc7:
  1896. case 0xc8:
  1897. case 0xc9:
  1898. case 0xca:
  1899. case 0xcb:
  1900. case 0xcc:
  1901. case 0xcd:
  1902. case 0xce:
  1903. case 0xcf:
  1904. case 0xd0:
  1905. case 0xd1:
  1906. case 0xd2:
  1907. case 0xd3:
  1908. case 0xd4:
  1909. case 0xd5:
  1910. case 0xd6:
  1911. case 0xd7:
  1912. case 0xd8:
  1913. case 0xd9:
  1914. case 0xda:
  1915. case 0xdb:
  1916. case 0xdc:
  1917. case 0xdd:
  1918. case 0xde:
  1919. case 0xdf:
  1920. {
  1921. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  1922. {
  1923. return token_type::parse_error;
  1924. }
  1925. break;
  1926. }
  1927. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  1928. case 0xe0:
  1929. {
  1930. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  1931. {
  1932. return token_type::parse_error;
  1933. }
  1934. break;
  1935. }
  1936. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  1937. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  1938. case 0xe1:
  1939. case 0xe2:
  1940. case 0xe3:
  1941. case 0xe4:
  1942. case 0xe5:
  1943. case 0xe6:
  1944. case 0xe7:
  1945. case 0xe8:
  1946. case 0xe9:
  1947. case 0xea:
  1948. case 0xeb:
  1949. case 0xec:
  1950. case 0xee:
  1951. case 0xef:
  1952. {
  1953. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  1954. {
  1955. return token_type::parse_error;
  1956. }
  1957. break;
  1958. }
  1959. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  1960. case 0xed:
  1961. {
  1962. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  1963. {
  1964. return token_type::parse_error;
  1965. }
  1966. break;
  1967. }
  1968. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  1969. case 0xf0:
  1970. {
  1971. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  1972. {
  1973. return token_type::parse_error;
  1974. }
  1975. break;
  1976. }
  1977. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  1978. case 0xf1:
  1979. case 0xf2:
  1980. case 0xf3:
  1981. {
  1982. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  1983. {
  1984. return token_type::parse_error;
  1985. }
  1986. break;
  1987. }
  1988. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  1989. case 0xf4:
  1990. {
  1991. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  1992. {
  1993. return token_type::parse_error;
  1994. }
  1995. break;
  1996. }
  1997. // remaining bytes (80..C1 and F5..FF) are ill-formed
  1998. default:
  1999. {
  2000. error_message = "invalid string: ill-formed UTF-8 byte";
  2001. return token_type::parse_error;
  2002. }
  2003. }
  2004. }
  2005. }
  2006. static void strtof(float& f, const char* str, char** endptr) noexcept
  2007. {
  2008. f = std::strtof(str, endptr);
  2009. }
  2010. static void strtof(double& f, const char* str, char** endptr) noexcept
  2011. {
  2012. f = std::strtod(str, endptr);
  2013. }
  2014. static void strtof(long double& f, const char* str, char** endptr) noexcept
  2015. {
  2016. f = std::strtold(str, endptr);
  2017. }
  2018. /*!
  2019. @brief scan a number literal
  2020. This function scans a string according to Sect. 6 of RFC 7159.
  2021. The function is realized with a deterministic finite state machine derived
  2022. from the grammar described in RFC 7159. Starting in state "init", the
  2023. input is read and used to determined the next state. Only state "done"
  2024. accepts the number. State "error" is a trap state to model errors. In the
  2025. table below, "anything" means any character but the ones listed before.
  2026. state | 0 | 1-9 | e E | + | - | . | anything
  2027. ---------|----------|----------|----------|---------|---------|----------|-----------
  2028. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  2029. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  2030. zero | done | done | exponent | done | done | decimal1 | done
  2031. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  2032. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  2033. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  2034. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  2035. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  2036. any2 | any2 | any2 | done | done | done | done | done
  2037. The state machine is realized with one label per state (prefixed with
  2038. "scan_number_") and `goto` statements between them. The state machine
  2039. contains cycles, but any cycle can be left when EOF is read. Therefore,
  2040. the function is guaranteed to terminate.
  2041. During scanning, the read bytes are stored in yytext. This string is
  2042. then converted to a signed integer, an unsigned integer, or a
  2043. floating-point number.
  2044. @return token_type::value_unsigned, token_type::value_integer, or
  2045. token_type::value_float if number could be successfully scanned,
  2046. token_type::parse_error otherwise
  2047. @note The scanner is independent of the current locale. Internally, the
  2048. locale's decimal point is used instead of `.` to work with the
  2049. locale-dependent converters.
  2050. */
  2051. token_type scan_number()
  2052. {
  2053. // reset yytext to store the number's bytes
  2054. reset();
  2055. // the type of the parsed number; initially set to unsigned; will be
  2056. // changed if minus sign, decimal point or exponent is read
  2057. token_type number_type = token_type::value_unsigned;
  2058. // state (init): we just found out we need to scan a number
  2059. switch (current)
  2060. {
  2061. case '-':
  2062. {
  2063. add(current);
  2064. goto scan_number_minus;
  2065. }
  2066. case '0':
  2067. {
  2068. add(current);
  2069. goto scan_number_zero;
  2070. }
  2071. case '1':
  2072. case '2':
  2073. case '3':
  2074. case '4':
  2075. case '5':
  2076. case '6':
  2077. case '7':
  2078. case '8':
  2079. case '9':
  2080. {
  2081. add(current);
  2082. goto scan_number_any1;
  2083. }
  2084. default:
  2085. {
  2086. // all other characters are rejected outside scan_number()
  2087. assert(false); // LCOV_EXCL_LINE
  2088. }
  2089. }
  2090. scan_number_minus:
  2091. // state: we just parsed a leading minus sign
  2092. number_type = token_type::value_integer;
  2093. switch (get())
  2094. {
  2095. case '0':
  2096. {
  2097. add(current);
  2098. goto scan_number_zero;
  2099. }
  2100. case '1':
  2101. case '2':
  2102. case '3':
  2103. case '4':
  2104. case '5':
  2105. case '6':
  2106. case '7':
  2107. case '8':
  2108. case '9':
  2109. {
  2110. add(current);
  2111. goto scan_number_any1;
  2112. }
  2113. default:
  2114. {
  2115. error_message = "invalid number; expected digit after '-'";
  2116. return token_type::parse_error;
  2117. }
  2118. }
  2119. scan_number_zero:
  2120. // state: we just parse a zero (maybe with a leading minus sign)
  2121. switch (get())
  2122. {
  2123. case '.':
  2124. {
  2125. add(decimal_point_char);
  2126. goto scan_number_decimal1;
  2127. }
  2128. case 'e':
  2129. case 'E':
  2130. {
  2131. add(current);
  2132. goto scan_number_exponent;
  2133. }
  2134. default:
  2135. goto scan_number_done;
  2136. }
  2137. scan_number_any1:
  2138. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  2139. switch (get())
  2140. {
  2141. case '0':
  2142. case '1':
  2143. case '2':
  2144. case '3':
  2145. case '4':
  2146. case '5':
  2147. case '6':
  2148. case '7':
  2149. case '8':
  2150. case '9':
  2151. {
  2152. add(current);
  2153. goto scan_number_any1;
  2154. }
  2155. case '.':
  2156. {
  2157. add(decimal_point_char);
  2158. goto scan_number_decimal1;
  2159. }
  2160. case 'e':
  2161. case 'E':
  2162. {
  2163. add(current);
  2164. goto scan_number_exponent;
  2165. }
  2166. default:
  2167. goto scan_number_done;
  2168. }
  2169. scan_number_decimal1:
  2170. // state: we just parsed a decimal point
  2171. number_type = token_type::value_float;
  2172. switch (get())
  2173. {
  2174. case '0':
  2175. case '1':
  2176. case '2':
  2177. case '3':
  2178. case '4':
  2179. case '5':
  2180. case '6':
  2181. case '7':
  2182. case '8':
  2183. case '9':
  2184. {
  2185. add(current);
  2186. goto scan_number_decimal2;
  2187. }
  2188. default:
  2189. {
  2190. error_message = "invalid number; expected digit after '.'";
  2191. return token_type::parse_error;
  2192. }
  2193. }
  2194. scan_number_decimal2:
  2195. // we just parsed at least one number after a decimal point
  2196. switch (get())
  2197. {
  2198. case '0':
  2199. case '1':
  2200. case '2':
  2201. case '3':
  2202. case '4':
  2203. case '5':
  2204. case '6':
  2205. case '7':
  2206. case '8':
  2207. case '9':
  2208. {
  2209. add(current);
  2210. goto scan_number_decimal2;
  2211. }
  2212. case 'e':
  2213. case 'E':
  2214. {
  2215. add(current);
  2216. goto scan_number_exponent;
  2217. }
  2218. default:
  2219. goto scan_number_done;
  2220. }
  2221. scan_number_exponent:
  2222. // we just parsed an exponent
  2223. number_type = token_type::value_float;
  2224. switch (get())
  2225. {
  2226. case '+':
  2227. case '-':
  2228. {
  2229. add(current);
  2230. goto scan_number_sign;
  2231. }
  2232. case '0':
  2233. case '1':
  2234. case '2':
  2235. case '3':
  2236. case '4':
  2237. case '5':
  2238. case '6':
  2239. case '7':
  2240. case '8':
  2241. case '9':
  2242. {
  2243. add(current);
  2244. goto scan_number_any2;
  2245. }
  2246. default:
  2247. {
  2248. error_message =
  2249. "invalid number; expected '+', '-', or digit after exponent";
  2250. return token_type::parse_error;
  2251. }
  2252. }
  2253. scan_number_sign:
  2254. // we just parsed an exponent sign
  2255. switch (get())
  2256. {
  2257. case '0':
  2258. case '1':
  2259. case '2':
  2260. case '3':
  2261. case '4':
  2262. case '5':
  2263. case '6':
  2264. case '7':
  2265. case '8':
  2266. case '9':
  2267. {
  2268. add(current);
  2269. goto scan_number_any2;
  2270. }
  2271. default:
  2272. {
  2273. error_message = "invalid number; expected digit after exponent sign";
  2274. return token_type::parse_error;
  2275. }
  2276. }
  2277. scan_number_any2:
  2278. // we just parsed a number after the exponent or exponent sign
  2279. switch (get())
  2280. {
  2281. case '0':
  2282. case '1':
  2283. case '2':
  2284. case '3':
  2285. case '4':
  2286. case '5':
  2287. case '6':
  2288. case '7':
  2289. case '8':
  2290. case '9':
  2291. {
  2292. add(current);
  2293. goto scan_number_any2;
  2294. }
  2295. default:
  2296. goto scan_number_done;
  2297. }
  2298. scan_number_done:
  2299. // unget the character after the number (we only read it to know that
  2300. // we are done scanning a number)
  2301. --chars_read;
  2302. next_unget = true;
  2303. // terminate token
  2304. add('\0');
  2305. --yylen;
  2306. char* endptr = nullptr;
  2307. errno = 0;
  2308. // try to parse integers first and fall back to floats
  2309. if (number_type == token_type::value_unsigned)
  2310. {
  2311. const auto x = std::strtoull(yytext.data(), &endptr, 10);
  2312. // we checked the number format before
  2313. assert(endptr == yytext.data() + yylen);
  2314. if (errno == 0)
  2315. {
  2316. value_unsigned = static_cast<number_unsigned_t>(x);
  2317. if (value_unsigned == x)
  2318. {
  2319. return token_type::value_unsigned;
  2320. }
  2321. }
  2322. }
  2323. else if (number_type == token_type::value_integer)
  2324. {
  2325. const auto x = std::strtoll(yytext.data(), &endptr, 10);
  2326. // we checked the number format before
  2327. assert(endptr == yytext.data() + yylen);
  2328. if (errno == 0)
  2329. {
  2330. value_integer = static_cast<number_integer_t>(x);
  2331. if (value_integer == x)
  2332. {
  2333. return token_type::value_integer;
  2334. }
  2335. }
  2336. }
  2337. // this code is reached if we parse a floating-point number or if an
  2338. // integer conversion above failed
  2339. strtof(value_float, yytext.data(), &endptr);
  2340. // we checked the number format before
  2341. assert(endptr == yytext.data() + yylen);
  2342. return token_type::value_float;
  2343. }
  2344. /*!
  2345. @param[in] literal_text the literal text to expect
  2346. @param[in] length the length of the passed literal text
  2347. @param[in] return_type the token type to return on success
  2348. */
  2349. token_type scan_literal(const char* literal_text, const std::size_t length,
  2350. token_type return_type)
  2351. {
  2352. assert(current == literal_text[0]);
  2353. for (std::size_t i = 1; i < length; ++i)
  2354. {
  2355. if (JSON_UNLIKELY(get() != literal_text[i]))
  2356. {
  2357. error_message = "invalid literal";
  2358. return token_type::parse_error;
  2359. }
  2360. }
  2361. return return_type;
  2362. }
  2363. /////////////////////
  2364. // input management
  2365. /////////////////////
  2366. /// reset yytext
  2367. void reset() noexcept
  2368. {
  2369. yylen = 0;
  2370. start_pos = chars_read - 1;
  2371. }
  2372. /// get a character from the input
  2373. int get()
  2374. {
  2375. ++chars_read;
  2376. return next_unget ? (next_unget = false, current)
  2377. : (current = ia->get_character());
  2378. }
  2379. /// add a character to yytext
  2380. void add(int c)
  2381. {
  2382. // resize yytext if necessary; this condition is deemed unlikely,
  2383. // because we start with a 1024-byte buffer
  2384. if (JSON_UNLIKELY((yylen + 1 > yytext.capacity())))
  2385. {
  2386. yytext.resize(2 * yytext.capacity(), '\0');
  2387. }
  2388. assert(yylen < yytext.size());
  2389. yytext[yylen++] = static_cast<char>(c);
  2390. }
  2391. public:
  2392. /////////////////////
  2393. // value getters
  2394. /////////////////////
  2395. /// return integer value
  2396. constexpr number_integer_t get_number_integer() const noexcept
  2397. {
  2398. return value_integer;
  2399. }
  2400. /// return unsigned integer value
  2401. constexpr number_unsigned_t get_number_unsigned() const noexcept
  2402. {
  2403. return value_unsigned;
  2404. }
  2405. /// return floating-point value
  2406. constexpr number_float_t get_number_float() const noexcept
  2407. {
  2408. return value_float;
  2409. }
  2410. /// return string value
  2411. const std::string get_string()
  2412. {
  2413. // yytext cannot be returned as char*, because it may contain a null
  2414. // byte (parsed as "\u0000")
  2415. return std::string(yytext.data(), yylen);
  2416. }
  2417. /////////////////////
  2418. // diagnostics
  2419. /////////////////////
  2420. /// return position of last read token
  2421. constexpr std::size_t get_position() const noexcept
  2422. {
  2423. return chars_read;
  2424. }
  2425. /// return the last read token (for errors only)
  2426. std::string get_token_string() const
  2427. {
  2428. // get the raw byte sequence of the last token
  2429. std::string s = ia->read(start_pos, chars_read - start_pos);
  2430. // escape control characters
  2431. std::string result;
  2432. for (auto c : s)
  2433. {
  2434. if (c == '\0' or c == std::char_traits<char>::eof())
  2435. {
  2436. // ignore EOF
  2437. continue;
  2438. }
  2439. else if ('\x00' <= c and c <= '\x1f')
  2440. {
  2441. // escape control characters
  2442. std::stringstream ss;
  2443. ss << "<U+" << std::setw(4) << std::uppercase << std::setfill('0')
  2444. << std::hex << static_cast<int>(c) << ">";
  2445. result += ss.str();
  2446. }
  2447. else
  2448. {
  2449. // add character as is
  2450. result.push_back(c);
  2451. }
  2452. }
  2453. return result;
  2454. }
  2455. /// return syntax error message
  2456. constexpr const char* get_error_message() const noexcept
  2457. {
  2458. return error_message;
  2459. }
  2460. /////////////////////
  2461. // actual scanner
  2462. /////////////////////
  2463. token_type scan()
  2464. {
  2465. // read next character and ignore whitespace
  2466. do
  2467. {
  2468. get();
  2469. }
  2470. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  2471. switch (current)
  2472. {
  2473. // structural characters
  2474. case '[':
  2475. return token_type::begin_array;
  2476. case ']':
  2477. return token_type::end_array;
  2478. case '{':
  2479. return token_type::begin_object;
  2480. case '}':
  2481. return token_type::end_object;
  2482. case ':':
  2483. return token_type::name_separator;
  2484. case ',':
  2485. return token_type::value_separator;
  2486. // literals
  2487. case 't':
  2488. return scan_literal("true", 4, token_type::literal_true);
  2489. case 'f':
  2490. return scan_literal("false", 5, token_type::literal_false);
  2491. case 'n':
  2492. return scan_literal("null", 4, token_type::literal_null);
  2493. // string
  2494. case '\"':
  2495. return scan_string();
  2496. // number
  2497. case '-':
  2498. case '0':
  2499. case '1':
  2500. case '2':
  2501. case '3':
  2502. case '4':
  2503. case '5':
  2504. case '6':
  2505. case '7':
  2506. case '8':
  2507. case '9':
  2508. return scan_number();
  2509. // end of input (the null byte is needed when parsing from
  2510. // string literals)
  2511. case '\0':
  2512. case std::char_traits<char>::eof():
  2513. return token_type::end_of_input;
  2514. // error
  2515. default:
  2516. error_message = "invalid literal";
  2517. return token_type::parse_error;
  2518. }
  2519. }
  2520. private:
  2521. /// input adapter
  2522. detail::input_adapter_t ia = nullptr;
  2523. /// the current character
  2524. int current = std::char_traits<char>::eof();
  2525. /// whether get() should return the last character again
  2526. bool next_unget = false;
  2527. /// the number of characters read
  2528. std::size_t chars_read = 0;
  2529. /// the start position of the current token
  2530. std::size_t start_pos = 0;
  2531. /// buffer for variable-length tokens (numbers, strings)
  2532. std::vector<char> yytext = std::vector<char>(1024, '\0');
  2533. /// current index in yytext
  2534. std::size_t yylen = 0;
  2535. /// a description of occurred lexer errors
  2536. const char* error_message = "";
  2537. // number values
  2538. number_integer_t value_integer = 0;
  2539. number_unsigned_t value_unsigned = 0;
  2540. number_float_t value_float = 0;
  2541. /// the decimal point
  2542. const char decimal_point_char = '.';
  2543. };
  2544. /*!
  2545. @brief syntax analysis
  2546. This class implements a recursive decent parser.
  2547. */
  2548. template<typename BasicJsonType>
  2549. class parser
  2550. {
  2551. using number_integer_t = typename BasicJsonType::number_integer_t;
  2552. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  2553. using number_float_t = typename BasicJsonType::number_float_t;
  2554. using lexer_t = lexer<BasicJsonType>;
  2555. using token_type = typename lexer_t::token_type;
  2556. public:
  2557. enum class parse_event_t : uint8_t
  2558. {
  2559. /// the parser read `{` and started to process a JSON object
  2560. object_start,
  2561. /// the parser read `}` and finished processing a JSON object
  2562. object_end,
  2563. /// the parser read `[` and started to process a JSON array
  2564. array_start,
  2565. /// the parser read `]` and finished processing a JSON array
  2566. array_end,
  2567. /// the parser read a key of a value in an object
  2568. key,
  2569. /// the parser finished reading a JSON value
  2570. value
  2571. };
  2572. using parser_callback_t =
  2573. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  2574. /// a parser reading from an input adapter
  2575. explicit parser(detail::input_adapter_t adapter,
  2576. const parser_callback_t cb = nullptr,
  2577. const bool allow_exceptions_ = true)
  2578. : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)
  2579. {}
  2580. /*!
  2581. @brief public parser interface
  2582. @param[in] strict whether to expect the last token to be EOF
  2583. @param[in,out] result parsed JSON value
  2584. @throw parse_error.101 in case of an unexpected token
  2585. @throw parse_error.102 if to_unicode fails or surrogate error
  2586. @throw parse_error.103 if to_unicode fails
  2587. */
  2588. void parse(const bool strict, BasicJsonType& result)
  2589. {
  2590. // read first token
  2591. get_token();
  2592. parse_internal(true, result);
  2593. result.assert_invariant();
  2594. // in strict mode, input must be completely read
  2595. if (strict)
  2596. {
  2597. get_token();
  2598. expect(token_type::end_of_input);
  2599. }
  2600. // in case of an error, return discarded value
  2601. if (errored)
  2602. {
  2603. result = value_t::discarded;
  2604. return;
  2605. }
  2606. // set top-level value to null if it was discarded by the callback
  2607. // function
  2608. if (result.is_discarded())
  2609. {
  2610. result = nullptr;
  2611. }
  2612. }
  2613. /*!
  2614. @brief public accept interface
  2615. @param[in] strict whether to expect the last token to be EOF
  2616. @return whether the input is a proper JSON text
  2617. */
  2618. bool accept(const bool strict = true)
  2619. {
  2620. // read first token
  2621. get_token();
  2622. if (not accept_internal())
  2623. {
  2624. return false;
  2625. }
  2626. // strict => last token must be EOF
  2627. return not strict or (get_token() == token_type::end_of_input);
  2628. }
  2629. private:
  2630. /*!
  2631. @brief the actual parser
  2632. @throw parse_error.101 in case of an unexpected token
  2633. @throw parse_error.102 if to_unicode fails or surrogate error
  2634. @throw parse_error.103 if to_unicode fails
  2635. */
  2636. void parse_internal(bool keep, BasicJsonType& result)
  2637. {
  2638. // never parse after a parse error was detected
  2639. assert(not errored);
  2640. // start with a discarded value
  2641. if (not result.is_discarded())
  2642. {
  2643. result.m_value.destroy(result.m_type);
  2644. result.m_type = value_t::discarded;
  2645. }
  2646. switch (last_token)
  2647. {
  2648. case token_type::begin_object:
  2649. {
  2650. if (keep and (not callback or ((keep = callback(depth++, parse_event_t::object_start, result)))))
  2651. {
  2652. // explicitly set result to object to cope with {}
  2653. result.m_type = value_t::object;
  2654. result.m_value = value_t::object;
  2655. }
  2656. // read next token
  2657. get_token();
  2658. // closing } -> we are done
  2659. if (last_token == token_type::end_object)
  2660. {
  2661. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2662. {
  2663. result.m_value.destroy(result.m_type);
  2664. result.m_type = value_t::discarded;
  2665. }
  2666. break;
  2667. }
  2668. // parse values
  2669. std::string key;
  2670. BasicJsonType value;
  2671. while (true)
  2672. {
  2673. // store key
  2674. if (not expect(token_type::value_string))
  2675. {
  2676. return;
  2677. }
  2678. key = m_lexer.get_string();
  2679. bool keep_tag = false;
  2680. if (keep)
  2681. {
  2682. if (callback)
  2683. {
  2684. BasicJsonType k(key);
  2685. keep_tag = callback(depth, parse_event_t::key, k);
  2686. }
  2687. else
  2688. {
  2689. keep_tag = true;
  2690. }
  2691. }
  2692. // parse separator (:)
  2693. get_token();
  2694. if (not expect(token_type::name_separator))
  2695. {
  2696. return;
  2697. }
  2698. // parse and add value
  2699. get_token();
  2700. value.m_value.destroy(value.m_type);
  2701. value.m_type = value_t::discarded;
  2702. parse_internal(keep, value);
  2703. if (JSON_UNLIKELY(errored))
  2704. {
  2705. return;
  2706. }
  2707. if (keep and keep_tag and not value.is_discarded())
  2708. {
  2709. result.m_value.object->emplace(std::move(key), std::move(value));
  2710. }
  2711. // comma -> next value
  2712. get_token();
  2713. if (last_token == token_type::value_separator)
  2714. {
  2715. get_token();
  2716. continue;
  2717. }
  2718. // closing }
  2719. if (not expect(token_type::end_object))
  2720. {
  2721. return;
  2722. }
  2723. break;
  2724. }
  2725. if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
  2726. {
  2727. result.m_value.destroy(result.m_type);
  2728. result.m_type = value_t::discarded;
  2729. }
  2730. break;
  2731. }
  2732. case token_type::begin_array:
  2733. {
  2734. if (keep and (not callback or ((keep = callback(depth++, parse_event_t::array_start, result)))))
  2735. {
  2736. // explicitly set result to object to cope with []
  2737. result.m_type = value_t::array;
  2738. result.m_value = value_t::array;
  2739. }
  2740. // read next token
  2741. get_token();
  2742. // closing ] -> we are done
  2743. if (last_token == token_type::end_array)
  2744. {
  2745. if (callback and not callback(--depth, parse_event_t::array_end, result))
  2746. {
  2747. result.m_value.destroy(result.m_type);
  2748. result.m_type = value_t::discarded;
  2749. }
  2750. break;
  2751. }
  2752. // parse values
  2753. BasicJsonType value;
  2754. while (true)
  2755. {
  2756. // parse value
  2757. value.m_value.destroy(value.m_type);
  2758. value.m_type = value_t::discarded;
  2759. parse_internal(keep, value);
  2760. if (JSON_UNLIKELY(errored))
  2761. {
  2762. return;
  2763. }
  2764. if (keep and not value.is_discarded())
  2765. {
  2766. result.m_value.array->push_back(std::move(value));
  2767. }
  2768. // comma -> next value
  2769. get_token();
  2770. if (last_token == token_type::value_separator)
  2771. {
  2772. get_token();
  2773. continue;
  2774. }
  2775. // closing ]
  2776. if (not expect(token_type::end_array))
  2777. {
  2778. return;
  2779. }
  2780. break;
  2781. }
  2782. if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
  2783. {
  2784. result.m_value.destroy(result.m_type);
  2785. result.m_type = value_t::discarded;
  2786. }
  2787. break;
  2788. }
  2789. case token_type::literal_null:
  2790. {
  2791. result.m_type = value_t::null;
  2792. break;
  2793. }
  2794. case token_type::value_string:
  2795. {
  2796. result.m_type = value_t::string;
  2797. result.m_value = m_lexer.get_string();
  2798. break;
  2799. }
  2800. case token_type::literal_true:
  2801. {
  2802. result.m_type = value_t::boolean;
  2803. result.m_value = true;
  2804. break;
  2805. }
  2806. case token_type::literal_false:
  2807. {
  2808. result.m_type = value_t::boolean;
  2809. result.m_value = false;
  2810. break;
  2811. }
  2812. case token_type::value_unsigned:
  2813. {
  2814. result.m_type = value_t::number_unsigned;
  2815. result.m_value = m_lexer.get_number_unsigned();
  2816. break;
  2817. }
  2818. case token_type::value_integer:
  2819. {
  2820. result.m_type = value_t::number_integer;
  2821. result.m_value = m_lexer.get_number_integer();
  2822. break;
  2823. }
  2824. case token_type::value_float:
  2825. {
  2826. result.m_type = value_t::number_float;
  2827. result.m_value = m_lexer.get_number_float();
  2828. // throw in case of infinity or NAN
  2829. if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))
  2830. {
  2831. if (allow_exceptions)
  2832. {
  2833. JSON_THROW(out_of_range::create(406, "number overflow parsing '" +
  2834. m_lexer.get_token_string() + "'"));
  2835. }
  2836. expect(token_type::uninitialized);
  2837. }
  2838. break;
  2839. }
  2840. case token_type::parse_error:
  2841. {
  2842. // using "uninitialized" to avoid "expected" message
  2843. if (not expect(token_type::uninitialized))
  2844. {
  2845. return;
  2846. }
  2847. break; // LCOV_EXCL_LINE
  2848. }
  2849. default:
  2850. {
  2851. // the last token was unexpected; we expected a value
  2852. if (not expect(token_type::literal_or_value))
  2853. {
  2854. return;
  2855. }
  2856. break; // LCOV_EXCL_LINE
  2857. }
  2858. }
  2859. if (keep and callback and not callback(depth, parse_event_t::value, result))
  2860. {
  2861. result.m_type = value_t::discarded;
  2862. }
  2863. }
  2864. /*!
  2865. @brief the acutal acceptor
  2866. @invariant 1. The last token is not yet processed. Therefore, the caller
  2867. of this function must make sure a token has been read.
  2868. 2. When this function returns, the last token is processed.
  2869. That is, the last read character was already considered.
  2870. This invariant makes sure that no token needs to be "unput".
  2871. */
  2872. bool accept_internal()
  2873. {
  2874. switch (last_token)
  2875. {
  2876. case token_type::begin_object:
  2877. {
  2878. // read next token
  2879. get_token();
  2880. // closing } -> we are done
  2881. if (last_token == token_type::end_object)
  2882. {
  2883. return true;
  2884. }
  2885. // parse values
  2886. while (true)
  2887. {
  2888. // parse key
  2889. if (last_token != token_type::value_string)
  2890. {
  2891. return false;
  2892. }
  2893. // parse separator (:)
  2894. get_token();
  2895. if (last_token != token_type::name_separator)
  2896. {
  2897. return false;
  2898. }
  2899. // parse value
  2900. get_token();
  2901. if (not accept_internal())
  2902. {
  2903. return false;
  2904. }
  2905. // comma -> next value
  2906. get_token();
  2907. if (last_token == token_type::value_separator)
  2908. {
  2909. get_token();
  2910. continue;
  2911. }
  2912. // closing }
  2913. return (last_token == token_type::end_object);
  2914. }
  2915. }
  2916. case token_type::begin_array:
  2917. {
  2918. // read next token
  2919. get_token();
  2920. // closing ] -> we are done
  2921. if (last_token == token_type::end_array)
  2922. {
  2923. return true;
  2924. }
  2925. // parse values
  2926. while (true)
  2927. {
  2928. // parse value
  2929. if (not accept_internal())
  2930. {
  2931. return false;
  2932. }
  2933. // comma -> next value
  2934. get_token();
  2935. if (last_token == token_type::value_separator)
  2936. {
  2937. get_token();
  2938. continue;
  2939. }
  2940. // closing ]
  2941. return (last_token == token_type::end_array);
  2942. }
  2943. }
  2944. case token_type::value_float:
  2945. {
  2946. // reject infinity or NAN
  2947. return std::isfinite(m_lexer.get_number_float());
  2948. }
  2949. case token_type::literal_false:
  2950. case token_type::literal_null:
  2951. case token_type::literal_true:
  2952. case token_type::value_integer:
  2953. case token_type::value_string:
  2954. case token_type::value_unsigned:
  2955. return true;
  2956. default: // the last token was unexpected
  2957. return false;
  2958. }
  2959. }
  2960. /// get next token from lexer
  2961. token_type get_token()
  2962. {
  2963. return (last_token = m_lexer.scan());
  2964. }
  2965. /*!
  2966. @throw parse_error.101 if expected token did not occur
  2967. */
  2968. bool expect(token_type t)
  2969. {
  2970. if (JSON_UNLIKELY(t != last_token))
  2971. {
  2972. errored = true;
  2973. expected = t;
  2974. if (allow_exceptions)
  2975. {
  2976. throw_exception();
  2977. }
  2978. else
  2979. {
  2980. return false;
  2981. }
  2982. }
  2983. return true;
  2984. }
  2985. [[noreturn]] void throw_exception() const
  2986. {
  2987. std::string error_msg = "syntax error - ";
  2988. if (last_token == token_type::parse_error)
  2989. {
  2990. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  2991. m_lexer.get_token_string() + "'";
  2992. }
  2993. else
  2994. {
  2995. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  2996. }
  2997. if (expected != token_type::uninitialized)
  2998. {
  2999. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  3000. }
  3001. JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));
  3002. }
  3003. private:
  3004. /// current level of recursion
  3005. int depth = 0;
  3006. /// callback function
  3007. const parser_callback_t callback = nullptr;
  3008. /// the type of the last read token
  3009. token_type last_token = token_type::uninitialized;
  3010. /// the lexer
  3011. lexer_t m_lexer;
  3012. /// whether a syntax error occurred
  3013. bool errored = false;
  3014. /// possible reason for the syntax error
  3015. token_type expected = token_type::uninitialized;
  3016. /// whether to throw exceptions in case of errors
  3017. const bool allow_exceptions = true;
  3018. };
  3019. ///////////////
  3020. // iterators //
  3021. ///////////////
  3022. /*!
  3023. @brief an iterator for primitive JSON types
  3024. This class models an iterator for primitive JSON types (boolean, number,
  3025. string). It's only purpose is to allow the iterator/const_iterator classes
  3026. to "iterate" over primitive values. Internally, the iterator is modeled by
  3027. a `difference_type` variable. Value begin_value (`0`) models the begin,
  3028. end_value (`1`) models past the end.
  3029. */
  3030. class primitive_iterator_t
  3031. {
  3032. public:
  3033. using difference_type = std::ptrdiff_t;
  3034. constexpr difference_type get_value() const noexcept
  3035. {
  3036. return m_it;
  3037. }
  3038. /// set iterator to a defined beginning
  3039. void set_begin() noexcept
  3040. {
  3041. m_it = begin_value;
  3042. }
  3043. /// set iterator to a defined past the end
  3044. void set_end() noexcept
  3045. {
  3046. m_it = end_value;
  3047. }
  3048. /// return whether the iterator can be dereferenced
  3049. constexpr bool is_begin() const noexcept
  3050. {
  3051. return m_it == begin_value;
  3052. }
  3053. /// return whether the iterator is at end
  3054. constexpr bool is_end() const noexcept
  3055. {
  3056. return m_it == end_value;
  3057. }
  3058. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3059. {
  3060. return lhs.m_it == rhs.m_it;
  3061. }
  3062. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3063. {
  3064. return lhs.m_it < rhs.m_it;
  3065. }
  3066. primitive_iterator_t operator+(difference_type i)
  3067. {
  3068. auto result = *this;
  3069. result += i;
  3070. return result;
  3071. }
  3072. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  3073. {
  3074. return lhs.m_it - rhs.m_it;
  3075. }
  3076. friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
  3077. {
  3078. return os << it.m_it;
  3079. }
  3080. primitive_iterator_t& operator++()
  3081. {
  3082. ++m_it;
  3083. return *this;
  3084. }
  3085. primitive_iterator_t operator++(int)
  3086. {
  3087. auto result = *this;
  3088. m_it++;
  3089. return result;
  3090. }
  3091. primitive_iterator_t& operator--()
  3092. {
  3093. --m_it;
  3094. return *this;
  3095. }
  3096. primitive_iterator_t operator--(int)
  3097. {
  3098. auto result = *this;
  3099. m_it--;
  3100. return result;
  3101. }
  3102. primitive_iterator_t& operator+=(difference_type n)
  3103. {
  3104. m_it += n;
  3105. return *this;
  3106. }
  3107. primitive_iterator_t& operator-=(difference_type n)
  3108. {
  3109. m_it -= n;
  3110. return *this;
  3111. }
  3112. private:
  3113. static constexpr difference_type begin_value = 0;
  3114. static constexpr difference_type end_value = begin_value + 1;
  3115. /// iterator as signed integer type
  3116. difference_type m_it = std::numeric_limits<std::ptrdiff_t>::min();
  3117. };
  3118. /*!
  3119. @brief an iterator value
  3120. @note This structure could easily be a union, but MSVC currently does not allow
  3121. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  3122. */
  3123. template<typename BasicJsonType> struct internal_iterator
  3124. {
  3125. /// iterator for JSON objects
  3126. typename BasicJsonType::object_t::iterator object_iterator {};
  3127. /// iterator for JSON arrays
  3128. typename BasicJsonType::array_t::iterator array_iterator {};
  3129. /// generic iterator for all other types
  3130. primitive_iterator_t primitive_iterator {};
  3131. };
  3132. template<typename IteratorType> class iteration_proxy;
  3133. /*!
  3134. @brief a template for a random access iterator for the @ref basic_json class
  3135. This class implements a both iterators (iterator and const_iterator) for the
  3136. @ref basic_json class.
  3137. @note An iterator is called *initialized* when a pointer to a JSON value has
  3138. been set (e.g., by a constructor or a copy assignment). If the iterator is
  3139. default-constructed, it is *uninitialized* and most methods are undefined.
  3140. **The library uses assertions to detect calls on uninitialized iterators.**
  3141. @requirement The class satisfies the following concept requirements:
  3142. -
  3143. [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  3144. The iterator that can be moved to point (forward and backward) to any
  3145. element in constant time.
  3146. @since version 1.0.0, simplified in version 2.0.9
  3147. */
  3148. template<typename BasicJsonType>
  3149. class iter_impl : public std::iterator<std::random_access_iterator_tag, BasicJsonType>
  3150. {
  3151. /// allow basic_json to access private members
  3152. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  3153. friend BasicJsonType;
  3154. friend iteration_proxy<iter_impl>;
  3155. using object_t = typename BasicJsonType::object_t;
  3156. using array_t = typename BasicJsonType::array_t;
  3157. // make sure BasicJsonType is basic_json or const basic_json
  3158. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  3159. "iter_impl only accepts (const) basic_json");
  3160. public:
  3161. /// the type of the values when the iterator is dereferenced
  3162. using value_type = typename BasicJsonType::value_type;
  3163. /// a type to represent differences between iterators
  3164. using difference_type = typename BasicJsonType::difference_type;
  3165. /// defines a pointer to the type iterated over (value_type)
  3166. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  3167. typename BasicJsonType::const_pointer,
  3168. typename BasicJsonType::pointer>::type;
  3169. /// defines a reference to the type iterated over (value_type)
  3170. using reference =
  3171. typename std::conditional<std::is_const<BasicJsonType>::value,
  3172. typename BasicJsonType::const_reference,
  3173. typename BasicJsonType::reference>::type;
  3174. /// the category of the iterator
  3175. using iterator_category = std::bidirectional_iterator_tag;
  3176. /// default constructor
  3177. iter_impl() = default;
  3178. /*!
  3179. @brief constructor for a given JSON instance
  3180. @param[in] object pointer to a JSON object for this iterator
  3181. @pre object != nullptr
  3182. @post The iterator is initialized; i.e. `m_object != nullptr`.
  3183. */
  3184. explicit iter_impl(pointer object) noexcept : m_object(object)
  3185. {
  3186. assert(m_object != nullptr);
  3187. switch (m_object->m_type)
  3188. {
  3189. case value_t::object:
  3190. {
  3191. m_it.object_iterator = typename object_t::iterator();
  3192. break;
  3193. }
  3194. case value_t::array:
  3195. {
  3196. m_it.array_iterator = typename array_t::iterator();
  3197. break;
  3198. }
  3199. default:
  3200. {
  3201. m_it.primitive_iterator = primitive_iterator_t();
  3202. break;
  3203. }
  3204. }
  3205. }
  3206. /*!
  3207. @note The conventional copy constructor and copy assignment are implicitly
  3208. defined. Combined with the following converting constructor and
  3209. assignment, they support: (1) copy from iterator to iterator, (2)
  3210. copy from const iterator to const iterator, and (3) conversion from
  3211. iterator to const iterator. However conversion from const iterator
  3212. to iterator is not defined.
  3213. */
  3214. /*!
  3215. @brief converting constructor
  3216. @param[in] other non-const iterator to copy from
  3217. @note It is not checked whether @a other is initialized.
  3218. */
  3219. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3220. : m_object(other.m_object), m_it(other.m_it) {}
  3221. /*!
  3222. @brief converting assignment
  3223. @param[in,out] other non-const iterator to copy from
  3224. @return const/non-const iterator
  3225. @note It is not checked whether @a other is initialized.
  3226. */
  3227. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  3228. {
  3229. m_object = other.m_object;
  3230. m_it = other.m_it;
  3231. return *this;
  3232. }
  3233. private:
  3234. /*!
  3235. @brief set the iterator to the first value
  3236. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3237. */
  3238. void set_begin() noexcept
  3239. {
  3240. assert(m_object != nullptr);
  3241. switch (m_object->m_type)
  3242. {
  3243. case value_t::object:
  3244. {
  3245. m_it.object_iterator = m_object->m_value.object->begin();
  3246. break;
  3247. }
  3248. case value_t::array:
  3249. {
  3250. m_it.array_iterator = m_object->m_value.array->begin();
  3251. break;
  3252. }
  3253. case value_t::null:
  3254. {
  3255. // set to end so begin()==end() is true: null is empty
  3256. m_it.primitive_iterator.set_end();
  3257. break;
  3258. }
  3259. default:
  3260. {
  3261. m_it.primitive_iterator.set_begin();
  3262. break;
  3263. }
  3264. }
  3265. }
  3266. /*!
  3267. @brief set the iterator past the last value
  3268. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3269. */
  3270. void set_end() noexcept
  3271. {
  3272. assert(m_object != nullptr);
  3273. switch (m_object->m_type)
  3274. {
  3275. case value_t::object:
  3276. {
  3277. m_it.object_iterator = m_object->m_value.object->end();
  3278. break;
  3279. }
  3280. case value_t::array:
  3281. {
  3282. m_it.array_iterator = m_object->m_value.array->end();
  3283. break;
  3284. }
  3285. default:
  3286. {
  3287. m_it.primitive_iterator.set_end();
  3288. break;
  3289. }
  3290. }
  3291. }
  3292. public:
  3293. /*!
  3294. @brief return a reference to the value pointed to by the iterator
  3295. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3296. */
  3297. reference operator*() const
  3298. {
  3299. assert(m_object != nullptr);
  3300. switch (m_object->m_type)
  3301. {
  3302. case value_t::object:
  3303. {
  3304. assert(m_it.object_iterator != m_object->m_value.object->end());
  3305. return m_it.object_iterator->second;
  3306. }
  3307. case value_t::array:
  3308. {
  3309. assert(m_it.array_iterator != m_object->m_value.array->end());
  3310. return *m_it.array_iterator;
  3311. }
  3312. case value_t::null:
  3313. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3314. default:
  3315. {
  3316. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3317. {
  3318. return *m_object;
  3319. }
  3320. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3321. }
  3322. }
  3323. }
  3324. /*!
  3325. @brief dereference the iterator
  3326. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3327. */
  3328. pointer operator->() const
  3329. {
  3330. assert(m_object != nullptr);
  3331. switch (m_object->m_type)
  3332. {
  3333. case value_t::object:
  3334. {
  3335. assert(m_it.object_iterator != m_object->m_value.object->end());
  3336. return &(m_it.object_iterator->second);
  3337. }
  3338. case value_t::array:
  3339. {
  3340. assert(m_it.array_iterator != m_object->m_value.array->end());
  3341. return &*m_it.array_iterator;
  3342. }
  3343. default:
  3344. {
  3345. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  3346. {
  3347. return m_object;
  3348. }
  3349. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3350. }
  3351. }
  3352. }
  3353. /*!
  3354. @brief post-increment (it++)
  3355. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3356. */
  3357. iter_impl operator++(int)
  3358. {
  3359. auto result = *this;
  3360. ++(*this);
  3361. return result;
  3362. }
  3363. /*!
  3364. @brief pre-increment (++it)
  3365. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3366. */
  3367. iter_impl& operator++()
  3368. {
  3369. assert(m_object != nullptr);
  3370. switch (m_object->m_type)
  3371. {
  3372. case value_t::object:
  3373. {
  3374. std::advance(m_it.object_iterator, 1);
  3375. break;
  3376. }
  3377. case value_t::array:
  3378. {
  3379. std::advance(m_it.array_iterator, 1);
  3380. break;
  3381. }
  3382. default:
  3383. {
  3384. ++m_it.primitive_iterator;
  3385. break;
  3386. }
  3387. }
  3388. return *this;
  3389. }
  3390. /*!
  3391. @brief post-decrement (it--)
  3392. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3393. */
  3394. iter_impl operator--(int)
  3395. {
  3396. auto result = *this;
  3397. --(*this);
  3398. return result;
  3399. }
  3400. /*!
  3401. @brief pre-decrement (--it)
  3402. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3403. */
  3404. iter_impl& operator--()
  3405. {
  3406. assert(m_object != nullptr);
  3407. switch (m_object->m_type)
  3408. {
  3409. case value_t::object:
  3410. {
  3411. std::advance(m_it.object_iterator, -1);
  3412. break;
  3413. }
  3414. case value_t::array:
  3415. {
  3416. std::advance(m_it.array_iterator, -1);
  3417. break;
  3418. }
  3419. default:
  3420. {
  3421. --m_it.primitive_iterator;
  3422. break;
  3423. }
  3424. }
  3425. return *this;
  3426. }
  3427. /*!
  3428. @brief comparison: equal
  3429. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3430. */
  3431. bool operator==(const iter_impl& other) const
  3432. {
  3433. // if objects are not the same, the comparison is undefined
  3434. if (JSON_UNLIKELY(m_object != other.m_object))
  3435. {
  3436. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3437. }
  3438. assert(m_object != nullptr);
  3439. switch (m_object->m_type)
  3440. {
  3441. case value_t::object:
  3442. return (m_it.object_iterator == other.m_it.object_iterator);
  3443. case value_t::array:
  3444. return (m_it.array_iterator == other.m_it.array_iterator);
  3445. default:
  3446. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  3447. }
  3448. }
  3449. /*!
  3450. @brief comparison: not equal
  3451. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3452. */
  3453. bool operator!=(const iter_impl& other) const
  3454. {
  3455. return not operator==(other);
  3456. }
  3457. /*!
  3458. @brief comparison: smaller
  3459. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3460. */
  3461. bool operator<(const iter_impl& other) const
  3462. {
  3463. // if objects are not the same, the comparison is undefined
  3464. if (JSON_UNLIKELY(m_object != other.m_object))
  3465. {
  3466. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  3467. }
  3468. assert(m_object != nullptr);
  3469. switch (m_object->m_type)
  3470. {
  3471. case value_t::object:
  3472. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  3473. case value_t::array:
  3474. return (m_it.array_iterator < other.m_it.array_iterator);
  3475. default:
  3476. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  3477. }
  3478. }
  3479. /*!
  3480. @brief comparison: less than or equal
  3481. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3482. */
  3483. bool operator<=(const iter_impl& other) const
  3484. {
  3485. return not other.operator < (*this);
  3486. }
  3487. /*!
  3488. @brief comparison: greater than
  3489. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3490. */
  3491. bool operator>(const iter_impl& other) const
  3492. {
  3493. return not operator<=(other);
  3494. }
  3495. /*!
  3496. @brief comparison: greater than or equal
  3497. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3498. */
  3499. bool operator>=(const iter_impl& other) const
  3500. {
  3501. return not operator<(other);
  3502. }
  3503. /*!
  3504. @brief add to iterator
  3505. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3506. */
  3507. iter_impl& operator+=(difference_type i)
  3508. {
  3509. assert(m_object != nullptr);
  3510. switch (m_object->m_type)
  3511. {
  3512. case value_t::object:
  3513. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3514. case value_t::array:
  3515. {
  3516. std::advance(m_it.array_iterator, i);
  3517. break;
  3518. }
  3519. default:
  3520. {
  3521. m_it.primitive_iterator += i;
  3522. break;
  3523. }
  3524. }
  3525. return *this;
  3526. }
  3527. /*!
  3528. @brief subtract from iterator
  3529. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3530. */
  3531. iter_impl& operator-=(difference_type i)
  3532. {
  3533. return operator+=(-i);
  3534. }
  3535. /*!
  3536. @brief add to iterator
  3537. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3538. */
  3539. iter_impl operator+(difference_type i) const
  3540. {
  3541. auto result = *this;
  3542. result += i;
  3543. return result;
  3544. }
  3545. /*!
  3546. @brief addition of distance and iterator
  3547. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3548. */
  3549. friend iter_impl operator+(difference_type i, const iter_impl& it)
  3550. {
  3551. auto result = it;
  3552. result += i;
  3553. return result;
  3554. }
  3555. /*!
  3556. @brief subtract from iterator
  3557. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3558. */
  3559. iter_impl operator-(difference_type i) const
  3560. {
  3561. auto result = *this;
  3562. result -= i;
  3563. return result;
  3564. }
  3565. /*!
  3566. @brief return difference
  3567. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3568. */
  3569. difference_type operator-(const iter_impl& other) const
  3570. {
  3571. assert(m_object != nullptr);
  3572. switch (m_object->m_type)
  3573. {
  3574. case value_t::object:
  3575. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  3576. case value_t::array:
  3577. return m_it.array_iterator - other.m_it.array_iterator;
  3578. default:
  3579. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  3580. }
  3581. }
  3582. /*!
  3583. @brief access to successor
  3584. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3585. */
  3586. reference operator[](difference_type n) const
  3587. {
  3588. assert(m_object != nullptr);
  3589. switch (m_object->m_type)
  3590. {
  3591. case value_t::object:
  3592. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  3593. case value_t::array:
  3594. return *std::next(m_it.array_iterator, n);
  3595. case value_t::null:
  3596. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3597. default:
  3598. {
  3599. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  3600. {
  3601. return *m_object;
  3602. }
  3603. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  3604. }
  3605. }
  3606. }
  3607. /*!
  3608. @brief return the key of an object iterator
  3609. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3610. */
  3611. typename object_t::key_type key() const
  3612. {
  3613. assert(m_object != nullptr);
  3614. if (JSON_LIKELY(m_object->is_object()))
  3615. {
  3616. return m_it.object_iterator->first;
  3617. }
  3618. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  3619. }
  3620. /*!
  3621. @brief return the value of an iterator
  3622. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  3623. */
  3624. reference value() const
  3625. {
  3626. return operator*();
  3627. }
  3628. private:
  3629. /// associated JSON instance
  3630. pointer m_object = nullptr;
  3631. /// the actual iterator of the associated instance
  3632. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};
  3633. };
  3634. /// proxy class for the iterator_wrapper functions
  3635. template<typename IteratorType> class iteration_proxy
  3636. {
  3637. private:
  3638. /// helper class for iteration
  3639. class iteration_proxy_internal
  3640. {
  3641. private:
  3642. /// the iterator
  3643. IteratorType anchor;
  3644. /// an index for arrays (used to create key names)
  3645. std::size_t array_index = 0;
  3646. public:
  3647. explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
  3648. /// dereference operator (needed for range-based for)
  3649. iteration_proxy_internal& operator*()
  3650. {
  3651. return *this;
  3652. }
  3653. /// increment operator (needed for range-based for)
  3654. iteration_proxy_internal& operator++()
  3655. {
  3656. ++anchor;
  3657. ++array_index;
  3658. return *this;
  3659. }
  3660. /// inequality operator (needed for range-based for)
  3661. bool operator!=(const iteration_proxy_internal& o) const noexcept
  3662. {
  3663. return anchor != o.anchor;
  3664. }
  3665. /// return key of the iterator
  3666. std::string key() const
  3667. {
  3668. assert(anchor.m_object != nullptr);
  3669. switch (anchor.m_object->type())
  3670. {
  3671. // use integer array index as key
  3672. case value_t::array:
  3673. return std::to_string(array_index);
  3674. // use key from the object
  3675. case value_t::object:
  3676. return anchor.key();
  3677. // use an empty key for all primitive types
  3678. default:
  3679. return "";
  3680. }
  3681. }
  3682. /// return value of the iterator
  3683. typename IteratorType::reference value() const
  3684. {
  3685. return anchor.value();
  3686. }
  3687. };
  3688. /// the container to iterate
  3689. typename IteratorType::reference container;
  3690. public:
  3691. /// construct iteration proxy from a container
  3692. explicit iteration_proxy(typename IteratorType::reference cont)
  3693. : container(cont) {}
  3694. /// return iterator begin (needed for range-based for)
  3695. iteration_proxy_internal begin() noexcept
  3696. {
  3697. return iteration_proxy_internal(container.begin());
  3698. }
  3699. /// return iterator end (needed for range-based for)
  3700. iteration_proxy_internal end() noexcept
  3701. {
  3702. return iteration_proxy_internal(container.end());
  3703. }
  3704. };
  3705. /*!
  3706. @brief a template for a reverse iterator class
  3707. @tparam Base the base iterator type to reverse. Valid types are @ref
  3708. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  3709. create @ref const_reverse_iterator).
  3710. @requirement The class satisfies the following concept requirements:
  3711. -
  3712. [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
  3713. The iterator that can be moved to point (forward and backward) to any
  3714. element in constant time.
  3715. - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
  3716. It is possible to write to the pointed-to element (only if @a Base is
  3717. @ref iterator).
  3718. @since version 1.0.0
  3719. */
  3720. template<typename Base>
  3721. class json_reverse_iterator : public std::reverse_iterator<Base>
  3722. {
  3723. public:
  3724. using difference_type = std::ptrdiff_t;
  3725. /// shortcut to the reverse iterator adaptor
  3726. using base_iterator = std::reverse_iterator<Base>;
  3727. /// the reference type for the pointed-to element
  3728. using reference = typename Base::reference;
  3729. /// create reverse iterator from iterator
  3730. json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  3731. : base_iterator(it) {}
  3732. /// create reverse iterator from base class
  3733. json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  3734. /// post-increment (it++)
  3735. json_reverse_iterator operator++(int)
  3736. {
  3737. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  3738. }
  3739. /// pre-increment (++it)
  3740. json_reverse_iterator& operator++()
  3741. {
  3742. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  3743. }
  3744. /// post-decrement (it--)
  3745. json_reverse_iterator operator--(int)
  3746. {
  3747. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  3748. }
  3749. /// pre-decrement (--it)
  3750. json_reverse_iterator& operator--()
  3751. {
  3752. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  3753. }
  3754. /// add to iterator
  3755. json_reverse_iterator& operator+=(difference_type i)
  3756. {
  3757. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  3758. }
  3759. /// add to iterator
  3760. json_reverse_iterator operator+(difference_type i) const
  3761. {
  3762. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  3763. }
  3764. /// subtract from iterator
  3765. json_reverse_iterator operator-(difference_type i) const
  3766. {
  3767. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  3768. }
  3769. /// return difference
  3770. difference_type operator-(const json_reverse_iterator& other) const
  3771. {
  3772. return base_iterator(*this) - base_iterator(other);
  3773. }
  3774. /// access to successor
  3775. reference operator[](difference_type n) const
  3776. {
  3777. return *(this->operator+(n));
  3778. }
  3779. /// return the key of an object iterator
  3780. auto key() const -> decltype(std::declval<Base>().key())
  3781. {
  3782. auto it = --this->base();
  3783. return it.key();
  3784. }
  3785. /// return the value of an iterator
  3786. reference value() const
  3787. {
  3788. auto it = --this->base();
  3789. return it.operator * ();
  3790. }
  3791. };
  3792. /////////////////////
  3793. // output adapters //
  3794. /////////////////////
  3795. /// abstract output adapter interface
  3796. template<typename CharType> struct output_adapter_protocol
  3797. {
  3798. virtual void write_character(CharType c) = 0;
  3799. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  3800. virtual ~output_adapter_protocol() = default;
  3801. };
  3802. /// a type to simplify interfaces
  3803. template<typename CharType>
  3804. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  3805. /// output adapter for byte vectors
  3806. template<typename CharType>
  3807. class output_vector_adapter : public output_adapter_protocol<CharType>
  3808. {
  3809. public:
  3810. explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
  3811. void write_character(CharType c) override
  3812. {
  3813. v.push_back(c);
  3814. }
  3815. void write_characters(const CharType* s, std::size_t length) override
  3816. {
  3817. std::copy(s, s + length, std::back_inserter(v));
  3818. }
  3819. private:
  3820. std::vector<CharType>& v;
  3821. };
  3822. /// output adapter for output streams
  3823. template<typename CharType>
  3824. class output_stream_adapter : public output_adapter_protocol<CharType>
  3825. {
  3826. public:
  3827. explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
  3828. void write_character(CharType c) override
  3829. {
  3830. stream.put(c);
  3831. }
  3832. void write_characters(const CharType* s, std::size_t length) override
  3833. {
  3834. stream.write(s, static_cast<std::streamsize>(length));
  3835. }
  3836. private:
  3837. std::basic_ostream<CharType>& stream;
  3838. };
  3839. /// output adapter for basic_string
  3840. template<typename CharType>
  3841. class output_string_adapter : public output_adapter_protocol<CharType>
  3842. {
  3843. public:
  3844. explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}
  3845. void write_character(CharType c) override
  3846. {
  3847. str.push_back(c);
  3848. }
  3849. void write_characters(const CharType* s, std::size_t length) override
  3850. {
  3851. str.append(s, length);
  3852. }
  3853. private:
  3854. std::basic_string<CharType>& str;
  3855. };
  3856. template<typename CharType>
  3857. class output_adapter
  3858. {
  3859. public:
  3860. output_adapter(std::vector<CharType>& vec)
  3861. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  3862. output_adapter(std::basic_ostream<CharType>& s)
  3863. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  3864. output_adapter(std::basic_string<CharType>& s)
  3865. : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}
  3866. operator output_adapter_t<CharType>()
  3867. {
  3868. return oa;
  3869. }
  3870. private:
  3871. output_adapter_t<CharType> oa = nullptr;
  3872. };
  3873. //////////////////////////////
  3874. // binary reader and writer //
  3875. //////////////////////////////
  3876. /*!
  3877. @brief deserialization of CBOR and MessagePack values
  3878. */
  3879. template<typename BasicJsonType>
  3880. class binary_reader
  3881. {
  3882. using number_integer_t = typename BasicJsonType::number_integer_t;
  3883. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3884. public:
  3885. /*!
  3886. @brief create a binary reader
  3887. @param[in] adapter input adapter to read from
  3888. */
  3889. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  3890. {
  3891. assert(ia);
  3892. }
  3893. /*!
  3894. @brief create a JSON value from CBOR input
  3895. @param[in] strict whether to expect the input to be consumed completed
  3896. @return JSON value created from CBOR input
  3897. @throw parse_error.110 if input ended unexpectedly or the end of file was
  3898. not reached when @a strict was set to true
  3899. @throw parse_error.112 if unsupported byte was read
  3900. */
  3901. BasicJsonType parse_cbor(const bool strict)
  3902. {
  3903. const auto res = parse_cbor_internal();
  3904. if (strict)
  3905. {
  3906. get();
  3907. check_eof(true);
  3908. }
  3909. return res;
  3910. }
  3911. /*!
  3912. @brief create a JSON value from MessagePack input
  3913. @param[in] strict whether to expect the input to be consumed completed
  3914. @return JSON value created from MessagePack input
  3915. @throw parse_error.110 if input ended unexpectedly or the end of file was
  3916. not reached when @a strict was set to true
  3917. @throw parse_error.112 if unsupported byte was read
  3918. */
  3919. BasicJsonType parse_msgpack(const bool strict)
  3920. {
  3921. const auto res = parse_msgpack_internal();
  3922. if (strict)
  3923. {
  3924. get();
  3925. check_eof(true);
  3926. }
  3927. return res;
  3928. }
  3929. /*!
  3930. @brief determine system byte order
  3931. @return true if and only if system's byte order is little endian
  3932. @note from http://stackoverflow.com/a/1001328/266378
  3933. */
  3934. static constexpr bool little_endianess(int num = 1) noexcept
  3935. {
  3936. return (*reinterpret_cast<char*>(&num) == 1);
  3937. }
  3938. private:
  3939. /*!
  3940. @param[in] get_char whether a new character should be retrieved from the
  3941. input (true, default) or whether the last read
  3942. character should be considered instead
  3943. */
  3944. BasicJsonType parse_cbor_internal(const bool get_char = true)
  3945. {
  3946. switch (get_char ? get() : current)
  3947. {
  3948. // EOF
  3949. case std::char_traits<char>::eof():
  3950. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  3951. // Integer 0x00..0x17 (0..23)
  3952. case 0x00:
  3953. case 0x01:
  3954. case 0x02:
  3955. case 0x03:
  3956. case 0x04:
  3957. case 0x05:
  3958. case 0x06:
  3959. case 0x07:
  3960. case 0x08:
  3961. case 0x09:
  3962. case 0x0a:
  3963. case 0x0b:
  3964. case 0x0c:
  3965. case 0x0d:
  3966. case 0x0e:
  3967. case 0x0f:
  3968. case 0x10:
  3969. case 0x11:
  3970. case 0x12:
  3971. case 0x13:
  3972. case 0x14:
  3973. case 0x15:
  3974. case 0x16:
  3975. case 0x17:
  3976. return static_cast<number_unsigned_t>(current);
  3977. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  3978. return get_number<uint8_t>();
  3979. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  3980. return get_number<uint16_t>();
  3981. case 0x1a: // Unsigned integer (four-byte uint32_t follows)
  3982. return get_number<uint32_t>();
  3983. case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
  3984. return get_number<uint64_t>();
  3985. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  3986. case 0x20:
  3987. case 0x21:
  3988. case 0x22:
  3989. case 0x23:
  3990. case 0x24:
  3991. case 0x25:
  3992. case 0x26:
  3993. case 0x27:
  3994. case 0x28:
  3995. case 0x29:
  3996. case 0x2a:
  3997. case 0x2b:
  3998. case 0x2c:
  3999. case 0x2d:
  4000. case 0x2e:
  4001. case 0x2f:
  4002. case 0x30:
  4003. case 0x31:
  4004. case 0x32:
  4005. case 0x33:
  4006. case 0x34:
  4007. case 0x35:
  4008. case 0x36:
  4009. case 0x37:
  4010. return static_cast<int8_t>(0x20 - 1 - current);
  4011. case 0x38: // Negative integer (one-byte uint8_t follows)
  4012. {
  4013. // must be uint8_t !
  4014. return static_cast<number_integer_t>(-1) - get_number<uint8_t>();
  4015. }
  4016. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  4017. {
  4018. return static_cast<number_integer_t>(-1) - get_number<uint16_t>();
  4019. }
  4020. case 0x3a: // Negative integer -1-n (four-byte uint32_t follows)
  4021. {
  4022. return static_cast<number_integer_t>(-1) - get_number<uint32_t>();
  4023. }
  4024. case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows)
  4025. {
  4026. return static_cast<number_integer_t>(-1) -
  4027. static_cast<number_integer_t>(get_number<uint64_t>());
  4028. }
  4029. // UTF-8 string (0x00..0x17 bytes follow)
  4030. case 0x60:
  4031. case 0x61:
  4032. case 0x62:
  4033. case 0x63:
  4034. case 0x64:
  4035. case 0x65:
  4036. case 0x66:
  4037. case 0x67:
  4038. case 0x68:
  4039. case 0x69:
  4040. case 0x6a:
  4041. case 0x6b:
  4042. case 0x6c:
  4043. case 0x6d:
  4044. case 0x6e:
  4045. case 0x6f:
  4046. case 0x70:
  4047. case 0x71:
  4048. case 0x72:
  4049. case 0x73:
  4050. case 0x74:
  4051. case 0x75:
  4052. case 0x76:
  4053. case 0x77:
  4054. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4055. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4056. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  4057. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  4058. case 0x7f: // UTF-8 string (indefinite length)
  4059. {
  4060. return get_cbor_string();
  4061. }
  4062. // array (0x00..0x17 data items follow)
  4063. case 0x80:
  4064. case 0x81:
  4065. case 0x82:
  4066. case 0x83:
  4067. case 0x84:
  4068. case 0x85:
  4069. case 0x86:
  4070. case 0x87:
  4071. case 0x88:
  4072. case 0x89:
  4073. case 0x8a:
  4074. case 0x8b:
  4075. case 0x8c:
  4076. case 0x8d:
  4077. case 0x8e:
  4078. case 0x8f:
  4079. case 0x90:
  4080. case 0x91:
  4081. case 0x92:
  4082. case 0x93:
  4083. case 0x94:
  4084. case 0x95:
  4085. case 0x96:
  4086. case 0x97:
  4087. {
  4088. return get_cbor_array(current & 0x1f);
  4089. }
  4090. case 0x98: // array (one-byte uint8_t for n follows)
  4091. {
  4092. return get_cbor_array(get_number<uint8_t>());
  4093. }
  4094. case 0x99: // array (two-byte uint16_t for n follow)
  4095. {
  4096. return get_cbor_array(get_number<uint16_t>());
  4097. }
  4098. case 0x9a: // array (four-byte uint32_t for n follow)
  4099. {
  4100. return get_cbor_array(get_number<uint32_t>());
  4101. }
  4102. case 0x9b: // array (eight-byte uint64_t for n follow)
  4103. {
  4104. return get_cbor_array(get_number<uint64_t>());
  4105. }
  4106. case 0x9f: // array (indefinite length)
  4107. {
  4108. BasicJsonType result = value_t::array;
  4109. while (get() != 0xff)
  4110. {
  4111. result.push_back(parse_cbor_internal(false));
  4112. }
  4113. return result;
  4114. }
  4115. // map (0x00..0x17 pairs of data items follow)
  4116. case 0xa0:
  4117. case 0xa1:
  4118. case 0xa2:
  4119. case 0xa3:
  4120. case 0xa4:
  4121. case 0xa5:
  4122. case 0xa6:
  4123. case 0xa7:
  4124. case 0xa8:
  4125. case 0xa9:
  4126. case 0xaa:
  4127. case 0xab:
  4128. case 0xac:
  4129. case 0xad:
  4130. case 0xae:
  4131. case 0xaf:
  4132. case 0xb0:
  4133. case 0xb1:
  4134. case 0xb2:
  4135. case 0xb3:
  4136. case 0xb4:
  4137. case 0xb5:
  4138. case 0xb6:
  4139. case 0xb7:
  4140. {
  4141. return get_cbor_object(current & 0x1f);
  4142. }
  4143. case 0xb8: // map (one-byte uint8_t for n follows)
  4144. {
  4145. return get_cbor_object(get_number<uint8_t>());
  4146. }
  4147. case 0xb9: // map (two-byte uint16_t for n follow)
  4148. {
  4149. return get_cbor_object(get_number<uint16_t>());
  4150. }
  4151. case 0xba: // map (four-byte uint32_t for n follow)
  4152. {
  4153. return get_cbor_object(get_number<uint32_t>());
  4154. }
  4155. case 0xbb: // map (eight-byte uint64_t for n follow)
  4156. {
  4157. return get_cbor_object(get_number<uint64_t>());
  4158. }
  4159. case 0xbf: // map (indefinite length)
  4160. {
  4161. BasicJsonType result = value_t::object;
  4162. while (get() != 0xff)
  4163. {
  4164. auto key = get_cbor_string();
  4165. result[key] = parse_cbor_internal();
  4166. }
  4167. return result;
  4168. }
  4169. case 0xf4: // false
  4170. {
  4171. return false;
  4172. }
  4173. case 0xf5: // true
  4174. {
  4175. return true;
  4176. }
  4177. case 0xf6: // null
  4178. {
  4179. return value_t::null;
  4180. }
  4181. case 0xf9: // Half-Precision Float (two-byte IEEE 754)
  4182. {
  4183. const int byte1 = get();
  4184. check_eof();
  4185. const int byte2 = get();
  4186. check_eof();
  4187. // code from RFC 7049, Appendix D, Figure 3:
  4188. // As half-precision floating-point numbers were only added
  4189. // to IEEE 754 in 2008, today's programming platforms often
  4190. // still only have limited support for them. It is very
  4191. // easy to include at least decoding support for them even
  4192. // without such support. An example of a small decoder for
  4193. // half-precision floating-point numbers in the C language
  4194. // is shown in Fig. 3.
  4195. const int half = (byte1 << 8) + byte2;
  4196. const int exp = (half >> 10) & 0x1f;
  4197. const int mant = half & 0x3ff;
  4198. double val;
  4199. if (exp == 0)
  4200. {
  4201. val = std::ldexp(mant, -24);
  4202. }
  4203. else if (exp != 31)
  4204. {
  4205. val = std::ldexp(mant + 1024, exp - 25);
  4206. }
  4207. else
  4208. {
  4209. val = (mant == 0) ? std::numeric_limits<double>::infinity()
  4210. : std::numeric_limits<double>::quiet_NaN();
  4211. }
  4212. return (half & 0x8000) != 0 ? -val : val;
  4213. }
  4214. case 0xfa: // Single-Precision Float (four-byte IEEE 754)
  4215. {
  4216. return get_number<float>();
  4217. }
  4218. case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
  4219. {
  4220. return get_number<double>();
  4221. }
  4222. default: // anything else (0xFF is handled inside the other types)
  4223. {
  4224. std::stringstream ss;
  4225. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  4226. JSON_THROW(parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + ss.str()));
  4227. }
  4228. }
  4229. }
  4230. BasicJsonType parse_msgpack_internal()
  4231. {
  4232. switch (get())
  4233. {
  4234. // EOF
  4235. case std::char_traits<char>::eof():
  4236. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4237. // positive fixint
  4238. case 0x00:
  4239. case 0x01:
  4240. case 0x02:
  4241. case 0x03:
  4242. case 0x04:
  4243. case 0x05:
  4244. case 0x06:
  4245. case 0x07:
  4246. case 0x08:
  4247. case 0x09:
  4248. case 0x0a:
  4249. case 0x0b:
  4250. case 0x0c:
  4251. case 0x0d:
  4252. case 0x0e:
  4253. case 0x0f:
  4254. case 0x10:
  4255. case 0x11:
  4256. case 0x12:
  4257. case 0x13:
  4258. case 0x14:
  4259. case 0x15:
  4260. case 0x16:
  4261. case 0x17:
  4262. case 0x18:
  4263. case 0x19:
  4264. case 0x1a:
  4265. case 0x1b:
  4266. case 0x1c:
  4267. case 0x1d:
  4268. case 0x1e:
  4269. case 0x1f:
  4270. case 0x20:
  4271. case 0x21:
  4272. case 0x22:
  4273. case 0x23:
  4274. case 0x24:
  4275. case 0x25:
  4276. case 0x26:
  4277. case 0x27:
  4278. case 0x28:
  4279. case 0x29:
  4280. case 0x2a:
  4281. case 0x2b:
  4282. case 0x2c:
  4283. case 0x2d:
  4284. case 0x2e:
  4285. case 0x2f:
  4286. case 0x30:
  4287. case 0x31:
  4288. case 0x32:
  4289. case 0x33:
  4290. case 0x34:
  4291. case 0x35:
  4292. case 0x36:
  4293. case 0x37:
  4294. case 0x38:
  4295. case 0x39:
  4296. case 0x3a:
  4297. case 0x3b:
  4298. case 0x3c:
  4299. case 0x3d:
  4300. case 0x3e:
  4301. case 0x3f:
  4302. case 0x40:
  4303. case 0x41:
  4304. case 0x42:
  4305. case 0x43:
  4306. case 0x44:
  4307. case 0x45:
  4308. case 0x46:
  4309. case 0x47:
  4310. case 0x48:
  4311. case 0x49:
  4312. case 0x4a:
  4313. case 0x4b:
  4314. case 0x4c:
  4315. case 0x4d:
  4316. case 0x4e:
  4317. case 0x4f:
  4318. case 0x50:
  4319. case 0x51:
  4320. case 0x52:
  4321. case 0x53:
  4322. case 0x54:
  4323. case 0x55:
  4324. case 0x56:
  4325. case 0x57:
  4326. case 0x58:
  4327. case 0x59:
  4328. case 0x5a:
  4329. case 0x5b:
  4330. case 0x5c:
  4331. case 0x5d:
  4332. case 0x5e:
  4333. case 0x5f:
  4334. case 0x60:
  4335. case 0x61:
  4336. case 0x62:
  4337. case 0x63:
  4338. case 0x64:
  4339. case 0x65:
  4340. case 0x66:
  4341. case 0x67:
  4342. case 0x68:
  4343. case 0x69:
  4344. case 0x6a:
  4345. case 0x6b:
  4346. case 0x6c:
  4347. case 0x6d:
  4348. case 0x6e:
  4349. case 0x6f:
  4350. case 0x70:
  4351. case 0x71:
  4352. case 0x72:
  4353. case 0x73:
  4354. case 0x74:
  4355. case 0x75:
  4356. case 0x76:
  4357. case 0x77:
  4358. case 0x78:
  4359. case 0x79:
  4360. case 0x7a:
  4361. case 0x7b:
  4362. case 0x7c:
  4363. case 0x7d:
  4364. case 0x7e:
  4365. case 0x7f:
  4366. return static_cast<number_unsigned_t>(current);
  4367. // fixmap
  4368. case 0x80:
  4369. case 0x81:
  4370. case 0x82:
  4371. case 0x83:
  4372. case 0x84:
  4373. case 0x85:
  4374. case 0x86:
  4375. case 0x87:
  4376. case 0x88:
  4377. case 0x89:
  4378. case 0x8a:
  4379. case 0x8b:
  4380. case 0x8c:
  4381. case 0x8d:
  4382. case 0x8e:
  4383. case 0x8f:
  4384. {
  4385. return get_msgpack_object(current & 0x0f);
  4386. }
  4387. // fixarray
  4388. case 0x90:
  4389. case 0x91:
  4390. case 0x92:
  4391. case 0x93:
  4392. case 0x94:
  4393. case 0x95:
  4394. case 0x96:
  4395. case 0x97:
  4396. case 0x98:
  4397. case 0x99:
  4398. case 0x9a:
  4399. case 0x9b:
  4400. case 0x9c:
  4401. case 0x9d:
  4402. case 0x9e:
  4403. case 0x9f:
  4404. {
  4405. return get_msgpack_array(current & 0x0f);
  4406. }
  4407. // fixstr
  4408. case 0xa0:
  4409. case 0xa1:
  4410. case 0xa2:
  4411. case 0xa3:
  4412. case 0xa4:
  4413. case 0xa5:
  4414. case 0xa6:
  4415. case 0xa7:
  4416. case 0xa8:
  4417. case 0xa9:
  4418. case 0xaa:
  4419. case 0xab:
  4420. case 0xac:
  4421. case 0xad:
  4422. case 0xae:
  4423. case 0xaf:
  4424. case 0xb0:
  4425. case 0xb1:
  4426. case 0xb2:
  4427. case 0xb3:
  4428. case 0xb4:
  4429. case 0xb5:
  4430. case 0xb6:
  4431. case 0xb7:
  4432. case 0xb8:
  4433. case 0xb9:
  4434. case 0xba:
  4435. case 0xbb:
  4436. case 0xbc:
  4437. case 0xbd:
  4438. case 0xbe:
  4439. case 0xbf:
  4440. return get_msgpack_string();
  4441. case 0xc0: // nil
  4442. return value_t::null;
  4443. case 0xc2: // false
  4444. return false;
  4445. case 0xc3: // true
  4446. return true;
  4447. case 0xca: // float 32
  4448. return get_number<float>();
  4449. case 0xcb: // float 64
  4450. return get_number<double>();
  4451. case 0xcc: // uint 8
  4452. return get_number<uint8_t>();
  4453. case 0xcd: // uint 16
  4454. return get_number<uint16_t>();
  4455. case 0xce: // uint 32
  4456. return get_number<uint32_t>();
  4457. case 0xcf: // uint 64
  4458. return get_number<uint64_t>();
  4459. case 0xd0: // int 8
  4460. return get_number<int8_t>();
  4461. case 0xd1: // int 16
  4462. return get_number<int16_t>();
  4463. case 0xd2: // int 32
  4464. return get_number<int32_t>();
  4465. case 0xd3: // int 64
  4466. return get_number<int64_t>();
  4467. case 0xd9: // str 8
  4468. case 0xda: // str 16
  4469. case 0xdb: // str 32
  4470. return get_msgpack_string();
  4471. case 0xdc: // array 16
  4472. {
  4473. return get_msgpack_array(get_number<uint16_t>());
  4474. }
  4475. case 0xdd: // array 32
  4476. {
  4477. return get_msgpack_array(get_number<uint32_t>());
  4478. }
  4479. case 0xde: // map 16
  4480. {
  4481. return get_msgpack_object(get_number<uint16_t>());
  4482. }
  4483. case 0xdf: // map 32
  4484. {
  4485. return get_msgpack_object(get_number<uint32_t>());
  4486. }
  4487. // positive fixint
  4488. case 0xe0:
  4489. case 0xe1:
  4490. case 0xe2:
  4491. case 0xe3:
  4492. case 0xe4:
  4493. case 0xe5:
  4494. case 0xe6:
  4495. case 0xe7:
  4496. case 0xe8:
  4497. case 0xe9:
  4498. case 0xea:
  4499. case 0xeb:
  4500. case 0xec:
  4501. case 0xed:
  4502. case 0xee:
  4503. case 0xef:
  4504. case 0xf0:
  4505. case 0xf1:
  4506. case 0xf2:
  4507. case 0xf3:
  4508. case 0xf4:
  4509. case 0xf5:
  4510. case 0xf6:
  4511. case 0xf7:
  4512. case 0xf8:
  4513. case 0xf9:
  4514. case 0xfa:
  4515. case 0xfb:
  4516. case 0xfc:
  4517. case 0xfd:
  4518. case 0xfe:
  4519. case 0xff:
  4520. return static_cast<int8_t>(current);
  4521. default: // anything else
  4522. {
  4523. std::stringstream ss;
  4524. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  4525. JSON_THROW(parse_error::create(112, chars_read,
  4526. "error reading MessagePack; last byte: 0x" + ss.str()));
  4527. }
  4528. }
  4529. }
  4530. /*!
  4531. @brief get next character from the input
  4532. This function provides the interface to the used input adapter. It does
  4533. not throw in case the input reached EOF, but returns
  4534. `std::char_traits<char>::eof()` in that case.
  4535. @return character read from the input
  4536. */
  4537. int get()
  4538. {
  4539. ++chars_read;
  4540. return (current = ia->get_character());
  4541. }
  4542. /*
  4543. @brief read a number from the input
  4544. @tparam NumberType the type of the number
  4545. @return number of type @a NumberType
  4546. @note This function needs to respect the system's endianess, because
  4547. bytes in CBOR and MessagePack are stored in network order (big
  4548. endian) and therefore need reordering on little endian systems.
  4549. @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes
  4550. */
  4551. template<typename NumberType> NumberType get_number()
  4552. {
  4553. // step 1: read input into array with system's byte order
  4554. std::array<uint8_t, sizeof(NumberType)> vec;
  4555. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  4556. {
  4557. get();
  4558. check_eof();
  4559. // reverse byte order prior to conversion if necessary
  4560. if (is_little_endian)
  4561. {
  4562. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  4563. }
  4564. else
  4565. {
  4566. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  4567. }
  4568. }
  4569. // step 2: convert array into number of type T and return
  4570. NumberType result;
  4571. std::memcpy(&result, vec.data(), sizeof(NumberType));
  4572. return result;
  4573. }
  4574. /*!
  4575. @brief create a string by reading characters from the input
  4576. @param[in] len number of bytes to read
  4577. @note We can not reserve @a len bytes for the result, because @a len
  4578. may be too large. Usually, @ref check_eof() detects the end of
  4579. the input before we run out of string memory.
  4580. @return string created by reading @a len bytes
  4581. @throw parse_error.110 if input has less than @a len bytes
  4582. */
  4583. template<typename NumberType>
  4584. std::string get_string(const NumberType len)
  4585. {
  4586. std::string result;
  4587. std::generate_n(std::back_inserter(result), len, [this]()
  4588. {
  4589. get();
  4590. check_eof();
  4591. return current;
  4592. });
  4593. return result;
  4594. }
  4595. /*!
  4596. @brief reads a CBOR string
  4597. This function first reads starting bytes to determine the expected
  4598. string length and then copies this number of bytes into a string.
  4599. Additionally, CBOR's strings with indefinite lengths are supported.
  4600. @return string
  4601. @throw parse_error.110 if input ended
  4602. @throw parse_error.113 if an unexpected byte is read
  4603. */
  4604. std::string get_cbor_string()
  4605. {
  4606. check_eof();
  4607. switch (current)
  4608. {
  4609. // UTF-8 string (0x00..0x17 bytes follow)
  4610. case 0x60:
  4611. case 0x61:
  4612. case 0x62:
  4613. case 0x63:
  4614. case 0x64:
  4615. case 0x65:
  4616. case 0x66:
  4617. case 0x67:
  4618. case 0x68:
  4619. case 0x69:
  4620. case 0x6a:
  4621. case 0x6b:
  4622. case 0x6c:
  4623. case 0x6d:
  4624. case 0x6e:
  4625. case 0x6f:
  4626. case 0x70:
  4627. case 0x71:
  4628. case 0x72:
  4629. case 0x73:
  4630. case 0x74:
  4631. case 0x75:
  4632. case 0x76:
  4633. case 0x77:
  4634. {
  4635. return get_string(current & 0x1f);
  4636. }
  4637. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  4638. {
  4639. return get_string(get_number<uint8_t>());
  4640. }
  4641. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  4642. {
  4643. return get_string(get_number<uint16_t>());
  4644. }
  4645. case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
  4646. {
  4647. return get_string(get_number<uint32_t>());
  4648. }
  4649. case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
  4650. {
  4651. return get_string(get_number<uint64_t>());
  4652. }
  4653. case 0x7f: // UTF-8 string (indefinite length)
  4654. {
  4655. std::string result;
  4656. while (get() != 0xff)
  4657. {
  4658. check_eof();
  4659. result.push_back(static_cast<char>(current));
  4660. }
  4661. return result;
  4662. }
  4663. default:
  4664. {
  4665. std::stringstream ss;
  4666. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  4667. JSON_THROW(parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + ss.str()));
  4668. }
  4669. }
  4670. }
  4671. template<typename NumberType>
  4672. BasicJsonType get_cbor_array(const NumberType len)
  4673. {
  4674. BasicJsonType result = value_t::array;
  4675. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  4676. {
  4677. return parse_cbor_internal();
  4678. });
  4679. return result;
  4680. }
  4681. template<typename NumberType>
  4682. BasicJsonType get_cbor_object(const NumberType len)
  4683. {
  4684. BasicJsonType result = value_t::object;
  4685. std::generate_n(std::inserter(*result.m_value.object,
  4686. result.m_value.object->end()),
  4687. len, [this]()
  4688. {
  4689. get();
  4690. auto key = get_cbor_string();
  4691. auto val = parse_cbor_internal();
  4692. return std::make_pair(std::move(key), std::move(val));
  4693. });
  4694. return result;
  4695. }
  4696. /*!
  4697. @brief reads a MessagePack string
  4698. This function first reads starting bytes to determine the expected
  4699. string length and then copies this number of bytes into a string.
  4700. @return string
  4701. @throw parse_error.110 if input ended
  4702. @throw parse_error.113 if an unexpected byte is read
  4703. */
  4704. std::string get_msgpack_string()
  4705. {
  4706. check_eof();
  4707. switch (current)
  4708. {
  4709. // fixstr
  4710. case 0xa0:
  4711. case 0xa1:
  4712. case 0xa2:
  4713. case 0xa3:
  4714. case 0xa4:
  4715. case 0xa5:
  4716. case 0xa6:
  4717. case 0xa7:
  4718. case 0xa8:
  4719. case 0xa9:
  4720. case 0xaa:
  4721. case 0xab:
  4722. case 0xac:
  4723. case 0xad:
  4724. case 0xae:
  4725. case 0xaf:
  4726. case 0xb0:
  4727. case 0xb1:
  4728. case 0xb2:
  4729. case 0xb3:
  4730. case 0xb4:
  4731. case 0xb5:
  4732. case 0xb6:
  4733. case 0xb7:
  4734. case 0xb8:
  4735. case 0xb9:
  4736. case 0xba:
  4737. case 0xbb:
  4738. case 0xbc:
  4739. case 0xbd:
  4740. case 0xbe:
  4741. case 0xbf:
  4742. {
  4743. return get_string(current & 0x1f);
  4744. }
  4745. case 0xd9: // str 8
  4746. {
  4747. return get_string(get_number<uint8_t>());
  4748. }
  4749. case 0xda: // str 16
  4750. {
  4751. return get_string(get_number<uint16_t>());
  4752. }
  4753. case 0xdb: // str 32
  4754. {
  4755. return get_string(get_number<uint32_t>());
  4756. }
  4757. default:
  4758. {
  4759. std::stringstream ss;
  4760. ss << std::setw(2) << std::setfill('0') << std::hex << current;
  4761. JSON_THROW(parse_error::create(113, chars_read,
  4762. "expected a MessagePack string; last byte: 0x" + ss.str()));
  4763. }
  4764. }
  4765. }
  4766. template<typename NumberType>
  4767. BasicJsonType get_msgpack_array(const NumberType len)
  4768. {
  4769. BasicJsonType result = value_t::array;
  4770. std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()
  4771. {
  4772. return parse_msgpack_internal();
  4773. });
  4774. return result;
  4775. }
  4776. template<typename NumberType>
  4777. BasicJsonType get_msgpack_object(const NumberType len)
  4778. {
  4779. BasicJsonType result = value_t::object;
  4780. std::generate_n(std::inserter(*result.m_value.object,
  4781. result.m_value.object->end()),
  4782. len, [this]()
  4783. {
  4784. get();
  4785. auto key = get_msgpack_string();
  4786. auto val = parse_msgpack_internal();
  4787. return std::make_pair(std::move(key), std::move(val));
  4788. });
  4789. return result;
  4790. }
  4791. /*!
  4792. @brief check if input ended
  4793. @throw parse_error.110 if input ended
  4794. */
  4795. void check_eof(const bool expect_eof = false) const
  4796. {
  4797. if (expect_eof)
  4798. {
  4799. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  4800. {
  4801. JSON_THROW(parse_error::create(110, chars_read, "expected end of input"));
  4802. }
  4803. }
  4804. else
  4805. {
  4806. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  4807. {
  4808. JSON_THROW(parse_error::create(110, chars_read, "unexpected end of input"));
  4809. }
  4810. }
  4811. }
  4812. private:
  4813. /// input adapter
  4814. input_adapter_t ia = nullptr;
  4815. /// the current character
  4816. int current = std::char_traits<char>::eof();
  4817. /// the number of characters read
  4818. std::size_t chars_read = 0;
  4819. /// whether we can assume little endianess
  4820. const bool is_little_endian = little_endianess();
  4821. };
  4822. /*!
  4823. @brief serialization to CBOR and MessagePack values
  4824. */
  4825. template<typename BasicJsonType, typename CharType>
  4826. class binary_writer
  4827. {
  4828. public:
  4829. /*!
  4830. @brief create a binary writer
  4831. @param[in] adapter output adapter to write to
  4832. */
  4833. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  4834. {
  4835. assert(oa);
  4836. }
  4837. /*!
  4838. @brief[in] j JSON value to serialize
  4839. */
  4840. void write_cbor(const BasicJsonType& j)
  4841. {
  4842. switch (j.type())
  4843. {
  4844. case value_t::null:
  4845. {
  4846. oa->write_character(static_cast<CharType>(0xf6));
  4847. break;
  4848. }
  4849. case value_t::boolean:
  4850. {
  4851. oa->write_character(j.m_value.boolean
  4852. ? static_cast<CharType>(0xf5)
  4853. : static_cast<CharType>(0xf4));
  4854. break;
  4855. }
  4856. case value_t::number_integer:
  4857. {
  4858. if (j.m_value.number_integer >= 0)
  4859. {
  4860. // CBOR does not differentiate between positive signed
  4861. // integers and unsigned integers. Therefore, we used the
  4862. // code from the value_t::number_unsigned case here.
  4863. if (j.m_value.number_integer <= 0x17)
  4864. {
  4865. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  4866. }
  4867. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  4868. {
  4869. oa->write_character(static_cast<CharType>(0x18));
  4870. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  4871. }
  4872. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  4873. {
  4874. oa->write_character(static_cast<CharType>(0x19));
  4875. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  4876. }
  4877. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  4878. {
  4879. oa->write_character(static_cast<CharType>(0x1a));
  4880. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  4881. }
  4882. else
  4883. {
  4884. oa->write_character(static_cast<CharType>(0x1b));
  4885. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  4886. }
  4887. }
  4888. else
  4889. {
  4890. // The conversions below encode the sign in the first
  4891. // byte, and the value is converted to a positive number.
  4892. const auto positive_number = -1 - j.m_value.number_integer;
  4893. if (j.m_value.number_integer >= -24)
  4894. {
  4895. write_number(static_cast<uint8_t>(0x20 + positive_number));
  4896. }
  4897. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  4898. {
  4899. oa->write_character(static_cast<CharType>(0x38));
  4900. write_number(static_cast<uint8_t>(positive_number));
  4901. }
  4902. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  4903. {
  4904. oa->write_character(static_cast<CharType>(0x39));
  4905. write_number(static_cast<uint16_t>(positive_number));
  4906. }
  4907. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  4908. {
  4909. oa->write_character(static_cast<CharType>(0x3a));
  4910. write_number(static_cast<uint32_t>(positive_number));
  4911. }
  4912. else
  4913. {
  4914. oa->write_character(static_cast<CharType>(0x3b));
  4915. write_number(static_cast<uint64_t>(positive_number));
  4916. }
  4917. }
  4918. break;
  4919. }
  4920. case value_t::number_unsigned:
  4921. {
  4922. if (j.m_value.number_unsigned <= 0x17)
  4923. {
  4924. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  4925. }
  4926. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  4927. {
  4928. oa->write_character(static_cast<CharType>(0x18));
  4929. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  4930. }
  4931. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  4932. {
  4933. oa->write_character(static_cast<CharType>(0x19));
  4934. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  4935. }
  4936. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  4937. {
  4938. oa->write_character(static_cast<CharType>(0x1a));
  4939. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  4940. }
  4941. else
  4942. {
  4943. oa->write_character(static_cast<CharType>(0x1b));
  4944. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  4945. }
  4946. break;
  4947. }
  4948. case value_t::number_float: // Double-Precision Float
  4949. {
  4950. oa->write_character(static_cast<CharType>(0xfb));
  4951. write_number(j.m_value.number_float);
  4952. break;
  4953. }
  4954. case value_t::string:
  4955. {
  4956. // step 1: write control byte and the string length
  4957. const auto N = j.m_value.string->size();
  4958. if (N <= 0x17)
  4959. {
  4960. write_number(static_cast<uint8_t>(0x60 + N));
  4961. }
  4962. else if (N <= 0xff)
  4963. {
  4964. oa->write_character(static_cast<CharType>(0x78));
  4965. write_number(static_cast<uint8_t>(N));
  4966. }
  4967. else if (N <= 0xffff)
  4968. {
  4969. oa->write_character(static_cast<CharType>(0x79));
  4970. write_number(static_cast<uint16_t>(N));
  4971. }
  4972. else if (N <= 0xffffffff)
  4973. {
  4974. oa->write_character(static_cast<CharType>(0x7a));
  4975. write_number(static_cast<uint32_t>(N));
  4976. }
  4977. // LCOV_EXCL_START
  4978. else if (N <= 0xffffffffffffffff)
  4979. {
  4980. oa->write_character(static_cast<CharType>(0x7b));
  4981. write_number(static_cast<uint64_t>(N));
  4982. }
  4983. // LCOV_EXCL_STOP
  4984. // step 2: write the string
  4985. oa->write_characters(
  4986. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  4987. j.m_value.string->size());
  4988. break;
  4989. }
  4990. case value_t::array:
  4991. {
  4992. // step 1: write control byte and the array size
  4993. const auto N = j.m_value.array->size();
  4994. if (N <= 0x17)
  4995. {
  4996. write_number(static_cast<uint8_t>(0x80 + N));
  4997. }
  4998. else if (N <= 0xff)
  4999. {
  5000. oa->write_character(static_cast<CharType>(0x98));
  5001. write_number(static_cast<uint8_t>(N));
  5002. }
  5003. else if (N <= 0xffff)
  5004. {
  5005. oa->write_character(static_cast<CharType>(0x99));
  5006. write_number(static_cast<uint16_t>(N));
  5007. }
  5008. else if (N <= 0xffffffff)
  5009. {
  5010. oa->write_character(static_cast<CharType>(0x9a));
  5011. write_number(static_cast<uint32_t>(N));
  5012. }
  5013. // LCOV_EXCL_START
  5014. else if (N <= 0xffffffffffffffff)
  5015. {
  5016. oa->write_character(static_cast<CharType>(0x9b));
  5017. write_number(static_cast<uint64_t>(N));
  5018. }
  5019. // LCOV_EXCL_STOP
  5020. // step 2: write each element
  5021. for (const auto& el : *j.m_value.array)
  5022. {
  5023. write_cbor(el);
  5024. }
  5025. break;
  5026. }
  5027. case value_t::object:
  5028. {
  5029. // step 1: write control byte and the object size
  5030. const auto N = j.m_value.object->size();
  5031. if (N <= 0x17)
  5032. {
  5033. write_number(static_cast<uint8_t>(0xa0 + N));
  5034. }
  5035. else if (N <= 0xff)
  5036. {
  5037. oa->write_character(static_cast<CharType>(0xb8));
  5038. write_number(static_cast<uint8_t>(N));
  5039. }
  5040. else if (N <= 0xffff)
  5041. {
  5042. oa->write_character(static_cast<CharType>(0xb9));
  5043. write_number(static_cast<uint16_t>(N));
  5044. }
  5045. else if (N <= 0xffffffff)
  5046. {
  5047. oa->write_character(static_cast<CharType>(0xba));
  5048. write_number(static_cast<uint32_t>(N));
  5049. }
  5050. // LCOV_EXCL_START
  5051. else if (N <= 0xffffffffffffffff)
  5052. {
  5053. oa->write_character(static_cast<CharType>(0xbb));
  5054. write_number(static_cast<uint64_t>(N));
  5055. }
  5056. // LCOV_EXCL_STOP
  5057. // step 2: write each element
  5058. for (const auto& el : *j.m_value.object)
  5059. {
  5060. write_cbor(el.first);
  5061. write_cbor(el.second);
  5062. }
  5063. break;
  5064. }
  5065. default:
  5066. break;
  5067. }
  5068. }
  5069. /*!
  5070. @brief[in] j JSON value to serialize
  5071. */
  5072. void write_msgpack(const BasicJsonType& j)
  5073. {
  5074. switch (j.type())
  5075. {
  5076. case value_t::null: // nil
  5077. {
  5078. oa->write_character(static_cast<CharType>(0xc0));
  5079. break;
  5080. }
  5081. case value_t::boolean: // true and false
  5082. {
  5083. oa->write_character(j.m_value.boolean
  5084. ? static_cast<CharType>(0xc3)
  5085. : static_cast<CharType>(0xc2));
  5086. break;
  5087. }
  5088. case value_t::number_integer:
  5089. {
  5090. if (j.m_value.number_integer >= 0)
  5091. {
  5092. // MessagePack does not differentiate between positive
  5093. // signed integers and unsigned integers. Therefore, we used
  5094. // the code from the value_t::number_unsigned case here.
  5095. if (j.m_value.number_unsigned < 128)
  5096. {
  5097. // positive fixnum
  5098. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5099. }
  5100. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5101. {
  5102. // uint 8
  5103. oa->write_character(static_cast<CharType>(0xcc));
  5104. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5105. }
  5106. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5107. {
  5108. // uint 16
  5109. oa->write_character(static_cast<CharType>(0xcd));
  5110. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5111. }
  5112. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5113. {
  5114. // uint 32
  5115. oa->write_character(static_cast<CharType>(0xce));
  5116. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5117. }
  5118. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5119. {
  5120. // uint 64
  5121. oa->write_character(static_cast<CharType>(0xcf));
  5122. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5123. }
  5124. }
  5125. else
  5126. {
  5127. if (j.m_value.number_integer >= -32)
  5128. {
  5129. // negative fixnum
  5130. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5131. }
  5132. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
  5133. j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  5134. {
  5135. // int 8
  5136. oa->write_character(static_cast<CharType>(0xd0));
  5137. write_number(static_cast<int8_t>(j.m_value.number_integer));
  5138. }
  5139. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
  5140. j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  5141. {
  5142. // int 16
  5143. oa->write_character(static_cast<CharType>(0xd1));
  5144. write_number(static_cast<int16_t>(j.m_value.number_integer));
  5145. }
  5146. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
  5147. j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  5148. {
  5149. // int 32
  5150. oa->write_character(static_cast<CharType>(0xd2));
  5151. write_number(static_cast<int32_t>(j.m_value.number_integer));
  5152. }
  5153. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
  5154. j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  5155. {
  5156. // int 64
  5157. oa->write_character(static_cast<CharType>(0xd3));
  5158. write_number(static_cast<int64_t>(j.m_value.number_integer));
  5159. }
  5160. }
  5161. break;
  5162. }
  5163. case value_t::number_unsigned:
  5164. {
  5165. if (j.m_value.number_unsigned < 128)
  5166. {
  5167. // positive fixnum
  5168. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5169. }
  5170. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  5171. {
  5172. // uint 8
  5173. oa->write_character(static_cast<CharType>(0xcc));
  5174. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  5175. }
  5176. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  5177. {
  5178. // uint 16
  5179. oa->write_character(static_cast<CharType>(0xcd));
  5180. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  5181. }
  5182. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  5183. {
  5184. // uint 32
  5185. oa->write_character(static_cast<CharType>(0xce));
  5186. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  5187. }
  5188. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  5189. {
  5190. // uint 64
  5191. oa->write_character(static_cast<CharType>(0xcf));
  5192. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  5193. }
  5194. break;
  5195. }
  5196. case value_t::number_float: // float 64
  5197. {
  5198. oa->write_character(static_cast<CharType>(0xcb));
  5199. write_number(j.m_value.number_float);
  5200. break;
  5201. }
  5202. case value_t::string:
  5203. {
  5204. // step 1: write control byte and the string length
  5205. const auto N = j.m_value.string->size();
  5206. if (N <= 31)
  5207. {
  5208. // fixstr
  5209. write_number(static_cast<uint8_t>(0xa0 | N));
  5210. }
  5211. else if (N <= 255)
  5212. {
  5213. // str 8
  5214. oa->write_character(static_cast<CharType>(0xd9));
  5215. write_number(static_cast<uint8_t>(N));
  5216. }
  5217. else if (N <= 65535)
  5218. {
  5219. // str 16
  5220. oa->write_character(static_cast<CharType>(0xda));
  5221. write_number(static_cast<uint16_t>(N));
  5222. }
  5223. else if (N <= 4294967295)
  5224. {
  5225. // str 32
  5226. oa->write_character(static_cast<CharType>(0xdb));
  5227. write_number(static_cast<uint32_t>(N));
  5228. }
  5229. // step 2: write the string
  5230. oa->write_characters(
  5231. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  5232. j.m_value.string->size());
  5233. break;
  5234. }
  5235. case value_t::array:
  5236. {
  5237. // step 1: write control byte and the array size
  5238. const auto N = j.m_value.array->size();
  5239. if (N <= 15)
  5240. {
  5241. // fixarray
  5242. write_number(static_cast<uint8_t>(0x90 | N));
  5243. }
  5244. else if (N <= 0xffff)
  5245. {
  5246. // array 16
  5247. oa->write_character(static_cast<CharType>(0xdc));
  5248. write_number(static_cast<uint16_t>(N));
  5249. }
  5250. else if (N <= 0xffffffff)
  5251. {
  5252. // array 32
  5253. oa->write_character(static_cast<CharType>(0xdd));
  5254. write_number(static_cast<uint32_t>(N));
  5255. }
  5256. // step 2: write each element
  5257. for (const auto& el : *j.m_value.array)
  5258. {
  5259. write_msgpack(el);
  5260. }
  5261. break;
  5262. }
  5263. case value_t::object:
  5264. {
  5265. // step 1: write control byte and the object size
  5266. const auto N = j.m_value.object->size();
  5267. if (N <= 15)
  5268. {
  5269. // fixmap
  5270. write_number(static_cast<uint8_t>(0x80 | (N & 0xf)));
  5271. }
  5272. else if (N <= 65535)
  5273. {
  5274. // map 16
  5275. oa->write_character(static_cast<CharType>(0xde));
  5276. write_number(static_cast<uint16_t>(N));
  5277. }
  5278. else if (N <= 4294967295)
  5279. {
  5280. // map 32
  5281. oa->write_character(static_cast<CharType>(0xdf));
  5282. write_number(static_cast<uint32_t>(N));
  5283. }
  5284. // step 2: write each element
  5285. for (const auto& el : *j.m_value.object)
  5286. {
  5287. write_msgpack(el.first);
  5288. write_msgpack(el.second);
  5289. }
  5290. break;
  5291. }
  5292. default:
  5293. break;
  5294. }
  5295. }
  5296. private:
  5297. /*
  5298. @brief write a number to output input
  5299. @param[in] n number of type @a NumberType
  5300. @tparam NumberType the type of the number
  5301. @note This function needs to respect the system's endianess, because bytes
  5302. in CBOR and MessagePack are stored in network order (big endian) and
  5303. therefore need reordering on little endian systems.
  5304. */
  5305. template<typename NumberType> void write_number(NumberType n)
  5306. {
  5307. // step 1: write number to array of length NumberType
  5308. std::array<CharType, sizeof(NumberType)> vec;
  5309. std::memcpy(vec.data(), &n, sizeof(NumberType));
  5310. // step 2: write array to output (with possible reordering)
  5311. if (is_little_endian)
  5312. {
  5313. // reverse byte order prior to conversion if necessary
  5314. std::reverse(vec.begin(), vec.end());
  5315. }
  5316. oa->write_characters(vec.data(), sizeof(NumberType));
  5317. }
  5318. private:
  5319. /// whether we can assume little endianess
  5320. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  5321. /// the output
  5322. output_adapter_t<CharType> oa = nullptr;
  5323. };
  5324. ///////////////////
  5325. // serialization //
  5326. ///////////////////
  5327. template<typename BasicJsonType>
  5328. class serializer
  5329. {
  5330. using string_t = typename BasicJsonType::string_t;
  5331. using number_float_t = typename BasicJsonType::number_float_t;
  5332. using number_integer_t = typename BasicJsonType::number_integer_t;
  5333. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5334. public:
  5335. /*!
  5336. @param[in] s output stream to serialize to
  5337. @param[in] ichar indentation character to use
  5338. */
  5339. serializer(output_adapter_t<char> s, const char ichar)
  5340. : o(std::move(s)), loc(std::localeconv()),
  5341. thousands_sep(loc->thousands_sep == nullptr ? '\0' : loc->thousands_sep[0]),
  5342. decimal_point(loc->decimal_point == nullptr ? '\0' : loc->decimal_point[0]),
  5343. indent_char(ichar), indent_string(512, indent_char) {}
  5344. // delete because of pointer members
  5345. serializer(const serializer&) = delete;
  5346. serializer& operator=(const serializer&) = delete;
  5347. /*!
  5348. @brief internal implementation of the serialization function
  5349. This function is called by the public member function dump and organizes
  5350. the serialization internally. The indentation level is propagated as
  5351. additional parameter. In case of arrays and objects, the function is
  5352. called recursively.
  5353. - strings and object keys are escaped using `escape_string()`
  5354. - integer numbers are converted implicitly via `operator<<`
  5355. - floating-point numbers are converted to a string using `"%g"` format
  5356. @param[in] val value to serialize
  5357. @param[in] pretty_print whether the output shall be pretty-printed
  5358. @param[in] indent_step the indent level
  5359. @param[in] current_indent the current indent level (only used internally)
  5360. */
  5361. void dump(const BasicJsonType& val, const bool pretty_print,
  5362. const bool ensure_ascii,
  5363. const unsigned int indent_step,
  5364. const unsigned int current_indent = 0)
  5365. {
  5366. switch (val.m_type)
  5367. {
  5368. case value_t::object:
  5369. {
  5370. if (val.m_value.object->empty())
  5371. {
  5372. o->write_characters("{}", 2);
  5373. return;
  5374. }
  5375. if (pretty_print)
  5376. {
  5377. o->write_characters("{\n", 2);
  5378. // variable to hold indentation for recursive calls
  5379. const auto new_indent = current_indent + indent_step;
  5380. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  5381. {
  5382. indent_string.resize(indent_string.size() * 2, ' ');
  5383. }
  5384. // first n-1 elements
  5385. auto i = val.m_value.object->cbegin();
  5386. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5387. {
  5388. o->write_characters(indent_string.c_str(), new_indent);
  5389. o->write_character('\"');
  5390. dump_escaped(i->first, ensure_ascii);
  5391. o->write_characters("\": ", 3);
  5392. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  5393. o->write_characters(",\n", 2);
  5394. }
  5395. // last element
  5396. assert(i != val.m_value.object->cend());
  5397. assert(std::next(i) == val.m_value.object->cend());
  5398. o->write_characters(indent_string.c_str(), new_indent);
  5399. o->write_character('\"');
  5400. dump_escaped(i->first, ensure_ascii);
  5401. o->write_characters("\": ", 3);
  5402. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  5403. o->write_character('\n');
  5404. o->write_characters(indent_string.c_str(), current_indent);
  5405. o->write_character('}');
  5406. }
  5407. else
  5408. {
  5409. o->write_character('{');
  5410. // first n-1 elements
  5411. auto i = val.m_value.object->cbegin();
  5412. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  5413. {
  5414. o->write_character('\"');
  5415. dump_escaped(i->first, ensure_ascii);
  5416. o->write_characters("\":", 2);
  5417. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  5418. o->write_character(',');
  5419. }
  5420. // last element
  5421. assert(i != val.m_value.object->cend());
  5422. assert(std::next(i) == val.m_value.object->cend());
  5423. o->write_character('\"');
  5424. dump_escaped(i->first, ensure_ascii);
  5425. o->write_characters("\":", 2);
  5426. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  5427. o->write_character('}');
  5428. }
  5429. return;
  5430. }
  5431. case value_t::array:
  5432. {
  5433. if (val.m_value.array->empty())
  5434. {
  5435. o->write_characters("[]", 2);
  5436. return;
  5437. }
  5438. if (pretty_print)
  5439. {
  5440. o->write_characters("[\n", 2);
  5441. // variable to hold indentation for recursive calls
  5442. const auto new_indent = current_indent + indent_step;
  5443. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  5444. {
  5445. indent_string.resize(indent_string.size() * 2, ' ');
  5446. }
  5447. // first n-1 elements
  5448. for (auto i = val.m_value.array->cbegin();
  5449. i != val.m_value.array->cend() - 1; ++i)
  5450. {
  5451. o->write_characters(indent_string.c_str(), new_indent);
  5452. dump(*i, true, ensure_ascii, indent_step, new_indent);
  5453. o->write_characters(",\n", 2);
  5454. }
  5455. // last element
  5456. assert(not val.m_value.array->empty());
  5457. o->write_characters(indent_string.c_str(), new_indent);
  5458. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  5459. o->write_character('\n');
  5460. o->write_characters(indent_string.c_str(), current_indent);
  5461. o->write_character(']');
  5462. }
  5463. else
  5464. {
  5465. o->write_character('[');
  5466. // first n-1 elements
  5467. for (auto i = val.m_value.array->cbegin();
  5468. i != val.m_value.array->cend() - 1; ++i)
  5469. {
  5470. dump(*i, false, ensure_ascii, indent_step, current_indent);
  5471. o->write_character(',');
  5472. }
  5473. // last element
  5474. assert(not val.m_value.array->empty());
  5475. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  5476. o->write_character(']');
  5477. }
  5478. return;
  5479. }
  5480. case value_t::string:
  5481. {
  5482. o->write_character('\"');
  5483. dump_escaped(*val.m_value.string, ensure_ascii);
  5484. o->write_character('\"');
  5485. return;
  5486. }
  5487. case value_t::boolean:
  5488. {
  5489. if (val.m_value.boolean)
  5490. {
  5491. o->write_characters("true", 4);
  5492. }
  5493. else
  5494. {
  5495. o->write_characters("false", 5);
  5496. }
  5497. return;
  5498. }
  5499. case value_t::number_integer:
  5500. {
  5501. dump_integer(val.m_value.number_integer);
  5502. return;
  5503. }
  5504. case value_t::number_unsigned:
  5505. {
  5506. dump_integer(val.m_value.number_unsigned);
  5507. return;
  5508. }
  5509. case value_t::number_float:
  5510. {
  5511. dump_float(val.m_value.number_float);
  5512. return;
  5513. }
  5514. case value_t::discarded:
  5515. {
  5516. o->write_characters("<discarded>", 11);
  5517. return;
  5518. }
  5519. case value_t::null:
  5520. {
  5521. o->write_characters("null", 4);
  5522. return;
  5523. }
  5524. }
  5525. }
  5526. private:
  5527. /*!
  5528. @brief returns the number of expected bytes following in UTF-8 string
  5529. @param[in] u the first byte of a UTF-8 string
  5530. @return the number of expected bytes following
  5531. */
  5532. static constexpr std::size_t bytes_following(const uint8_t u)
  5533. {
  5534. return ((0 <= u and u <= 127) ? 0
  5535. : ((192 <= u and u <= 223) ? 1
  5536. : ((224 <= u and u <= 239) ? 2
  5537. : ((240 <= u and u <= 247) ? 3 : std::string::npos))));
  5538. }
  5539. /*!
  5540. @brief calculates the extra space to escape a JSON string
  5541. @param[in] s the string to escape
  5542. @param[in] ensure_ascii whether to escape non-ASCII characters with
  5543. \uXXXX sequences
  5544. @return the number of characters required to escape string @a s
  5545. @complexity Linear in the length of string @a s.
  5546. */
  5547. static std::size_t extra_space(const string_t& s,
  5548. const bool ensure_ascii) noexcept
  5549. {
  5550. std::size_t res = 0;
  5551. for (std::size_t i = 0; i < s.size(); ++i)
  5552. {
  5553. switch (s[i])
  5554. {
  5555. // control characters that can be escaped with a backslash
  5556. case '"':
  5557. case '\\':
  5558. case '\b':
  5559. case '\f':
  5560. case '\n':
  5561. case '\r':
  5562. case '\t':
  5563. {
  5564. // from c (1 byte) to \x (2 bytes)
  5565. res += 1;
  5566. break;
  5567. }
  5568. // control characters that need \uxxxx escaping
  5569. case 0x00:
  5570. case 0x01:
  5571. case 0x02:
  5572. case 0x03:
  5573. case 0x04:
  5574. case 0x05:
  5575. case 0x06:
  5576. case 0x07:
  5577. case 0x0b:
  5578. case 0x0e:
  5579. case 0x0f:
  5580. case 0x10:
  5581. case 0x11:
  5582. case 0x12:
  5583. case 0x13:
  5584. case 0x14:
  5585. case 0x15:
  5586. case 0x16:
  5587. case 0x17:
  5588. case 0x18:
  5589. case 0x19:
  5590. case 0x1a:
  5591. case 0x1b:
  5592. case 0x1c:
  5593. case 0x1d:
  5594. case 0x1e:
  5595. case 0x1f:
  5596. {
  5597. // from c (1 byte) to \uxxxx (6 bytes)
  5598. res += 5;
  5599. break;
  5600. }
  5601. default:
  5602. {
  5603. if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))
  5604. {
  5605. const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
  5606. if (bytes == std::string::npos)
  5607. {
  5608. // invalid characters are treated as is, so no
  5609. // additional space will be used
  5610. break;
  5611. }
  5612. if (bytes == 3)
  5613. {
  5614. // codepoints that need 4 bytes (i.e., 3 additional
  5615. // bytes) in UTF-8 need a surrogate pair when \u
  5616. // escaping is used: from 4 bytes to \uxxxx\uxxxx
  5617. // (12 bytes)
  5618. res += (12 - bytes - 1);
  5619. }
  5620. else
  5621. {
  5622. // from x bytes to \uxxxx (6 bytes)
  5623. res += (6 - bytes - 1);
  5624. }
  5625. // skip the additional bytes
  5626. i += bytes;
  5627. }
  5628. break;
  5629. }
  5630. }
  5631. }
  5632. return res;
  5633. }
  5634. static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)
  5635. {
  5636. // expecting a proper codepoint
  5637. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  5638. // the last written character was the backslash before the 'u'
  5639. assert(result[pos] == '\\');
  5640. // write the 'u'
  5641. result[++pos] = 'u';
  5642. // convert a number 0..15 to its hex representation (0..f)
  5643. static const std::array<char, 16> hexify =
  5644. {
  5645. {
  5646. '0', '1', '2', '3', '4', '5', '6', '7',
  5647. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  5648. }
  5649. };
  5650. if (codepoint < 0x10000)
  5651. {
  5652. // codepoints U+0000..U+FFFF can be represented as \uxxxx.
  5653. result[++pos] = hexify[(codepoint >> 12) & 0x0F];
  5654. result[++pos] = hexify[(codepoint >> 8) & 0x0F];
  5655. result[++pos] = hexify[(codepoint >> 4) & 0x0F];
  5656. result[++pos] = hexify[codepoint & 0x0F];
  5657. }
  5658. else
  5659. {
  5660. // codepoints U+10000..U+10FFFF need a surrogate pair to be
  5661. // represented as \uxxxx\uxxxx.
  5662. // http://www.unicode.org/faq/utf_bom.html#utf16-4
  5663. codepoint -= 0x10000;
  5664. const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);
  5665. const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);
  5666. result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];
  5667. result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];
  5668. result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];
  5669. result[++pos] = hexify[high_surrogate & 0x0F];
  5670. ++pos; // backslash is already in output
  5671. result[++pos] = 'u';
  5672. result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];
  5673. result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];
  5674. result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];
  5675. result[++pos] = hexify[low_surrogate & 0x0F];
  5676. }
  5677. ++pos;
  5678. }
  5679. /*!
  5680. @brief dump escaped string
  5681. Escape a string by replacing certain special characters by a sequence of an
  5682. escape character (backslash) and another character and other control
  5683. characters by a sequence of "\u" followed by a four-digit hex
  5684. representation. The escaped string is written to output stream @a o.
  5685. @param[in] s the string to escape
  5686. @param[in] ensure_ascii whether to escape non-ASCII characters with
  5687. \uXXXX sequences
  5688. @complexity Linear in the length of string @a s.
  5689. */
  5690. void dump_escaped(const string_t& s, const bool ensure_ascii) const
  5691. {
  5692. const auto space = extra_space(s, ensure_ascii);
  5693. if (space == 0)
  5694. {
  5695. o->write_characters(s.c_str(), s.size());
  5696. return;
  5697. }
  5698. // create a result string of necessary size
  5699. string_t result(s.size() + space, '\\');
  5700. std::size_t pos = 0;
  5701. for (std::size_t i = 0; i < s.size(); ++i)
  5702. {
  5703. switch (s[i])
  5704. {
  5705. case '"': // quotation mark (0x22)
  5706. {
  5707. result[pos + 1] = '"';
  5708. pos += 2;
  5709. break;
  5710. }
  5711. case '\\': // reverse solidus (0x5c)
  5712. {
  5713. // nothing to change
  5714. pos += 2;
  5715. break;
  5716. }
  5717. case '\b': // backspace (0x08)
  5718. {
  5719. result[pos + 1] = 'b';
  5720. pos += 2;
  5721. break;
  5722. }
  5723. case '\f': // formfeed (0x0c)
  5724. {
  5725. result[pos + 1] = 'f';
  5726. pos += 2;
  5727. break;
  5728. }
  5729. case '\n': // newline (0x0a)
  5730. {
  5731. result[pos + 1] = 'n';
  5732. pos += 2;
  5733. break;
  5734. }
  5735. case '\r': // carriage return (0x0d)
  5736. {
  5737. result[pos + 1] = 'r';
  5738. pos += 2;
  5739. break;
  5740. }
  5741. case '\t': // horizontal tab (0x09)
  5742. {
  5743. result[pos + 1] = 't';
  5744. pos += 2;
  5745. break;
  5746. }
  5747. default:
  5748. {
  5749. // escape control characters (0x00..0x1F) or, if
  5750. // ensure_ascii parameter is used, non-ASCII characters
  5751. if ((0x00 <= s[i] and s[i] <= 0x1F) or
  5752. (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))
  5753. {
  5754. const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));
  5755. if (bytes == std::string::npos)
  5756. {
  5757. // copy invalid character as is
  5758. result[pos++] = s[i];
  5759. break;
  5760. }
  5761. // check that the additional bytes are present
  5762. assert(i + bytes < s.size());
  5763. // to use \uxxxx escaping, we first need to caluclate
  5764. // the codepoint from the UTF-8 bytes
  5765. int codepoint = 0;
  5766. assert(0 <= bytes and bytes <= 3);
  5767. switch (bytes)
  5768. {
  5769. case 0:
  5770. {
  5771. codepoint = s[i] & 0xFF;
  5772. break;
  5773. }
  5774. case 1:
  5775. {
  5776. codepoint = ((s[i] & 0x3F) << 6)
  5777. + (s[i + 1] & 0x7F);
  5778. break;
  5779. }
  5780. case 2:
  5781. {
  5782. codepoint = ((s[i] & 0x1F) << 12)
  5783. + ((s[i + 1] & 0x7F) << 6)
  5784. + (s[i + 2] & 0x7F);
  5785. break;
  5786. }
  5787. case 3:
  5788. {
  5789. codepoint = ((s[i] & 0xF) << 18)
  5790. + ((s[i + 1] & 0x7F) << 12)
  5791. + ((s[i + 2] & 0x7F) << 6)
  5792. + (s[i + 3] & 0x7F);
  5793. break;
  5794. }
  5795. default:
  5796. break; // LCOV_EXCL_LINE
  5797. }
  5798. escape_codepoint(codepoint, result, pos);
  5799. i += bytes;
  5800. }
  5801. else
  5802. {
  5803. // all other characters are added as-is
  5804. result[pos++] = s[i];
  5805. }
  5806. break;
  5807. }
  5808. }
  5809. }
  5810. assert(pos == result.size());
  5811. o->write_characters(result.c_str(), result.size());
  5812. }
  5813. /*!
  5814. @brief dump an integer
  5815. Dump a given integer to output stream @a o. Works internally with
  5816. @a number_buffer.
  5817. @param[in] x integer number (signed or unsigned) to dump
  5818. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  5819. */
  5820. template <
  5821. typename NumberType,
  5822. detail::enable_if_t<std::is_same<NumberType, number_unsigned_t>::value or
  5823. std::is_same<NumberType, number_integer_t>::value,
  5824. int> = 0 >
  5825. void dump_integer(NumberType x)
  5826. {
  5827. // special case for "0"
  5828. if (x == 0)
  5829. {
  5830. o->write_character('0');
  5831. return;
  5832. }
  5833. const bool is_negative = x < 0;
  5834. std::size_t i = 0;
  5835. // spare 1 byte for '\0'
  5836. while (x != 0 and i < number_buffer.size() - 1)
  5837. {
  5838. const auto digit = std::labs(static_cast<long>(x % 10));
  5839. number_buffer[i++] = static_cast<char>('0' + digit);
  5840. x /= 10;
  5841. }
  5842. // make sure the number has been processed completely
  5843. assert(x == 0);
  5844. if (is_negative)
  5845. {
  5846. // make sure there is capacity for the '-'
  5847. assert(i < number_buffer.size() - 2);
  5848. number_buffer[i++] = '-';
  5849. }
  5850. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  5851. o->write_characters(number_buffer.data(), i);
  5852. }
  5853. /*!
  5854. @brief dump a floating-point number
  5855. Dump a given floating-point number to output stream @a o. Works internally
  5856. with @a number_buffer.
  5857. @param[in] x floating-point number to dump
  5858. */
  5859. void dump_float(number_float_t x)
  5860. {
  5861. // NaN / inf
  5862. if (not std::isfinite(x) or std::isnan(x))
  5863. {
  5864. o->write_characters("null", 4);
  5865. return;
  5866. }
  5867. // special case for 0.0 and -0.0
  5868. if (x == 0)
  5869. {
  5870. if (std::signbit(x))
  5871. {
  5872. o->write_characters("-0.0", 4);
  5873. }
  5874. else
  5875. {
  5876. o->write_characters("0.0", 3);
  5877. }
  5878. return;
  5879. }
  5880. // get number of digits for a text -> float -> text round-trip
  5881. static constexpr auto d = std::numeric_limits<number_float_t>::digits10;
  5882. // the actual conversion
  5883. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  5884. // negative value indicates an error
  5885. assert(len > 0);
  5886. // check if buffer was large enough
  5887. assert(static_cast<std::size_t>(len) < number_buffer.size());
  5888. // erase thousands separator
  5889. if (thousands_sep != '\0')
  5890. {
  5891. const auto end = std::remove(number_buffer.begin(),
  5892. number_buffer.begin() + len, thousands_sep);
  5893. std::fill(end, number_buffer.end(), '\0');
  5894. assert((end - number_buffer.begin()) <= len);
  5895. len = (end - number_buffer.begin());
  5896. }
  5897. // convert decimal point to '.'
  5898. if (decimal_point != '\0' and decimal_point != '.')
  5899. {
  5900. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  5901. if (dec_pos != number_buffer.end())
  5902. {
  5903. *dec_pos = '.';
  5904. }
  5905. }
  5906. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  5907. // determine if need to append ".0"
  5908. const bool value_is_int_like =
  5909. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  5910. [](char c)
  5911. {
  5912. return (c == '.' or c == 'e');
  5913. });
  5914. if (value_is_int_like)
  5915. {
  5916. o->write_characters(".0", 2);
  5917. }
  5918. }
  5919. private:
  5920. /// the output of the serializer
  5921. output_adapter_t<char> o = nullptr;
  5922. /// a (hopefully) large enough character buffer
  5923. std::array<char, 64> number_buffer{{}};
  5924. /// the locale
  5925. const std::lconv* loc = nullptr;
  5926. /// the locale's thousand separator character
  5927. const char thousands_sep = '\0';
  5928. /// the locale's decimal point character
  5929. const char decimal_point = '\0';
  5930. /// the indentation character
  5931. const char indent_char;
  5932. /// the indentation string
  5933. string_t indent_string;
  5934. };
  5935. template<typename BasicJsonType>
  5936. class json_ref
  5937. {
  5938. public:
  5939. using value_type = BasicJsonType;
  5940. json_ref(value_type&& value)
  5941. : owned_value(std::move(value)),
  5942. value_ref(&owned_value),
  5943. is_rvalue(true)
  5944. {}
  5945. json_ref(const value_type& value)
  5946. : value_ref(const_cast<value_type*>(&value)),
  5947. is_rvalue(false)
  5948. {}
  5949. json_ref(std::initializer_list<json_ref> init)
  5950. : owned_value(init),
  5951. value_ref(&owned_value),
  5952. is_rvalue(true)
  5953. {}
  5954. template <class... Args>
  5955. json_ref(Args... args)
  5956. : owned_value(std::forward<Args>(args)...),
  5957. value_ref(&owned_value),
  5958. is_rvalue(true)
  5959. {}
  5960. // class should be movable only
  5961. json_ref(json_ref&&) = default;
  5962. json_ref(const json_ref&) = delete;
  5963. json_ref& operator=(const json_ref&) = delete;
  5964. value_type moved_or_copied() const
  5965. {
  5966. if (is_rvalue)
  5967. {
  5968. return std::move(*value_ref);
  5969. }
  5970. return *value_ref;
  5971. }
  5972. value_type const& operator*() const
  5973. {
  5974. return *static_cast<value_type const*>(value_ref);
  5975. }
  5976. value_type const* operator->() const
  5977. {
  5978. return static_cast<value_type const*>(value_ref);
  5979. }
  5980. private:
  5981. mutable value_type owned_value = nullptr;
  5982. value_type* value_ref = nullptr;
  5983. const bool is_rvalue;
  5984. };
  5985. } // namespace detail
  5986. /// namespace to hold default `to_json` / `from_json` functions
  5987. namespace
  5988. {
  5989. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  5990. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  5991. }
  5992. /*!
  5993. @brief default JSONSerializer template argument
  5994. This serializer ignores the template arguments and uses ADL
  5995. ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
  5996. for serialization.
  5997. */
  5998. template<typename, typename>
  5999. struct adl_serializer
  6000. {
  6001. /*!
  6002. @brief convert a JSON value to any value type
  6003. This function is usually called by the `get()` function of the
  6004. @ref basic_json class (either explicit or via conversion operators).
  6005. @param[in] j JSON value to read from
  6006. @param[in,out] val value to write to
  6007. */
  6008. template<typename BasicJsonType, typename ValueType>
  6009. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  6010. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  6011. {
  6012. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  6013. }
  6014. /*!
  6015. @brief convert any value type to a JSON value
  6016. This function is usually called by the constructors of the @ref basic_json
  6017. class.
  6018. @param[in,out] j JSON value to write to
  6019. @param[in] val value to read from
  6020. */
  6021. template<typename BasicJsonType, typename ValueType>
  6022. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  6023. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  6024. {
  6025. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  6026. }
  6027. };
  6028. /*!
  6029. @brief JSON Pointer
  6030. A JSON pointer defines a string syntax for identifying a specific value
  6031. within a JSON document. It can be used with functions `at` and
  6032. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  6033. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  6034. @since version 2.0.0
  6035. */
  6036. class json_pointer
  6037. {
  6038. /// allow basic_json to access private members
  6039. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6040. friend class basic_json;
  6041. public:
  6042. /*!
  6043. @brief create JSON pointer
  6044. Create a JSON pointer according to the syntax described in
  6045. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  6046. @param[in] s string representing the JSON pointer; if omitted, the empty
  6047. string is assumed which references the whole JSON value
  6048. @throw parse_error.107 if the given JSON pointer @a s is nonempty and
  6049. does not begin with a slash (`/`); see example below
  6050. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s
  6051. is not followed by `0` (representing `~`) or `1` (representing `/`);
  6052. see example below
  6053. @liveexample{The example shows the construction several valid JSON
  6054. pointers as well as the exceptional behavior.,json_pointer}
  6055. @since version 2.0.0
  6056. */
  6057. explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {}
  6058. /*!
  6059. @brief return a string representation of the JSON pointer
  6060. @invariant For each JSON pointer `ptr`, it holds:
  6061. @code {.cpp}
  6062. ptr == json_pointer(ptr.to_string());
  6063. @endcode
  6064. @return a string representation of the JSON pointer
  6065. @liveexample{The example shows the result of `to_string`.,
  6066. json_pointer__to_string}
  6067. @since version 2.0.0
  6068. */
  6069. std::string to_string() const noexcept
  6070. {
  6071. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  6072. std::string{},
  6073. [](const std::string & a, const std::string & b)
  6074. {
  6075. return a + "/" + escape(b);
  6076. });
  6077. }
  6078. /// @copydoc to_string()
  6079. operator std::string() const
  6080. {
  6081. return to_string();
  6082. }
  6083. private:
  6084. /*!
  6085. @brief remove and return last reference pointer
  6086. @throw out_of_range.405 if JSON pointer has no parent
  6087. */
  6088. std::string pop_back()
  6089. {
  6090. if (JSON_UNLIKELY(is_root()))
  6091. {
  6092. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  6093. }
  6094. auto last = reference_tokens.back();
  6095. reference_tokens.pop_back();
  6096. return last;
  6097. }
  6098. /// return whether pointer points to the root document
  6099. bool is_root() const
  6100. {
  6101. return reference_tokens.empty();
  6102. }
  6103. json_pointer top() const
  6104. {
  6105. if (JSON_UNLIKELY(is_root()))
  6106. {
  6107. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  6108. }
  6109. json_pointer result = *this;
  6110. result.reference_tokens = {reference_tokens[0]};
  6111. return result;
  6112. }
  6113. /*!
  6114. @brief create and return a reference to the pointed to value
  6115. @complexity Linear in the number of reference tokens.
  6116. @throw parse_error.109 if array index is not a number
  6117. @throw type_error.313 if value cannot be unflattened
  6118. */
  6119. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6120. NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;
  6121. /*!
  6122. @brief return a reference to the pointed to value
  6123. @note This version does not throw if a value is not present, but tries to
  6124. create nested values instead. For instance, calling this function
  6125. with pointer `"/this/that"` on a null value is equivalent to calling
  6126. `operator[]("this").operator[]("that")` on that value, effectively
  6127. changing the null value to an object.
  6128. @param[in] ptr a JSON value
  6129. @return reference to the JSON value pointed to by the JSON pointer
  6130. @complexity Linear in the length of the JSON pointer.
  6131. @throw parse_error.106 if an array index begins with '0'
  6132. @throw parse_error.109 if an array index was not a number
  6133. @throw out_of_range.404 if the JSON pointer can not be resolved
  6134. */
  6135. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6136. NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6137. /*!
  6138. @throw parse_error.106 if an array index begins with '0'
  6139. @throw parse_error.109 if an array index was not a number
  6140. @throw out_of_range.402 if the array index '-' is used
  6141. @throw out_of_range.404 if the JSON pointer can not be resolved
  6142. */
  6143. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6144. NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6145. /*!
  6146. @brief return a const reference to the pointed to value
  6147. @param[in] ptr a JSON value
  6148. @return const reference to the JSON value pointed to by the JSON
  6149. pointer
  6150. @throw parse_error.106 if an array index begins with '0'
  6151. @throw parse_error.109 if an array index was not a number
  6152. @throw out_of_range.402 if the array index '-' is used
  6153. @throw out_of_range.404 if the JSON pointer can not be resolved
  6154. */
  6155. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6156. const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6157. /*!
  6158. @throw parse_error.106 if an array index begins with '0'
  6159. @throw parse_error.109 if an array index was not a number
  6160. @throw out_of_range.402 if the array index '-' is used
  6161. @throw out_of_range.404 if the JSON pointer can not be resolved
  6162. */
  6163. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6164. const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;
  6165. /*!
  6166. @brief split the string input to reference tokens
  6167. @note This function is only called by the json_pointer constructor.
  6168. All exceptions below are documented there.
  6169. @throw parse_error.107 if the pointer is not empty or begins with '/'
  6170. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  6171. */
  6172. static std::vector<std::string> split(const std::string& reference_string)
  6173. {
  6174. std::vector<std::string> result;
  6175. // special case: empty reference string -> no reference tokens
  6176. if (reference_string.empty())
  6177. {
  6178. return result;
  6179. }
  6180. // check if nonempty reference string begins with slash
  6181. if (JSON_UNLIKELY(reference_string[0] != '/'))
  6182. {
  6183. JSON_THROW(detail::parse_error::create(107, 1,
  6184. "JSON pointer must be empty or begin with '/' - was: '" +
  6185. reference_string + "'"));
  6186. }
  6187. // extract the reference tokens:
  6188. // - slash: position of the last read slash (or end of string)
  6189. // - start: position after the previous slash
  6190. for (
  6191. // search for the first slash after the first character
  6192. std::size_t slash = reference_string.find_first_of('/', 1),
  6193. // set the beginning of the first reference token
  6194. start = 1;
  6195. // we can stop if start == string::npos+1 = 0
  6196. start != 0;
  6197. // set the beginning of the next reference token
  6198. // (will eventually be 0 if slash == std::string::npos)
  6199. start = slash + 1,
  6200. // find next slash
  6201. slash = reference_string.find_first_of('/', start))
  6202. {
  6203. // use the text between the beginning of the reference token
  6204. // (start) and the last slash (slash).
  6205. auto reference_token = reference_string.substr(start, slash - start);
  6206. // check reference tokens are properly escaped
  6207. for (std::size_t pos = reference_token.find_first_of('~');
  6208. pos != std::string::npos;
  6209. pos = reference_token.find_first_of('~', pos + 1))
  6210. {
  6211. assert(reference_token[pos] == '~');
  6212. // ~ must be followed by 0 or 1
  6213. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  6214. (reference_token[pos + 1] != '0' and
  6215. reference_token[pos + 1] != '1')))
  6216. {
  6217. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  6218. }
  6219. }
  6220. // finally, store the reference token
  6221. unescape(reference_token);
  6222. result.push_back(reference_token);
  6223. }
  6224. return result;
  6225. }
  6226. /*!
  6227. @brief replace all occurrences of a substring by another string
  6228. @param[in,out] s the string to manipulate; changed so that all
  6229. occurrences of @a f are replaced with @a t
  6230. @param[in] f the substring to replace with @a t
  6231. @param[in] t the string to replace @a f
  6232. @pre The search string @a f must not be empty. **This precondition is
  6233. enforced with an assertion.**
  6234. @since version 2.0.0
  6235. */
  6236. static void replace_substring(std::string& s, const std::string& f,
  6237. const std::string& t)
  6238. {
  6239. assert(not f.empty());
  6240. for (auto pos = s.find(f); // find first occurrence of f
  6241. pos != std::string::npos; // make sure f was found
  6242. s.replace(pos, f.size(), t), // replace with t, and
  6243. pos = s.find(f, pos + t.size())) // find next occurrence of f
  6244. {}
  6245. }
  6246. /// escape "~"" to "~0" and "/" to "~1"
  6247. static std::string escape(std::string s)
  6248. {
  6249. replace_substring(s, "~", "~0");
  6250. replace_substring(s, "/", "~1");
  6251. return s;
  6252. }
  6253. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  6254. static void unescape(std::string& s)
  6255. {
  6256. replace_substring(s, "~1", "/");
  6257. replace_substring(s, "~0", "~");
  6258. }
  6259. /*!
  6260. @param[in] reference_string the reference string to the current value
  6261. @param[in] value the value to consider
  6262. @param[in,out] result the result object to insert values to
  6263. @note Empty objects or arrays are flattened to `null`.
  6264. */
  6265. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6266. static void flatten(const std::string& reference_string,
  6267. const NLOHMANN_BASIC_JSON_TPL& value,
  6268. NLOHMANN_BASIC_JSON_TPL& result);
  6269. /*!
  6270. @param[in] value flattened JSON
  6271. @return unflattened JSON
  6272. @throw parse_error.109 if array index is not a number
  6273. @throw type_error.314 if value is not an object
  6274. @throw type_error.315 if object values are not primitive
  6275. @throw type_error.313 if value cannot be unflattened
  6276. */
  6277. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6278. static NLOHMANN_BASIC_JSON_TPL
  6279. unflatten(const NLOHMANN_BASIC_JSON_TPL& value);
  6280. friend bool operator==(json_pointer const& lhs,
  6281. json_pointer const& rhs) noexcept;
  6282. friend bool operator!=(json_pointer const& lhs,
  6283. json_pointer const& rhs) noexcept;
  6284. /// the reference tokens
  6285. std::vector<std::string> reference_tokens;
  6286. };
  6287. /*!
  6288. @brief a class to store JSON values
  6289. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  6290. in @ref object_t)
  6291. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  6292. in @ref array_t)
  6293. @tparam StringType type for JSON strings and object keys (`std::string` by
  6294. default; will be used in @ref string_t)
  6295. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  6296. in @ref boolean_t)
  6297. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  6298. default; will be used in @ref number_integer_t)
  6299. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  6300. `uint64_t` by default; will be used in @ref number_unsigned_t)
  6301. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  6302. default; will be used in @ref number_float_t)
  6303. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  6304. default)
  6305. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  6306. and `from_json()` (@ref adl_serializer by default)
  6307. @requirement The class satisfies the following concept requirements:
  6308. - Basic
  6309. - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
  6310. JSON values can be default constructed. The result will be a JSON null
  6311. value.
  6312. - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
  6313. A JSON value can be constructed from an rvalue argument.
  6314. - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
  6315. A JSON value can be copy-constructed from an lvalue expression.
  6316. - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
  6317. A JSON value van be assigned from an rvalue argument.
  6318. - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
  6319. A JSON value can be copy-assigned from an lvalue expression.
  6320. - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
  6321. JSON values can be destructed.
  6322. - Layout
  6323. - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
  6324. JSON values have
  6325. [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  6326. All non-static data members are private and standard layout types, the
  6327. class has no virtual functions or (virtual) base classes.
  6328. - Library-wide
  6329. - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
  6330. JSON values can be compared with `==`, see @ref
  6331. operator==(const_reference,const_reference).
  6332. - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
  6333. JSON values can be compared with `<`, see @ref
  6334. operator<(const_reference,const_reference).
  6335. - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
  6336. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  6337. other compatible types, using unqualified function call @ref swap().
  6338. - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
  6339. JSON values can be compared against `std::nullptr_t` objects which are used
  6340. to model the `null` value.
  6341. - Container
  6342. - [Container](http://en.cppreference.com/w/cpp/concept/Container):
  6343. JSON values can be used like STL containers and provide iterator access.
  6344. - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
  6345. JSON values can be used like STL containers and provide reverse iterator
  6346. access.
  6347. @invariant The member variables @a m_value and @a m_type have the following
  6348. relationship:
  6349. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  6350. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  6351. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  6352. The invariants are checked by member function assert_invariant().
  6353. @internal
  6354. @note ObjectType trick from http://stackoverflow.com/a/9860911
  6355. @endinternal
  6356. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  6357. Format](http://rfc7159.net/rfc7159)
  6358. @since version 1.0.0
  6359. @nosubgrouping
  6360. */
  6361. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  6362. class basic_json
  6363. {
  6364. private:
  6365. template<detail::value_t> friend struct detail::external_constructor;
  6366. friend ::nlohmann::json_pointer;
  6367. friend ::nlohmann::detail::parser<basic_json>;
  6368. friend ::nlohmann::detail::serializer<basic_json>;
  6369. template<typename BasicJsonType>
  6370. friend class ::nlohmann::detail::iter_impl;
  6371. template<typename BasicJsonType, typename CharType>
  6372. friend class ::nlohmann::detail::binary_writer;
  6373. template<typename BasicJsonType>
  6374. friend class ::nlohmann::detail::binary_reader;
  6375. /// workaround type for MSVC
  6376. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  6377. // convenience aliases for types residing in namespace detail;
  6378. using lexer = ::nlohmann::detail::lexer<basic_json>;
  6379. using parser = ::nlohmann::detail::parser<basic_json>;
  6380. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  6381. template<typename BasicJsonType>
  6382. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  6383. template<typename BasicJsonType>
  6384. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  6385. template<typename Iterator>
  6386. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  6387. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  6388. template<typename CharType>
  6389. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  6390. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  6391. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  6392. using serializer = ::nlohmann::detail::serializer<basic_json>;
  6393. public:
  6394. using value_t = detail::value_t;
  6395. // forward declarations
  6396. using json_pointer = ::nlohmann::json_pointer;
  6397. template<typename T, typename SFINAE>
  6398. using json_serializer = JSONSerializer<T, SFINAE>;
  6399. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  6400. ////////////////
  6401. // exceptions //
  6402. ////////////////
  6403. /// @name exceptions
  6404. /// Classes to implement user-defined exceptions.
  6405. /// @{
  6406. /// @copydoc detail::exception
  6407. using exception = detail::exception;
  6408. /// @copydoc detail::parse_error
  6409. using parse_error = detail::parse_error;
  6410. /// @copydoc detail::invalid_iterator
  6411. using invalid_iterator = detail::invalid_iterator;
  6412. /// @copydoc detail::type_error
  6413. using type_error = detail::type_error;
  6414. /// @copydoc detail::out_of_range
  6415. using out_of_range = detail::out_of_range;
  6416. /// @copydoc detail::other_error
  6417. using other_error = detail::other_error;
  6418. /// @}
  6419. /////////////////////
  6420. // container types //
  6421. /////////////////////
  6422. /// @name container types
  6423. /// The canonic container types to use @ref basic_json like any other STL
  6424. /// container.
  6425. /// @{
  6426. /// the type of elements in a basic_json container
  6427. using value_type = basic_json;
  6428. /// the type of an element reference
  6429. using reference = value_type&;
  6430. /// the type of an element const reference
  6431. using const_reference = const value_type&;
  6432. /// a type to represent differences between iterators
  6433. using difference_type = std::ptrdiff_t;
  6434. /// a type to represent container sizes
  6435. using size_type = std::size_t;
  6436. /// the allocator type
  6437. using allocator_type = AllocatorType<basic_json>;
  6438. /// the type of an element pointer
  6439. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  6440. /// the type of an element const pointer
  6441. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  6442. /// an iterator for a basic_json container
  6443. using iterator = iter_impl<basic_json>;
  6444. /// a const iterator for a basic_json container
  6445. using const_iterator = iter_impl<const basic_json>;
  6446. /// a reverse iterator for a basic_json container
  6447. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  6448. /// a const reverse iterator for a basic_json container
  6449. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  6450. /// @}
  6451. /*!
  6452. @brief returns the allocator associated with the container
  6453. */
  6454. static allocator_type get_allocator()
  6455. {
  6456. return allocator_type();
  6457. }
  6458. /*!
  6459. @brief returns version information on the library
  6460. This function returns a JSON object with information about the library,
  6461. including the version number and information on the platform and compiler.
  6462. @return JSON object holding version information
  6463. key | description
  6464. ----------- | ---------------
  6465. `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
  6466. `copyright` | The copyright line for the library as string.
  6467. `name` | The name of the library as string.
  6468. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  6469. `url` | The URL of the project as string.
  6470. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
  6471. @liveexample{The following code shows an example output of the `meta()`
  6472. function.,meta}
  6473. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  6474. changes to any JSON value.
  6475. @complexity Constant.
  6476. @since 2.1.0
  6477. */
  6478. static basic_json meta()
  6479. {
  6480. basic_json result;
  6481. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  6482. result["name"] = "JSON for Modern C++";
  6483. result["url"] = "https://github.com/nlohmann/json";
  6484. result["version"] =
  6485. {
  6486. {"string", "2.1.1"}, {"major", 2}, {"minor", 1}, {"patch", 1}
  6487. };
  6488. #ifdef _WIN32
  6489. result["platform"] = "win32";
  6490. #elif defined __linux__
  6491. result["platform"] = "linux";
  6492. #elif defined __APPLE__
  6493. result["platform"] = "apple";
  6494. #elif defined __unix__
  6495. result["platform"] = "unix";
  6496. #else
  6497. result["platform"] = "unknown";
  6498. #endif
  6499. #if defined(__ICC) || defined(__INTEL_COMPILER)
  6500. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  6501. #elif defined(__clang__)
  6502. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  6503. #elif defined(__GNUC__) || defined(__GNUG__)
  6504. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  6505. #elif defined(__HP_cc) || defined(__HP_aCC)
  6506. result["compiler"] = "hp"
  6507. #elif defined(__IBMCPP__)
  6508. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  6509. #elif defined(_MSC_VER)
  6510. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  6511. #elif defined(__PGI)
  6512. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  6513. #elif defined(__SUNPRO_CC)
  6514. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  6515. #else
  6516. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  6517. #endif
  6518. #ifdef __cplusplus
  6519. result["compiler"]["c++"] = std::to_string(__cplusplus);
  6520. #else
  6521. result["compiler"]["c++"] = "unknown";
  6522. #endif
  6523. return result;
  6524. }
  6525. ///////////////////////////
  6526. // JSON value data types //
  6527. ///////////////////////////
  6528. /// @name JSON value data types
  6529. /// The data types to store a JSON value. These types are derived from
  6530. /// the template arguments passed to class @ref basic_json.
  6531. /// @{
  6532. /*!
  6533. @brief a type for an object
  6534. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  6535. > An object is an unordered collection of zero or more name/value pairs,
  6536. > where a name is a string and a value is a string, number, boolean, null,
  6537. > object, or array.
  6538. To store objects in C++, a type is defined by the template parameters
  6539. described below.
  6540. @tparam ObjectType the container to store objects (e.g., `std::map` or
  6541. `std::unordered_map`)
  6542. @tparam StringType the type of the keys or names (e.g., `std::string`).
  6543. The comparison function `std::less<StringType>` is used to order elements
  6544. inside the container.
  6545. @tparam AllocatorType the allocator to use for objects (e.g.,
  6546. `std::allocator`)
  6547. #### Default type
  6548. With the default values for @a ObjectType (`std::map`), @a StringType
  6549. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  6550. value for @a object_t is:
  6551. @code {.cpp}
  6552. std::map<
  6553. std::string, // key_type
  6554. basic_json, // value_type
  6555. std::less<std::string>, // key_compare
  6556. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  6557. >
  6558. @endcode
  6559. #### Behavior
  6560. The choice of @a object_t influences the behavior of the JSON class. With
  6561. the default type, objects have the following behavior:
  6562. - When all names are unique, objects will be interoperable in the sense
  6563. that all software implementations receiving that object will agree on
  6564. the name-value mappings.
  6565. - When the names within an object are not unique, later stored name/value
  6566. pairs overwrite previously stored name/value pairs, leaving the used
  6567. names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
  6568. be treated as equal and both stored as `{"key": 1}`.
  6569. - Internally, name/value pairs are stored in lexicographical order of the
  6570. names. Objects will also be serialized (see @ref dump) in this order.
  6571. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  6572. and serialized as `{"a": 2, "b": 1}`.
  6573. - When comparing objects, the order of the name/value pairs is irrelevant.
  6574. This makes objects interoperable in the sense that they will not be
  6575. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  6576. `{"a": 2, "b": 1}` will be treated as equal.
  6577. #### Limits
  6578. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6579. > An implementation may set limits on the maximum depth of nesting.
  6580. In this class, the object's limit of nesting is not explicitly constrained.
  6581. However, a maximum depth of nesting may be introduced by the compiler or
  6582. runtime environment. A theoretical limit can be queried by calling the
  6583. @ref max_size function of a JSON object.
  6584. #### Storage
  6585. Objects are stored as pointers in a @ref basic_json type. That is, for any
  6586. access to object values, a pointer of type `object_t*` must be
  6587. dereferenced.
  6588. @sa @ref array_t -- type for an array value
  6589. @since version 1.0.0
  6590. @note The order name/value pairs are added to the object is *not*
  6591. preserved by the library. Therefore, iterating an object may return
  6592. name/value pairs in a different order than they were originally stored. In
  6593. fact, keys will be traversed in alphabetical order as `std::map` with
  6594. `std::less` is used by default. Please note this behavior conforms to [RFC
  6595. 7159](http://rfc7159.net/rfc7159), because any order implements the
  6596. specified "unordered" nature of JSON objects.
  6597. */
  6598. using object_t = ObjectType<StringType,
  6599. basic_json,
  6600. std::less<StringType>,
  6601. AllocatorType<std::pair<const StringType,
  6602. basic_json>>>;
  6603. /*!
  6604. @brief a type for an array
  6605. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  6606. > An array is an ordered sequence of zero or more values.
  6607. To store objects in C++, a type is defined by the template parameters
  6608. explained below.
  6609. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  6610. `std::list`)
  6611. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  6612. #### Default type
  6613. With the default values for @a ArrayType (`std::vector`) and @a
  6614. AllocatorType (`std::allocator`), the default value for @a array_t is:
  6615. @code {.cpp}
  6616. std::vector<
  6617. basic_json, // value_type
  6618. std::allocator<basic_json> // allocator_type
  6619. >
  6620. @endcode
  6621. #### Limits
  6622. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6623. > An implementation may set limits on the maximum depth of nesting.
  6624. In this class, the array's limit of nesting is not explicitly constrained.
  6625. However, a maximum depth of nesting may be introduced by the compiler or
  6626. runtime environment. A theoretical limit can be queried by calling the
  6627. @ref max_size function of a JSON array.
  6628. #### Storage
  6629. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  6630. access to array values, a pointer of type `array_t*` must be dereferenced.
  6631. @sa @ref object_t -- type for an object value
  6632. @since version 1.0.0
  6633. */
  6634. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  6635. /*!
  6636. @brief a type for a string
  6637. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  6638. > A string is a sequence of zero or more Unicode characters.
  6639. To store objects in C++, a type is defined by the template parameter
  6640. described below. Unicode values are split by the JSON class into
  6641. byte-sized characters during deserialization.
  6642. @tparam StringType the container to store strings (e.g., `std::string`).
  6643. Note this container is used for keys/names in objects, see @ref object_t.
  6644. #### Default type
  6645. With the default values for @a StringType (`std::string`), the default
  6646. value for @a string_t is:
  6647. @code {.cpp}
  6648. std::string
  6649. @endcode
  6650. #### Encoding
  6651. Strings are stored in UTF-8 encoding. Therefore, functions like
  6652. `std::string::size()` or `std::string::length()` return the number of
  6653. bytes in the string rather than the number of characters or glyphs.
  6654. #### String comparison
  6655. [RFC 7159](http://rfc7159.net/rfc7159) states:
  6656. > Software implementations are typically required to test names of object
  6657. > members for equality. Implementations that transform the textual
  6658. > representation into sequences of Unicode code units and then perform the
  6659. > comparison numerically, code unit by code unit, are interoperable in the
  6660. > sense that implementations will agree in all cases on equality or
  6661. > inequality of two strings. For example, implementations that compare
  6662. > strings with escaped characters unconverted may incorrectly find that
  6663. > `"a\\b"` and `"a\u005Cb"` are not equal.
  6664. This implementation is interoperable as it does compare strings code unit
  6665. by code unit.
  6666. #### Storage
  6667. String values are stored as pointers in a @ref basic_json type. That is,
  6668. for any access to string values, a pointer of type `string_t*` must be
  6669. dereferenced.
  6670. @since version 1.0.0
  6671. */
  6672. using string_t = StringType;
  6673. /*!
  6674. @brief a type for a boolean
  6675. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  6676. type which differentiates the two literals `true` and `false`.
  6677. To store objects in C++, a type is defined by the template parameter @a
  6678. BooleanType which chooses the type to use.
  6679. #### Default type
  6680. With the default values for @a BooleanType (`bool`), the default value for
  6681. @a boolean_t is:
  6682. @code {.cpp}
  6683. bool
  6684. @endcode
  6685. #### Storage
  6686. Boolean values are stored directly inside a @ref basic_json type.
  6687. @since version 1.0.0
  6688. */
  6689. using boolean_t = BooleanType;
  6690. /*!
  6691. @brief a type for a number (integer)
  6692. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6693. > The representation of numbers is similar to that used in most
  6694. > programming languages. A number is represented in base 10 using decimal
  6695. > digits. It contains an integer component that may be prefixed with an
  6696. > optional minus sign, which may be followed by a fraction part and/or an
  6697. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6698. > cannot be represented in the grammar below (such as Infinity and NaN)
  6699. > are not permitted.
  6700. This description includes both integer and floating-point numbers.
  6701. However, C++ allows more precise storage if it is known whether the number
  6702. is a signed integer, an unsigned integer or a floating-point number.
  6703. Therefore, three different types, @ref number_integer_t, @ref
  6704. number_unsigned_t and @ref number_float_t are used.
  6705. To store integer numbers in C++, a type is defined by the template
  6706. parameter @a NumberIntegerType which chooses the type to use.
  6707. #### Default type
  6708. With the default values for @a NumberIntegerType (`int64_t`), the default
  6709. value for @a number_integer_t is:
  6710. @code {.cpp}
  6711. int64_t
  6712. @endcode
  6713. #### Default behavior
  6714. - The restrictions about leading zeros is not enforced in C++. Instead,
  6715. leading zeros in integer literals lead to an interpretation as octal
  6716. number. Internally, the value will be stored as decimal number. For
  6717. instance, the C++ integer literal `010` will be serialized to `8`.
  6718. During deserialization, leading zeros yield an error.
  6719. - Not-a-number (NaN) values will be serialized to `null`.
  6720. #### Limits
  6721. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6722. > An implementation may set limits on the range and precision of numbers.
  6723. When the default type is used, the maximal integer number that can be
  6724. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  6725. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  6726. that are out of range will yield over/underflow when used in a
  6727. constructor. During deserialization, too large or small integer numbers
  6728. will be automatically be stored as @ref number_unsigned_t or @ref
  6729. number_float_t.
  6730. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  6731. > Note that when such software is used, numbers that are integers and are
  6732. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  6733. > that implementations will agree exactly on their numeric values.
  6734. As this range is a subrange of the exactly supported range [INT64_MIN,
  6735. INT64_MAX], this class's integer type is interoperable.
  6736. #### Storage
  6737. Integer number values are stored directly inside a @ref basic_json type.
  6738. @sa @ref number_float_t -- type for number values (floating-point)
  6739. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  6740. @since version 1.0.0
  6741. */
  6742. using number_integer_t = NumberIntegerType;
  6743. /*!
  6744. @brief a type for a number (unsigned)
  6745. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6746. > The representation of numbers is similar to that used in most
  6747. > programming languages. A number is represented in base 10 using decimal
  6748. > digits. It contains an integer component that may be prefixed with an
  6749. > optional minus sign, which may be followed by a fraction part and/or an
  6750. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6751. > cannot be represented in the grammar below (such as Infinity and NaN)
  6752. > are not permitted.
  6753. This description includes both integer and floating-point numbers.
  6754. However, C++ allows more precise storage if it is known whether the number
  6755. is a signed integer, an unsigned integer or a floating-point number.
  6756. Therefore, three different types, @ref number_integer_t, @ref
  6757. number_unsigned_t and @ref number_float_t are used.
  6758. To store unsigned integer numbers in C++, a type is defined by the
  6759. template parameter @a NumberUnsignedType which chooses the type to use.
  6760. #### Default type
  6761. With the default values for @a NumberUnsignedType (`uint64_t`), the
  6762. default value for @a number_unsigned_t is:
  6763. @code {.cpp}
  6764. uint64_t
  6765. @endcode
  6766. #### Default behavior
  6767. - The restrictions about leading zeros is not enforced in C++. Instead,
  6768. leading zeros in integer literals lead to an interpretation as octal
  6769. number. Internally, the value will be stored as decimal number. For
  6770. instance, the C++ integer literal `010` will be serialized to `8`.
  6771. During deserialization, leading zeros yield an error.
  6772. - Not-a-number (NaN) values will be serialized to `null`.
  6773. #### Limits
  6774. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  6775. > An implementation may set limits on the range and precision of numbers.
  6776. When the default type is used, the maximal integer number that can be
  6777. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  6778. number that can be stored is `0`. Integer numbers that are out of range
  6779. will yield over/underflow when used in a constructor. During
  6780. deserialization, too large or small integer numbers will be automatically
  6781. be stored as @ref number_integer_t or @ref number_float_t.
  6782. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  6783. > Note that when such software is used, numbers that are integers and are
  6784. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  6785. > that implementations will agree exactly on their numeric values.
  6786. As this range is a subrange (when considered in conjunction with the
  6787. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  6788. this class's integer type is interoperable.
  6789. #### Storage
  6790. Integer number values are stored directly inside a @ref basic_json type.
  6791. @sa @ref number_float_t -- type for number values (floating-point)
  6792. @sa @ref number_integer_t -- type for number values (integer)
  6793. @since version 2.0.0
  6794. */
  6795. using number_unsigned_t = NumberUnsignedType;
  6796. /*!
  6797. @brief a type for a number (floating-point)
  6798. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  6799. > The representation of numbers is similar to that used in most
  6800. > programming languages. A number is represented in base 10 using decimal
  6801. > digits. It contains an integer component that may be prefixed with an
  6802. > optional minus sign, which may be followed by a fraction part and/or an
  6803. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  6804. > cannot be represented in the grammar below (such as Infinity and NaN)
  6805. > are not permitted.
  6806. This description includes both integer and floating-point numbers.
  6807. However, C++ allows more precise storage if it is known whether the number
  6808. is a signed integer, an unsigned integer or a floating-point number.
  6809. Therefore, three different types, @ref number_integer_t, @ref
  6810. number_unsigned_t and @ref number_float_t are used.
  6811. To store floating-point numbers in C++, a type is defined by the template
  6812. parameter @a NumberFloatType which chooses the type to use.
  6813. #### Default type
  6814. With the default values for @a NumberFloatType (`double`), the default
  6815. value for @a number_float_t is:
  6816. @code {.cpp}
  6817. double
  6818. @endcode
  6819. #### Default behavior
  6820. - The restrictions about leading zeros is not enforced in C++. Instead,
  6821. leading zeros in floating-point literals will be ignored. Internally,
  6822. the value will be stored as decimal number. For instance, the C++
  6823. floating-point literal `01.2` will be serialized to `1.2`. During
  6824. deserialization, leading zeros yield an error.
  6825. - Not-a-number (NaN) values will be serialized to `null`.
  6826. #### Limits
  6827. [RFC 7159](http://rfc7159.net/rfc7159) states:
  6828. > This specification allows implementations to set limits on the range and
  6829. > precision of numbers accepted. Since software that implements IEEE
  6830. > 754-2008 binary64 (double precision) numbers is generally available and
  6831. > widely used, good interoperability can be achieved by implementations
  6832. > that expect no more precision or range than these provide, in the sense
  6833. > that implementations will approximate JSON numbers within the expected
  6834. > precision.
  6835. This implementation does exactly follow this approach, as it uses double
  6836. precision floating-point numbers. Note values smaller than
  6837. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  6838. will be stored as NaN internally and be serialized to `null`.
  6839. #### Storage
  6840. Floating-point number values are stored directly inside a @ref basic_json
  6841. type.
  6842. @sa @ref number_integer_t -- type for number values (integer)
  6843. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  6844. @since version 1.0.0
  6845. */
  6846. using number_float_t = NumberFloatType;
  6847. /// @}
  6848. private:
  6849. /// helper for exception-safe object creation
  6850. template<typename T, typename... Args>
  6851. static T* create(Args&& ... args)
  6852. {
  6853. AllocatorType<T> alloc;
  6854. auto deleter = [&](T * object)
  6855. {
  6856. alloc.deallocate(object, 1);
  6857. };
  6858. std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
  6859. alloc.construct(object.get(), std::forward<Args>(args)...);
  6860. assert(object != nullptr);
  6861. return object.release();
  6862. }
  6863. ////////////////////////
  6864. // JSON value storage //
  6865. ////////////////////////
  6866. /*!
  6867. @brief a JSON value
  6868. The actual storage for a JSON value of the @ref basic_json class. This
  6869. union combines the different storage types for the JSON value types
  6870. defined in @ref value_t.
  6871. JSON type | value_t type | used type
  6872. --------- | --------------- | ------------------------
  6873. object | object | pointer to @ref object_t
  6874. array | array | pointer to @ref array_t
  6875. string | string | pointer to @ref string_t
  6876. boolean | boolean | @ref boolean_t
  6877. number | number_integer | @ref number_integer_t
  6878. number | number_unsigned | @ref number_unsigned_t
  6879. number | number_float | @ref number_float_t
  6880. null | null | *no value is stored*
  6881. @note Variable-length types (objects, arrays, and strings) are stored as
  6882. pointers. The size of the union should not exceed 64 bits if the default
  6883. value types are used.
  6884. @since version 1.0.0
  6885. */
  6886. union json_value
  6887. {
  6888. /// object (stored with pointer to save storage)
  6889. object_t* object;
  6890. /// array (stored with pointer to save storage)
  6891. array_t* array;
  6892. /// string (stored with pointer to save storage)
  6893. string_t* string;
  6894. /// boolean
  6895. boolean_t boolean;
  6896. /// number (integer)
  6897. number_integer_t number_integer;
  6898. /// number (unsigned integer)
  6899. number_unsigned_t number_unsigned;
  6900. /// number (floating-point)
  6901. number_float_t number_float;
  6902. /// default constructor (for null values)
  6903. json_value() = default;
  6904. /// constructor for booleans
  6905. json_value(boolean_t v) noexcept : boolean(v) {}
  6906. /// constructor for numbers (integer)
  6907. json_value(number_integer_t v) noexcept : number_integer(v) {}
  6908. /// constructor for numbers (unsigned)
  6909. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  6910. /// constructor for numbers (floating-point)
  6911. json_value(number_float_t v) noexcept : number_float(v) {}
  6912. /// constructor for empty values of a given type
  6913. json_value(value_t t)
  6914. {
  6915. switch (t)
  6916. {
  6917. case value_t::object:
  6918. {
  6919. object = create<object_t>();
  6920. break;
  6921. }
  6922. case value_t::array:
  6923. {
  6924. array = create<array_t>();
  6925. break;
  6926. }
  6927. case value_t::string:
  6928. {
  6929. string = create<string_t>("");
  6930. break;
  6931. }
  6932. case value_t::boolean:
  6933. {
  6934. boolean = boolean_t(false);
  6935. break;
  6936. }
  6937. case value_t::number_integer:
  6938. {
  6939. number_integer = number_integer_t(0);
  6940. break;
  6941. }
  6942. case value_t::number_unsigned:
  6943. {
  6944. number_unsigned = number_unsigned_t(0);
  6945. break;
  6946. }
  6947. case value_t::number_float:
  6948. {
  6949. number_float = number_float_t(0.0);
  6950. break;
  6951. }
  6952. case value_t::null:
  6953. {
  6954. break;
  6955. }
  6956. default:
  6957. {
  6958. if (JSON_UNLIKELY(t == value_t::null))
  6959. {
  6960. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE
  6961. }
  6962. break;
  6963. }
  6964. }
  6965. }
  6966. /// constructor for strings
  6967. json_value(const string_t& value)
  6968. {
  6969. string = create<string_t>(value);
  6970. }
  6971. /// constructor for rvalue strings
  6972. json_value(string_t&& value)
  6973. {
  6974. string = create<string_t>(std::move(value));
  6975. }
  6976. /// constructor for objects
  6977. json_value(const object_t& value)
  6978. {
  6979. object = create<object_t>(value);
  6980. }
  6981. /// constructor for rvalue objects
  6982. json_value(object_t&& value)
  6983. {
  6984. object = create<object_t>(std::move(value));
  6985. }
  6986. /// constructor for arrays
  6987. json_value(const array_t& value)
  6988. {
  6989. array = create<array_t>(value);
  6990. }
  6991. /// constructor for rvalue arrays
  6992. json_value(array_t&& value)
  6993. {
  6994. array = create<array_t>(std::move(value));
  6995. }
  6996. void destroy(value_t t)
  6997. {
  6998. switch (t)
  6999. {
  7000. case value_t::object:
  7001. {
  7002. AllocatorType<object_t> alloc;
  7003. alloc.destroy(object);
  7004. alloc.deallocate(object, 1);
  7005. break;
  7006. }
  7007. case value_t::array:
  7008. {
  7009. AllocatorType<array_t> alloc;
  7010. alloc.destroy(array);
  7011. alloc.deallocate(array, 1);
  7012. break;
  7013. }
  7014. case value_t::string:
  7015. {
  7016. AllocatorType<string_t> alloc;
  7017. alloc.destroy(string);
  7018. alloc.deallocate(string, 1);
  7019. break;
  7020. }
  7021. default:
  7022. {
  7023. break;
  7024. }
  7025. }
  7026. }
  7027. };
  7028. /*!
  7029. @brief checks the class invariants
  7030. This function asserts the class invariants. It needs to be called at the
  7031. end of every constructor to make sure that created objects respect the
  7032. invariant. Furthermore, it has to be called each time the type of a JSON
  7033. value is changed, because the invariant expresses a relationship between
  7034. @a m_type and @a m_value.
  7035. */
  7036. void assert_invariant() const
  7037. {
  7038. assert(m_type != value_t::object or m_value.object != nullptr);
  7039. assert(m_type != value_t::array or m_value.array != nullptr);
  7040. assert(m_type != value_t::string or m_value.string != nullptr);
  7041. }
  7042. public:
  7043. //////////////////////////
  7044. // JSON parser callback //
  7045. //////////////////////////
  7046. using parse_event_t = typename parser::parse_event_t;
  7047. /*!
  7048. @brief per-element parser callback type
  7049. With a parser callback function, the result of parsing a JSON text can be
  7050. influenced. When passed to @ref parse(std::istream&, const
  7051. parser_callback_t) or @ref parse(const CharT, const parser_callback_t),
  7052. it is called on certain events (passed as @ref parse_event_t via parameter
  7053. @a event) with a set recursion depth @a depth and context JSON value
  7054. @a parsed. The return value of the callback function is a boolean
  7055. indicating whether the element that emitted the callback shall be kept or
  7056. not.
  7057. We distinguish six scenarios (determined by the event type) in which the
  7058. callback function can be called. The following table describes the values
  7059. of the parameters @a depth, @a event, and @a parsed.
  7060. parameter @a event | description | parameter @a depth | parameter @a parsed
  7061. ------------------ | ----------- | ------------------ | -------------------
  7062. 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
  7063. 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
  7064. 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
  7065. 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
  7066. 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
  7067. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  7068. @image html callback_events.png "Example when certain parse events are triggered"
  7069. Discarding a value (i.e., returning `false`) has different effects
  7070. depending on the context in which function was called:
  7071. - Discarded values in structured types are skipped. That is, the parser
  7072. will behave as if the discarded value was never read.
  7073. - In case a value outside a structured type is skipped, it is replaced
  7074. with `null`. This case happens if the top-level element is skipped.
  7075. @param[in] depth the depth of the recursion during parsing
  7076. @param[in] event an event of type parse_event_t indicating the context in
  7077. the callback function has been called
  7078. @param[in,out] parsed the current intermediate parse result; note that
  7079. writing to this value has no effect for parse_event_t::key events
  7080. @return Whether the JSON value which called the function during parsing
  7081. should be kept (`true`) or not (`false`). In the latter case, it is either
  7082. skipped completely or replaced by an empty discarded object.
  7083. @sa @ref parse(std::istream&, parser_callback_t) or
  7084. @ref parse(const CharT, const parser_callback_t) for examples
  7085. @since version 1.0.0
  7086. */
  7087. using parser_callback_t = typename parser::parser_callback_t;
  7088. //////////////////
  7089. // constructors //
  7090. //////////////////
  7091. /// @name constructors and destructors
  7092. /// Constructors of class @ref basic_json, copy/move constructor, copy
  7093. /// assignment, static functions creating objects, and the destructor.
  7094. /// @{
  7095. /*!
  7096. @brief create an empty value with a given type
  7097. Create an empty JSON value with a given type. The value will be default
  7098. initialized with an empty value which depends on the type:
  7099. Value type | initial value
  7100. ----------- | -------------
  7101. null | `null`
  7102. boolean | `false`
  7103. string | `""`
  7104. number | `0`
  7105. object | `{}`
  7106. array | `[]`
  7107. @param[in] v the type of the value to create
  7108. @complexity Constant.
  7109. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7110. changes to any JSON value.
  7111. @liveexample{The following code shows the constructor for different @ref
  7112. value_t values,basic_json__value_t}
  7113. @sa @ref clear() -- restores the postcondition of this constructor
  7114. @since version 1.0.0
  7115. */
  7116. basic_json(const value_t v)
  7117. : m_type(v), m_value(v)
  7118. {
  7119. assert_invariant();
  7120. }
  7121. /*!
  7122. @brief create a null object
  7123. Create a `null` JSON value. It either takes a null pointer as parameter
  7124. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  7125. The passed null pointer itself is not read -- it is only used to choose
  7126. the right constructor.
  7127. @complexity Constant.
  7128. @exceptionsafety No-throw guarantee: this constructor never throws
  7129. exceptions.
  7130. @liveexample{The following code shows the constructor with and without a
  7131. null pointer parameter.,basic_json__nullptr_t}
  7132. @since version 1.0.0
  7133. */
  7134. basic_json(std::nullptr_t = nullptr) noexcept
  7135. : basic_json(value_t::null)
  7136. {
  7137. assert_invariant();
  7138. }
  7139. /*!
  7140. @brief create a JSON value
  7141. This is a "catch all" constructor for all compatible JSON types; that is,
  7142. types for which a `to_json()` method exsits. The constructor forwards the
  7143. parameter @a val to that method (to `json_serializer<U>::to_json` method
  7144. with `U = uncvref_t<CompatibleType>`, to be exact).
  7145. Template type @a CompatibleType includes, but is not limited to, the
  7146. following types:
  7147. - **arrays**: @ref array_t and all kinds of compatible containers such as
  7148. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  7149. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  7150. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  7151. which a @ref basic_json value can be constructed.
  7152. - **objects**: @ref object_t and all kinds of compatible associative
  7153. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  7154. and `std::unordered_multimap` with a `key_type` compatible to
  7155. @ref string_t and a `value_type` from which a @ref basic_json value can
  7156. be constructed.
  7157. - **strings**: @ref string_t, string literals, and all compatible string
  7158. containers can be used.
  7159. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  7160. @ref number_float_t, and all convertible number types such as `int`,
  7161. `size_t`, `int64_t`, `float` or `double` can be used.
  7162. - **boolean**: @ref boolean_t / `bool` can be used.
  7163. See the examples below.
  7164. @tparam CompatibleType a type such that:
  7165. - @a CompatibleType is not derived from `std::istream`,
  7166. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  7167. constructors),
  7168. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  7169. @ref json_pointer, @ref iterator, etc ...)
  7170. - @ref @ref json_serializer<U> has a
  7171. `to_json(basic_json_t&, CompatibleType&&)` method
  7172. @tparam U = `uncvref_t<CompatibleType>`
  7173. @param[in] val the value to be forwarded to the respective constructor
  7174. @complexity Usually linear in the size of the passed @a val, also
  7175. depending on the implementation of the called `to_json()`
  7176. method.
  7177. @exceptionsafety Depends on the called constructor. For types directly
  7178. supported by the library (i.e., all types for which no `to_json()` function
  7179. was provided), strong guarantee holds: if an exception is thrown, there are
  7180. no changes to any JSON value.
  7181. @liveexample{The following code shows the constructor with several
  7182. compatible types.,basic_json__CompatibleType}
  7183. @since version 2.1.0
  7184. */
  7185. template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
  7186. detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
  7187. not std::is_same<U, basic_json_t>::value and
  7188. not detail::is_basic_json_nested_type<
  7189. basic_json_t, U>::value and
  7190. detail::has_to_json<basic_json, U>::value,
  7191. int> = 0>
  7192. basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
  7193. std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
  7194. {
  7195. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  7196. assert_invariant();
  7197. }
  7198. /*!
  7199. @brief create a container (array or object) from an initializer list
  7200. Creates a JSON value of type array or object from the passed initializer
  7201. list @a init. In case @a type_deduction is `true` (default), the type of
  7202. the JSON value to be created is deducted from the initializer list @a init
  7203. according to the following rules:
  7204. 1. If the list is empty, an empty JSON object value `{}` is created.
  7205. 2. If the list consists of pairs whose first element is a string, a JSON
  7206. object value is created where the first elements of the pairs are
  7207. treated as keys and the second elements are as values.
  7208. 3. In all other cases, an array is created.
  7209. The rules aim to create the best fit between a C++ initializer list and
  7210. JSON values. The rationale is as follows:
  7211. 1. The empty initializer list is written as `{}` which is exactly an empty
  7212. JSON object.
  7213. 2. C++ has no way of describing mapped types other than to list a list of
  7214. pairs. As JSON requires that keys must be of type string, rule 2 is the
  7215. weakest constraint one can pose on initializer lists to interpret them
  7216. as an object.
  7217. 3. In all other cases, the initializer list could not be interpreted as
  7218. JSON object type, so interpreting it as JSON array type is safe.
  7219. With the rules described above, the following JSON values cannot be
  7220. expressed by an initializer list:
  7221. - the empty array (`[]`): use @ref array(initializer_list_t)
  7222. with an empty initializer list in this case
  7223. - arrays whose elements satisfy rule 2: use @ref
  7224. array(initializer_list_t) with the same initializer list
  7225. in this case
  7226. @note When used without parentheses around an empty initializer list, @ref
  7227. basic_json() is called instead of this function, yielding the JSON null
  7228. value.
  7229. @param[in] init initializer list with JSON values
  7230. @param[in] type_deduction internal parameter; when set to `true`, the type
  7231. of the JSON value is deducted from the initializer list @a init; when set
  7232. to `false`, the type provided via @a manual_type is forced. This mode is
  7233. used by the functions @ref array(initializer_list_t) and
  7234. @ref object(initializer_list_t).
  7235. @param[in] manual_type internal parameter; when @a type_deduction is set
  7236. to `false`, the created JSON value will use the provided type (only @ref
  7237. value_t::array and @ref value_t::object are valid); when @a type_deduction
  7238. is set to `true`, this parameter has no effect
  7239. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  7240. `value_t::object`, but @a init contains an element which is not a pair
  7241. whose first element is a string. In this case, the constructor could not
  7242. create an object. If @a type_deduction would have be `true`, an array
  7243. would have been created. See @ref object(initializer_list_t)
  7244. for an example.
  7245. @complexity Linear in the size of the initializer list @a init.
  7246. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7247. changes to any JSON value.
  7248. @liveexample{The example below shows how JSON values are created from
  7249. initializer lists.,basic_json__list_init_t}
  7250. @sa @ref array(initializer_list_t) -- create a JSON array
  7251. value from an initializer list
  7252. @sa @ref object(initializer_list_t) -- create a JSON object
  7253. value from an initializer list
  7254. @since version 1.0.0
  7255. */
  7256. basic_json(initializer_list_t init,
  7257. bool type_deduction = true,
  7258. value_t manual_type = value_t::array)
  7259. {
  7260. // check if each element is an array with two elements whose first
  7261. // element is a string
  7262. bool is_an_object = std::all_of(init.begin(), init.end(),
  7263. [](const detail::json_ref<basic_json>& element_ref)
  7264. {
  7265. return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
  7266. });
  7267. // adjust type if type deduction is not wanted
  7268. if (not type_deduction)
  7269. {
  7270. // if array is wanted, do not create an object though possible
  7271. if (manual_type == value_t::array)
  7272. {
  7273. is_an_object = false;
  7274. }
  7275. // if object is wanted but impossible, throw an exception
  7276. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  7277. {
  7278. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  7279. }
  7280. }
  7281. if (is_an_object)
  7282. {
  7283. // the initializer list is a list of pairs -> create object
  7284. m_type = value_t::object;
  7285. m_value = value_t::object;
  7286. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  7287. {
  7288. auto element = element_ref.moved_or_copied();
  7289. m_value.object->emplace(
  7290. std::move(*((*element.m_value.array)[0].m_value.string)),
  7291. std::move((*element.m_value.array)[1]));
  7292. });
  7293. }
  7294. else
  7295. {
  7296. // the initializer list describes an array -> create array
  7297. m_type = value_t::array;
  7298. m_value.array = create<array_t>(init.begin(), init.end());
  7299. }
  7300. assert_invariant();
  7301. }
  7302. /*!
  7303. @brief explicitly create an array from an initializer list
  7304. Creates a JSON array value from a given initializer list. That is, given a
  7305. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  7306. initializer list is empty, the empty array `[]` is created.
  7307. @note This function is only needed to express two edge cases that cannot
  7308. be realized with the initializer list constructor (@ref
  7309. basic_json(initializer_list_t, bool, value_t)). These cases
  7310. are:
  7311. 1. creating an array whose elements are all pairs whose first element is a
  7312. string -- in this case, the initializer list constructor would create an
  7313. object, taking the first elements as keys
  7314. 2. creating an empty array -- passing the empty initializer list to the
  7315. initializer list constructor yields an empty object
  7316. @param[in] init initializer list with JSON values to create an array from
  7317. (optional)
  7318. @return JSON array value
  7319. @complexity Linear in the size of @a init.
  7320. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7321. changes to any JSON value.
  7322. @liveexample{The following code shows an example for the `array`
  7323. function.,array}
  7324. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  7325. create a JSON value from an initializer list
  7326. @sa @ref object(initializer_list_t) -- create a JSON object
  7327. value from an initializer list
  7328. @since version 1.0.0
  7329. */
  7330. static basic_json array(initializer_list_t init = {})
  7331. {
  7332. return basic_json(init, false, value_t::array);
  7333. }
  7334. /*!
  7335. @brief explicitly create an object from an initializer list
  7336. Creates a JSON object value from a given initializer list. The initializer
  7337. lists elements must be pairs, and their first elements must be strings. If
  7338. the initializer list is empty, the empty object `{}` is created.
  7339. @note This function is only added for symmetry reasons. In contrast to the
  7340. related function @ref array(initializer_list_t), there are
  7341. no cases which can only be expressed by this function. That is, any
  7342. initializer list @a init can also be passed to the initializer list
  7343. constructor @ref basic_json(initializer_list_t, bool, value_t).
  7344. @param[in] init initializer list to create an object from (optional)
  7345. @return JSON object value
  7346. @throw type_error.301 if @a init is not a list of pairs whose first
  7347. elements are strings. In this case, no object can be created. When such a
  7348. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  7349. an array would have been created from the passed initializer list @a init.
  7350. See example below.
  7351. @complexity Linear in the size of @a init.
  7352. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7353. changes to any JSON value.
  7354. @liveexample{The following code shows an example for the `object`
  7355. function.,object}
  7356. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  7357. create a JSON value from an initializer list
  7358. @sa @ref array(initializer_list_t) -- create a JSON array
  7359. value from an initializer list
  7360. @since version 1.0.0
  7361. */
  7362. static basic_json object(initializer_list_t init = {})
  7363. {
  7364. return basic_json(init, false, value_t::object);
  7365. }
  7366. /*!
  7367. @brief construct an array with count copies of given value
  7368. Constructs a JSON array value by creating @a cnt copies of a passed value.
  7369. In case @a cnt is `0`, an empty array is created.
  7370. @param[in] cnt the number of JSON copies of @a val to create
  7371. @param[in] val the JSON value to copy
  7372. @post `std::distance(begin(),end()) == cnt` holds.
  7373. @complexity Linear in @a cnt.
  7374. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7375. changes to any JSON value.
  7376. @liveexample{The following code shows examples for the @ref
  7377. basic_json(size_type\, const basic_json&)
  7378. constructor.,basic_json__size_type_basic_json}
  7379. @since version 1.0.0
  7380. */
  7381. basic_json(size_type cnt, const basic_json& val)
  7382. : m_type(value_t::array)
  7383. {
  7384. m_value.array = create<array_t>(cnt, val);
  7385. assert_invariant();
  7386. }
  7387. /*!
  7388. @brief construct a JSON container given an iterator range
  7389. Constructs the JSON value with the contents of the range `[first, last)`.
  7390. The semantics depends on the different types a JSON value can have:
  7391. - In case of a null type, invalid_iterator.206 is thrown.
  7392. - In case of other primitive types (number, boolean, or string), @a first
  7393. must be `begin()` and @a last must be `end()`. In this case, the value is
  7394. copied. Otherwise, invalid_iterator.204 is thrown.
  7395. - In case of structured types (array, object), the constructor behaves as
  7396. similar versions for `std::vector` or `std::map`; that is, a JSON array
  7397. or object is constructed from the values in the range.
  7398. @tparam InputIT an input iterator type (@ref iterator or @ref
  7399. const_iterator)
  7400. @param[in] first begin of the range to copy from (included)
  7401. @param[in] last end of the range to copy from (excluded)
  7402. @pre Iterators @a first and @a last must be initialized. **This
  7403. precondition is enforced with an assertion (see warning).** If
  7404. assertions are switched off, a violation of this precondition yields
  7405. undefined behavior.
  7406. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  7407. checked efficiently. Only certain edge cases are detected; see the
  7408. description of the exceptions below. A violation of this precondition
  7409. yields undefined behavior.
  7410. @warning A precondition is enforced with a runtime assertion that will
  7411. result in calling `std::abort` if this precondition is not met.
  7412. Assertions can be disabled by defining `NDEBUG` at compile time.
  7413. See http://en.cppreference.com/w/cpp/error/assert for more
  7414. information.
  7415. @throw invalid_iterator.201 if iterators @a first and @a last are not
  7416. compatible (i.e., do not belong to the same JSON value). In this case,
  7417. the range `[first, last)` is undefined.
  7418. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  7419. primitive type (number, boolean, or string), but @a first does not point
  7420. to the first element any more. In this case, the range `[first, last)` is
  7421. undefined. See example code below.
  7422. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  7423. null value. In this case, the range `[first, last)` is undefined.
  7424. @complexity Linear in distance between @a first and @a last.
  7425. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7426. changes to any JSON value.
  7427. @liveexample{The example below shows several ways to create JSON values by
  7428. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  7429. @since version 1.0.0
  7430. */
  7431. template<class InputIT, typename std::enable_if<
  7432. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  7433. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  7434. basic_json(InputIT first, InputIT last)
  7435. {
  7436. assert(first.m_object != nullptr);
  7437. assert(last.m_object != nullptr);
  7438. // make sure iterator fits the current value
  7439. if (JSON_UNLIKELY(first.m_object != last.m_object))
  7440. {
  7441. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  7442. }
  7443. // copy type from first iterator
  7444. m_type = first.m_object->m_type;
  7445. // check if iterator range is complete for primitive values
  7446. switch (m_type)
  7447. {
  7448. case value_t::boolean:
  7449. case value_t::number_float:
  7450. case value_t::number_integer:
  7451. case value_t::number_unsigned:
  7452. case value_t::string:
  7453. {
  7454. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  7455. or not last.m_it.primitive_iterator.is_end()))
  7456. {
  7457. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  7458. }
  7459. break;
  7460. }
  7461. default:
  7462. break;
  7463. }
  7464. switch (m_type)
  7465. {
  7466. case value_t::number_integer:
  7467. {
  7468. m_value.number_integer = first.m_object->m_value.number_integer;
  7469. break;
  7470. }
  7471. case value_t::number_unsigned:
  7472. {
  7473. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  7474. break;
  7475. }
  7476. case value_t::number_float:
  7477. {
  7478. m_value.number_float = first.m_object->m_value.number_float;
  7479. break;
  7480. }
  7481. case value_t::boolean:
  7482. {
  7483. m_value.boolean = first.m_object->m_value.boolean;
  7484. break;
  7485. }
  7486. case value_t::string:
  7487. {
  7488. m_value = *first.m_object->m_value.string;
  7489. break;
  7490. }
  7491. case value_t::object:
  7492. {
  7493. m_value.object = create<object_t>(first.m_it.object_iterator,
  7494. last.m_it.object_iterator);
  7495. break;
  7496. }
  7497. case value_t::array:
  7498. {
  7499. m_value.array = create<array_t>(first.m_it.array_iterator,
  7500. last.m_it.array_iterator);
  7501. break;
  7502. }
  7503. default:
  7504. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  7505. std::string(first.m_object->type_name())));
  7506. }
  7507. assert_invariant();
  7508. }
  7509. ///////////////////////////////////////
  7510. // other constructors and destructor //
  7511. ///////////////////////////////////////
  7512. /// @private
  7513. basic_json(const detail::json_ref<basic_json>& ref)
  7514. : basic_json(ref.moved_or_copied())
  7515. {}
  7516. /*!
  7517. @brief copy constructor
  7518. Creates a copy of a given JSON value.
  7519. @param[in] other the JSON value to copy
  7520. @post `*this == other`
  7521. @complexity Linear in the size of @a other.
  7522. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7523. changes to any JSON value.
  7524. @requirement This function helps `basic_json` satisfying the
  7525. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7526. requirements:
  7527. - The complexity is linear.
  7528. - As postcondition, it holds: `other == basic_json(other)`.
  7529. @liveexample{The following code shows an example for the copy
  7530. constructor.,basic_json__basic_json}
  7531. @since version 1.0.0
  7532. */
  7533. basic_json(const basic_json& other)
  7534. : m_type(other.m_type)
  7535. {
  7536. // check of passed value is valid
  7537. other.assert_invariant();
  7538. switch (m_type)
  7539. {
  7540. case value_t::object:
  7541. {
  7542. m_value = *other.m_value.object;
  7543. break;
  7544. }
  7545. case value_t::array:
  7546. {
  7547. m_value = *other.m_value.array;
  7548. break;
  7549. }
  7550. case value_t::string:
  7551. {
  7552. m_value = *other.m_value.string;
  7553. break;
  7554. }
  7555. case value_t::boolean:
  7556. {
  7557. m_value = other.m_value.boolean;
  7558. break;
  7559. }
  7560. case value_t::number_integer:
  7561. {
  7562. m_value = other.m_value.number_integer;
  7563. break;
  7564. }
  7565. case value_t::number_unsigned:
  7566. {
  7567. m_value = other.m_value.number_unsigned;
  7568. break;
  7569. }
  7570. case value_t::number_float:
  7571. {
  7572. m_value = other.m_value.number_float;
  7573. break;
  7574. }
  7575. default:
  7576. break;
  7577. }
  7578. assert_invariant();
  7579. }
  7580. /*!
  7581. @brief move constructor
  7582. Move constructor. Constructs a JSON value with the contents of the given
  7583. value @a other using move semantics. It "steals" the resources from @a
  7584. other and leaves it as JSON null value.
  7585. @param[in,out] other value to move to this object
  7586. @post `*this` has the same value as @a other before the call.
  7587. @post @a other is a JSON null value.
  7588. @complexity Constant.
  7589. @exceptionsafety No-throw guarantee: this constructor never throws
  7590. exceptions.
  7591. @requirement This function helps `basic_json` satisfying the
  7592. [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)
  7593. requirements.
  7594. @liveexample{The code below shows the move constructor explicitly called
  7595. via std::move.,basic_json__moveconstructor}
  7596. @since version 1.0.0
  7597. */
  7598. basic_json(basic_json&& other) noexcept
  7599. : m_type(std::move(other.m_type)),
  7600. m_value(std::move(other.m_value))
  7601. {
  7602. // check that passed value is valid
  7603. other.assert_invariant();
  7604. // invalidate payload
  7605. other.m_type = value_t::null;
  7606. other.m_value = {};
  7607. assert_invariant();
  7608. }
  7609. /*!
  7610. @brief copy assignment
  7611. Copy assignment operator. Copies a JSON value via the "copy and swap"
  7612. strategy: It is expressed in terms of the copy constructor, destructor,
  7613. and the `swap()` member function.
  7614. @param[in] other value to copy from
  7615. @complexity Linear.
  7616. @requirement This function helps `basic_json` satisfying the
  7617. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7618. requirements:
  7619. - The complexity is linear.
  7620. @liveexample{The code below shows and example for the copy assignment. It
  7621. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  7622. copy of `a` (which is the null value after the swap) is
  7623. destroyed.,basic_json__copyassignment}
  7624. @since version 1.0.0
  7625. */
  7626. reference& operator=(basic_json other) noexcept (
  7627. std::is_nothrow_move_constructible<value_t>::value and
  7628. std::is_nothrow_move_assignable<value_t>::value and
  7629. std::is_nothrow_move_constructible<json_value>::value and
  7630. std::is_nothrow_move_assignable<json_value>::value
  7631. )
  7632. {
  7633. // check that passed value is valid
  7634. other.assert_invariant();
  7635. using std::swap;
  7636. swap(m_type, other.m_type);
  7637. swap(m_value, other.m_value);
  7638. assert_invariant();
  7639. return *this;
  7640. }
  7641. /*!
  7642. @brief destructor
  7643. Destroys the JSON value and frees all allocated memory.
  7644. @complexity Linear.
  7645. @requirement This function helps `basic_json` satisfying the
  7646. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  7647. requirements:
  7648. - The complexity is linear.
  7649. - All stored elements are destroyed and all memory is freed.
  7650. @since version 1.0.0
  7651. */
  7652. ~basic_json()
  7653. {
  7654. assert_invariant();
  7655. m_value.destroy(m_type);
  7656. }
  7657. /// @}
  7658. public:
  7659. ///////////////////////
  7660. // object inspection //
  7661. ///////////////////////
  7662. /// @name object inspection
  7663. /// Functions to inspect the type of a JSON value.
  7664. /// @{
  7665. /*!
  7666. @brief serialization
  7667. Serialization function for JSON values. The function tries to mimic
  7668. Python's `json.dumps()` function, and currently supports its @a indent
  7669. and @a ensure_ascii parameters.
  7670. @param[in] indent If indent is nonnegative, then array elements and object
  7671. members will be pretty-printed with that indent level. An indent level of
  7672. `0` will only insert newlines. `-1` (the default) selects the most compact
  7673. representation.
  7674. @param[in] indent_char The character to use for indentation if @a indent is
  7675. greater than `0`. The default is ` ` (space).
  7676. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  7677. in the output are escaped with \uXXXX sequences, and the result consists
  7678. of ASCII characters only.
  7679. @return string containing the serialization of the JSON value
  7680. @complexity Linear.
  7681. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  7682. changes in the JSON value.
  7683. @liveexample{The following example shows the effect of different @a indent\,
  7684. @a indent_char\, and @a ensure_ascii parameters to the result of the
  7685. serialization.,dump}
  7686. @see https://docs.python.org/2/library/json.html#json.dump
  7687. @since version 1.0.0; indentation character @a indent_char and option
  7688. @a ensure_ascii added in version 3.0.0
  7689. */
  7690. string_t dump(const int indent = -1, const char indent_char = ' ',
  7691. const bool ensure_ascii = false) const
  7692. {
  7693. string_t result;
  7694. serializer s(detail::output_adapter<char>(result), indent_char);
  7695. if (indent >= 0)
  7696. {
  7697. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  7698. }
  7699. else
  7700. {
  7701. s.dump(*this, false, ensure_ascii, 0);
  7702. }
  7703. return result;
  7704. }
  7705. /*!
  7706. @brief return the type of the JSON value (explicit)
  7707. Return the type of the JSON value as a value from the @ref value_t
  7708. enumeration.
  7709. @return the type of the JSON value
  7710. Value type | return value
  7711. ------------------------- | -------------------------
  7712. null | value_t::null
  7713. boolean | value_t::boolean
  7714. string | value_t::string
  7715. number (integer) | value_t::number_integer
  7716. number (unsigned integer) | value_t::number_unsigned
  7717. number (foating-point) | value_t::number_float
  7718. object | value_t::object
  7719. array | value_t::array
  7720. discarded | value_t::discarded
  7721. @complexity Constant.
  7722. @exceptionsafety No-throw guarantee: this member function never throws
  7723. exceptions.
  7724. @liveexample{The following code exemplifies `type()` for all JSON
  7725. types.,type}
  7726. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  7727. @sa @ref type_name() -- return the type as string
  7728. @since version 1.0.0
  7729. */
  7730. constexpr value_t type() const noexcept
  7731. {
  7732. return m_type;
  7733. }
  7734. /*!
  7735. @brief return whether type is primitive
  7736. This function returns true if and only if the JSON type is primitive
  7737. (string, number, boolean, or null).
  7738. @return `true` if type is primitive (string, number, boolean, or null),
  7739. `false` otherwise.
  7740. @complexity Constant.
  7741. @exceptionsafety No-throw guarantee: this member function never throws
  7742. exceptions.
  7743. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  7744. types.,is_primitive}
  7745. @sa @ref is_structured() -- returns whether JSON value is structured
  7746. @sa @ref is_null() -- returns whether JSON value is `null`
  7747. @sa @ref is_string() -- returns whether JSON value is a string
  7748. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  7749. @sa @ref is_number() -- returns whether JSON value is a number
  7750. @since version 1.0.0
  7751. */
  7752. constexpr bool is_primitive() const noexcept
  7753. {
  7754. return is_null() or is_string() or is_boolean() or is_number();
  7755. }
  7756. /*!
  7757. @brief return whether type is structured
  7758. This function returns true if and only if the JSON type is structured
  7759. (array or object).
  7760. @return `true` if type is structured (array or object), `false` otherwise.
  7761. @complexity Constant.
  7762. @exceptionsafety No-throw guarantee: this member function never throws
  7763. exceptions.
  7764. @liveexample{The following code exemplifies `is_structured()` for all JSON
  7765. types.,is_structured}
  7766. @sa @ref is_primitive() -- returns whether value is primitive
  7767. @sa @ref is_array() -- returns whether value is an array
  7768. @sa @ref is_object() -- returns whether value is an object
  7769. @since version 1.0.0
  7770. */
  7771. constexpr bool is_structured() const noexcept
  7772. {
  7773. return is_array() or is_object();
  7774. }
  7775. /*!
  7776. @brief return whether value is null
  7777. This function returns true if and only if the JSON value is null.
  7778. @return `true` if type is null, `false` otherwise.
  7779. @complexity Constant.
  7780. @exceptionsafety No-throw guarantee: this member function never throws
  7781. exceptions.
  7782. @liveexample{The following code exemplifies `is_null()` for all JSON
  7783. types.,is_null}
  7784. @since version 1.0.0
  7785. */
  7786. constexpr bool is_null() const noexcept
  7787. {
  7788. return (m_type == value_t::null);
  7789. }
  7790. /*!
  7791. @brief return whether value is a boolean
  7792. This function returns true if and only if the JSON value is a boolean.
  7793. @return `true` if type is boolean, `false` otherwise.
  7794. @complexity Constant.
  7795. @exceptionsafety No-throw guarantee: this member function never throws
  7796. exceptions.
  7797. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  7798. types.,is_boolean}
  7799. @since version 1.0.0
  7800. */
  7801. constexpr bool is_boolean() const noexcept
  7802. {
  7803. return (m_type == value_t::boolean);
  7804. }
  7805. /*!
  7806. @brief return whether value is a number
  7807. This function returns true if and only if the JSON value is a number. This
  7808. includes both integer (signed and unsigned) and floating-point values.
  7809. @return `true` if type is number (regardless whether integer, unsigned
  7810. integer or floating-type), `false` otherwise.
  7811. @complexity Constant.
  7812. @exceptionsafety No-throw guarantee: this member function never throws
  7813. exceptions.
  7814. @liveexample{The following code exemplifies `is_number()` for all JSON
  7815. types.,is_number}
  7816. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  7817. integer number
  7818. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7819. number
  7820. @sa @ref is_number_float() -- check if value is a floating-point number
  7821. @since version 1.0.0
  7822. */
  7823. constexpr bool is_number() const noexcept
  7824. {
  7825. return is_number_integer() or is_number_float();
  7826. }
  7827. /*!
  7828. @brief return whether value is an integer number
  7829. This function returns true if and only if the JSON value is a signed or
  7830. unsigned integer number. This excludes floating-point values.
  7831. @return `true` if type is an integer or unsigned integer number, `false`
  7832. otherwise.
  7833. @complexity Constant.
  7834. @exceptionsafety No-throw guarantee: this member function never throws
  7835. exceptions.
  7836. @liveexample{The following code exemplifies `is_number_integer()` for all
  7837. JSON types.,is_number_integer}
  7838. @sa @ref is_number() -- check if value is a number
  7839. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7840. number
  7841. @sa @ref is_number_float() -- check if value is a floating-point number
  7842. @since version 1.0.0
  7843. */
  7844. constexpr bool is_number_integer() const noexcept
  7845. {
  7846. return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
  7847. }
  7848. /*!
  7849. @brief return whether value is an unsigned integer number
  7850. This function returns true if and only if the JSON value is an unsigned
  7851. integer number. This excludes floating-point and signed integer values.
  7852. @return `true` if type is an unsigned integer number, `false` otherwise.
  7853. @complexity Constant.
  7854. @exceptionsafety No-throw guarantee: this member function never throws
  7855. exceptions.
  7856. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  7857. JSON types.,is_number_unsigned}
  7858. @sa @ref is_number() -- check if value is a number
  7859. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  7860. integer number
  7861. @sa @ref is_number_float() -- check if value is a floating-point number
  7862. @since version 2.0.0
  7863. */
  7864. constexpr bool is_number_unsigned() const noexcept
  7865. {
  7866. return (m_type == value_t::number_unsigned);
  7867. }
  7868. /*!
  7869. @brief return whether value is a floating-point number
  7870. This function returns true if and only if the JSON value is a
  7871. floating-point number. This excludes signed and unsigned integer values.
  7872. @return `true` if type is a floating-point number, `false` otherwise.
  7873. @complexity Constant.
  7874. @exceptionsafety No-throw guarantee: this member function never throws
  7875. exceptions.
  7876. @liveexample{The following code exemplifies `is_number_float()` for all
  7877. JSON types.,is_number_float}
  7878. @sa @ref is_number() -- check if value is number
  7879. @sa @ref is_number_integer() -- check if value is an integer number
  7880. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  7881. number
  7882. @since version 1.0.0
  7883. */
  7884. constexpr bool is_number_float() const noexcept
  7885. {
  7886. return (m_type == value_t::number_float);
  7887. }
  7888. /*!
  7889. @brief return whether value is an object
  7890. This function returns true if and only if the JSON value is an object.
  7891. @return `true` if type is object, `false` otherwise.
  7892. @complexity Constant.
  7893. @exceptionsafety No-throw guarantee: this member function never throws
  7894. exceptions.
  7895. @liveexample{The following code exemplifies `is_object()` for all JSON
  7896. types.,is_object}
  7897. @since version 1.0.0
  7898. */
  7899. constexpr bool is_object() const noexcept
  7900. {
  7901. return (m_type == value_t::object);
  7902. }
  7903. /*!
  7904. @brief return whether value is an array
  7905. This function returns true if and only if the JSON value is an array.
  7906. @return `true` if type is array, `false` otherwise.
  7907. @complexity Constant.
  7908. @exceptionsafety No-throw guarantee: this member function never throws
  7909. exceptions.
  7910. @liveexample{The following code exemplifies `is_array()` for all JSON
  7911. types.,is_array}
  7912. @since version 1.0.0
  7913. */
  7914. constexpr bool is_array() const noexcept
  7915. {
  7916. return (m_type == value_t::array);
  7917. }
  7918. /*!
  7919. @brief return whether value is a string
  7920. This function returns true if and only if the JSON value is a string.
  7921. @return `true` if type is string, `false` otherwise.
  7922. @complexity Constant.
  7923. @exceptionsafety No-throw guarantee: this member function never throws
  7924. exceptions.
  7925. @liveexample{The following code exemplifies `is_string()` for all JSON
  7926. types.,is_string}
  7927. @since version 1.0.0
  7928. */
  7929. constexpr bool is_string() const noexcept
  7930. {
  7931. return (m_type == value_t::string);
  7932. }
  7933. /*!
  7934. @brief return whether value is discarded
  7935. This function returns true if and only if the JSON value was discarded
  7936. during parsing with a callback function (see @ref parser_callback_t).
  7937. @note This function will always be `false` for JSON values after parsing.
  7938. That is, discarded values can only occur during parsing, but will be
  7939. removed when inside a structured value or replaced by null in other cases.
  7940. @return `true` if type is discarded, `false` otherwise.
  7941. @complexity Constant.
  7942. @exceptionsafety No-throw guarantee: this member function never throws
  7943. exceptions.
  7944. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  7945. types.,is_discarded}
  7946. @since version 1.0.0
  7947. */
  7948. constexpr bool is_discarded() const noexcept
  7949. {
  7950. return (m_type == value_t::discarded);
  7951. }
  7952. /*!
  7953. @brief return the type of the JSON value (implicit)
  7954. Implicitly return the type of the JSON value as a value from the @ref
  7955. value_t enumeration.
  7956. @return the type of the JSON value
  7957. @complexity Constant.
  7958. @exceptionsafety No-throw guarantee: this member function never throws
  7959. exceptions.
  7960. @liveexample{The following code exemplifies the @ref value_t operator for
  7961. all JSON types.,operator__value_t}
  7962. @sa @ref type() -- return the type of the JSON value (explicit)
  7963. @sa @ref type_name() -- return the type as string
  7964. @since version 1.0.0
  7965. */
  7966. constexpr operator value_t() const noexcept
  7967. {
  7968. return m_type;
  7969. }
  7970. /// @}
  7971. private:
  7972. //////////////////
  7973. // value access //
  7974. //////////////////
  7975. /// get a boolean (explicit)
  7976. boolean_t get_impl(boolean_t* /*unused*/) const
  7977. {
  7978. if (JSON_LIKELY(is_boolean()))
  7979. {
  7980. return m_value.boolean;
  7981. }
  7982. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  7983. }
  7984. /// get a pointer to the value (object)
  7985. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  7986. {
  7987. return is_object() ? m_value.object : nullptr;
  7988. }
  7989. /// get a pointer to the value (object)
  7990. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  7991. {
  7992. return is_object() ? m_value.object : nullptr;
  7993. }
  7994. /// get a pointer to the value (array)
  7995. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  7996. {
  7997. return is_array() ? m_value.array : nullptr;
  7998. }
  7999. /// get a pointer to the value (array)
  8000. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  8001. {
  8002. return is_array() ? m_value.array : nullptr;
  8003. }
  8004. /// get a pointer to the value (string)
  8005. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  8006. {
  8007. return is_string() ? m_value.string : nullptr;
  8008. }
  8009. /// get a pointer to the value (string)
  8010. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  8011. {
  8012. return is_string() ? m_value.string : nullptr;
  8013. }
  8014. /// get a pointer to the value (boolean)
  8015. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  8016. {
  8017. return is_boolean() ? &m_value.boolean : nullptr;
  8018. }
  8019. /// get a pointer to the value (boolean)
  8020. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  8021. {
  8022. return is_boolean() ? &m_value.boolean : nullptr;
  8023. }
  8024. /// get a pointer to the value (integer number)
  8025. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  8026. {
  8027. return is_number_integer() ? &m_value.number_integer : nullptr;
  8028. }
  8029. /// get a pointer to the value (integer number)
  8030. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  8031. {
  8032. return is_number_integer() ? &m_value.number_integer : nullptr;
  8033. }
  8034. /// get a pointer to the value (unsigned number)
  8035. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  8036. {
  8037. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  8038. }
  8039. /// get a pointer to the value (unsigned number)
  8040. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  8041. {
  8042. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  8043. }
  8044. /// get a pointer to the value (floating-point number)
  8045. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  8046. {
  8047. return is_number_float() ? &m_value.number_float : nullptr;
  8048. }
  8049. /// get a pointer to the value (floating-point number)
  8050. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  8051. {
  8052. return is_number_float() ? &m_value.number_float : nullptr;
  8053. }
  8054. /*!
  8055. @brief helper function to implement get_ref()
  8056. This function helps to implement get_ref() without code duplication for
  8057. const and non-const overloads
  8058. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  8059. @throw type_error.303 if ReferenceType does not match underlying value
  8060. type of the current JSON
  8061. */
  8062. template<typename ReferenceType, typename ThisType>
  8063. static ReferenceType get_ref_impl(ThisType& obj)
  8064. {
  8065. // delegate the call to get_ptr<>()
  8066. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  8067. if (JSON_LIKELY(ptr != nullptr))
  8068. {
  8069. return *ptr;
  8070. }
  8071. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  8072. }
  8073. public:
  8074. /// @name value access
  8075. /// Direct access to the stored value of a JSON value.
  8076. /// @{
  8077. /*!
  8078. @brief get special-case overload
  8079. This overloads avoids a lot of template boilerplate, it can be seen as the
  8080. identity method
  8081. @tparam BasicJsonType == @ref basic_json
  8082. @return a copy of *this
  8083. @complexity Constant.
  8084. @since version 2.1.0
  8085. */
  8086. template <
  8087. typename BasicJsonType,
  8088. detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type,
  8089. basic_json_t>::value,
  8090. int> = 0 >
  8091. basic_json get() const
  8092. {
  8093. return *this;
  8094. }
  8095. /*!
  8096. @brief get a value (explicit)
  8097. Explicit type conversion between the JSON value and a compatible value
  8098. which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  8099. and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  8100. The value is converted by calling the @ref json_serializer<ValueType>
  8101. `from_json()` method.
  8102. The function is equivalent to executing
  8103. @code {.cpp}
  8104. ValueType ret;
  8105. JSONSerializer<ValueType>::from_json(*this, ret);
  8106. return ret;
  8107. @endcode
  8108. This overloads is chosen if:
  8109. - @a ValueType is not @ref basic_json,
  8110. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  8111. `void from_json(const basic_json&, ValueType&)`, and
  8112. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  8113. the form `ValueType from_json(const basic_json&)`
  8114. @tparam ValueTypeCV the provided value type
  8115. @tparam ValueType the returned value type
  8116. @return copy of the JSON value, converted to @a ValueType
  8117. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  8118. @liveexample{The example below shows several conversions from JSON values
  8119. to other types. There a few things to note: (1) Floating-point numbers can
  8120. be converted to integers\, (2) A JSON array can be converted to a standard
  8121. `std::vector<short>`\, (3) A JSON object can be converted to C++
  8122. associative containers such as `std::unordered_map<std::string\,
  8123. json>`.,get__ValueType_const}
  8124. @since version 2.1.0
  8125. */
  8126. template <
  8127. typename ValueTypeCV,
  8128. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  8129. detail::enable_if_t <
  8130. not std::is_same<basic_json_t, ValueType>::value and
  8131. detail::has_from_json<basic_json_t, ValueType>::value and
  8132. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  8133. int > = 0 >
  8134. ValueType get() const noexcept(noexcept(
  8135. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  8136. {
  8137. // we cannot static_assert on ValueTypeCV being non-const, because
  8138. // there is support for get<const basic_json_t>(), which is why we
  8139. // still need the uncvref
  8140. static_assert(not std::is_reference<ValueTypeCV>::value,
  8141. "get() cannot be used with reference types, you might want to use get_ref()");
  8142. static_assert(std::is_default_constructible<ValueType>::value,
  8143. "types must be DefaultConstructible when used with get()");
  8144. ValueType ret;
  8145. JSONSerializer<ValueType>::from_json(*this, ret);
  8146. return ret;
  8147. }
  8148. /*!
  8149. @brief get a value (explicit); special case
  8150. Explicit type conversion between the JSON value and a compatible value
  8151. which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
  8152. and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
  8153. The value is converted by calling the @ref json_serializer<ValueType>
  8154. `from_json()` method.
  8155. The function is equivalent to executing
  8156. @code {.cpp}
  8157. return JSONSerializer<ValueTypeCV>::from_json(*this);
  8158. @endcode
  8159. This overloads is chosen if:
  8160. - @a ValueType is not @ref basic_json and
  8161. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  8162. `ValueType from_json(const basic_json&)`
  8163. @note If @ref json_serializer<ValueType> has both overloads of
  8164. `from_json()`, this one is chosen.
  8165. @tparam ValueTypeCV the provided value type
  8166. @tparam ValueType the returned value type
  8167. @return copy of the JSON value, converted to @a ValueType
  8168. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  8169. @since version 2.1.0
  8170. */
  8171. template <
  8172. typename ValueTypeCV,
  8173. typename ValueType = detail::uncvref_t<ValueTypeCV>,
  8174. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  8175. detail::has_non_default_from_json<basic_json_t,
  8176. ValueType>::value, int> = 0 >
  8177. ValueType get() const noexcept(noexcept(
  8178. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  8179. {
  8180. static_assert(not std::is_reference<ValueTypeCV>::value,
  8181. "get() cannot be used with reference types, you might want to use get_ref()");
  8182. return JSONSerializer<ValueTypeCV>::from_json(*this);
  8183. }
  8184. /*!
  8185. @brief get a pointer value (explicit)
  8186. Explicit pointer access to the internally stored JSON value. No copies are
  8187. made.
  8188. @warning The pointer becomes invalid if the underlying JSON object
  8189. changes.
  8190. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  8191. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  8192. @ref number_unsigned_t, or @ref number_float_t.
  8193. @return pointer to the internally stored JSON value if the requested
  8194. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  8195. @complexity Constant.
  8196. @liveexample{The example below shows how pointers to internal values of a
  8197. JSON value can be requested. Note that no type conversions are made and a
  8198. `nullptr` is returned if the value and the requested pointer type does not
  8199. match.,get__PointerType}
  8200. @sa @ref get_ptr() for explicit pointer-member access
  8201. @since version 1.0.0
  8202. */
  8203. template<typename PointerType, typename std::enable_if<
  8204. std::is_pointer<PointerType>::value, int>::type = 0>
  8205. PointerType get() noexcept
  8206. {
  8207. // delegate the call to get_ptr
  8208. return get_ptr<PointerType>();
  8209. }
  8210. /*!
  8211. @brief get a pointer value (explicit)
  8212. @copydoc get()
  8213. */
  8214. template<typename PointerType, typename std::enable_if<
  8215. std::is_pointer<PointerType>::value, int>::type = 0>
  8216. constexpr const PointerType get() const noexcept
  8217. {
  8218. // delegate the call to get_ptr
  8219. return get_ptr<PointerType>();
  8220. }
  8221. /*!
  8222. @brief get a pointer value (implicit)
  8223. Implicit pointer access to the internally stored JSON value. No copies are
  8224. made.
  8225. @warning Writing data to the pointee of the result yields an undefined
  8226. state.
  8227. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  8228. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  8229. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  8230. assertion.
  8231. @return pointer to the internally stored JSON value if the requested
  8232. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  8233. @complexity Constant.
  8234. @liveexample{The example below shows how pointers to internal values of a
  8235. JSON value can be requested. Note that no type conversions are made and a
  8236. `nullptr` is returned if the value and the requested pointer type does not
  8237. match.,get_ptr}
  8238. @since version 1.0.0
  8239. */
  8240. template<typename PointerType, typename std::enable_if<
  8241. std::is_pointer<PointerType>::value, int>::type = 0>
  8242. PointerType get_ptr() noexcept
  8243. {
  8244. // get the type of the PointerType (remove pointer and const)
  8245. using pointee_t = typename std::remove_const<typename
  8246. std::remove_pointer<typename
  8247. std::remove_const<PointerType>::type>::type>::type;
  8248. // make sure the type matches the allowed types
  8249. static_assert(
  8250. std::is_same<object_t, pointee_t>::value
  8251. or std::is_same<array_t, pointee_t>::value
  8252. or std::is_same<string_t, pointee_t>::value
  8253. or std::is_same<boolean_t, pointee_t>::value
  8254. or std::is_same<number_integer_t, pointee_t>::value
  8255. or std::is_same<number_unsigned_t, pointee_t>::value
  8256. or std::is_same<number_float_t, pointee_t>::value
  8257. , "incompatible pointer type");
  8258. // delegate the call to get_impl_ptr<>()
  8259. return get_impl_ptr(static_cast<PointerType>(nullptr));
  8260. }
  8261. /*!
  8262. @brief get a pointer value (implicit)
  8263. @copydoc get_ptr()
  8264. */
  8265. template<typename PointerType, typename std::enable_if<
  8266. std::is_pointer<PointerType>::value and
  8267. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  8268. constexpr const PointerType get_ptr() const noexcept
  8269. {
  8270. // get the type of the PointerType (remove pointer and const)
  8271. using pointee_t = typename std::remove_const<typename
  8272. std::remove_pointer<typename
  8273. std::remove_const<PointerType>::type>::type>::type;
  8274. // make sure the type matches the allowed types
  8275. static_assert(
  8276. std::is_same<object_t, pointee_t>::value
  8277. or std::is_same<array_t, pointee_t>::value
  8278. or std::is_same<string_t, pointee_t>::value
  8279. or std::is_same<boolean_t, pointee_t>::value
  8280. or std::is_same<number_integer_t, pointee_t>::value
  8281. or std::is_same<number_unsigned_t, pointee_t>::value
  8282. or std::is_same<number_float_t, pointee_t>::value
  8283. , "incompatible pointer type");
  8284. // delegate the call to get_impl_ptr<>() const
  8285. return get_impl_ptr(static_cast<const PointerType>(nullptr));
  8286. }
  8287. /*!
  8288. @brief get a reference value (implicit)
  8289. Implicit reference access to the internally stored JSON value. No copies
  8290. are made.
  8291. @warning Writing data to the referee of the result yields an undefined
  8292. state.
  8293. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  8294. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  8295. @ref number_float_t. Enforced by static assertion.
  8296. @return reference to the internally stored JSON value if the requested
  8297. reference type @a ReferenceType fits to the JSON value; throws
  8298. type_error.303 otherwise
  8299. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  8300. with the stored JSON value; see example below
  8301. @complexity Constant.
  8302. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  8303. @since version 1.1.0
  8304. */
  8305. template<typename ReferenceType, typename std::enable_if<
  8306. std::is_reference<ReferenceType>::value, int>::type = 0>
  8307. ReferenceType get_ref()
  8308. {
  8309. // delegate call to get_ref_impl
  8310. return get_ref_impl<ReferenceType>(*this);
  8311. }
  8312. /*!
  8313. @brief get a reference value (implicit)
  8314. @copydoc get_ref()
  8315. */
  8316. template<typename ReferenceType, typename std::enable_if<
  8317. std::is_reference<ReferenceType>::value and
  8318. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  8319. ReferenceType get_ref() const
  8320. {
  8321. // delegate call to get_ref_impl
  8322. return get_ref_impl<ReferenceType>(*this);
  8323. }
  8324. /*!
  8325. @brief get a value (implicit)
  8326. Implicit type conversion between the JSON value and a compatible value.
  8327. The call is realized by calling @ref get() const.
  8328. @tparam ValueType non-pointer type compatible to the JSON value, for
  8329. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  8330. `std::vector` types for JSON arrays. The character type of @ref string_t
  8331. as well as an initializer list of this type is excluded to avoid
  8332. ambiguities as these types implicitly convert to `std::string`.
  8333. @return copy of the JSON value, converted to type @a ValueType
  8334. @throw type_error.302 in case passed type @a ValueType is incompatible
  8335. to the JSON value type (e.g., the JSON value is of type boolean, but a
  8336. string is requested); see example below
  8337. @complexity Linear in the size of the JSON value.
  8338. @liveexample{The example below shows several conversions from JSON values
  8339. to other types. There a few things to note: (1) Floating-point numbers can
  8340. be converted to integers\, (2) A JSON array can be converted to a standard
  8341. `std::vector<short>`\, (3) A JSON object can be converted to C++
  8342. associative containers such as `std::unordered_map<std::string\,
  8343. json>`.,operator__ValueType}
  8344. @since version 1.0.0
  8345. */
  8346. template < typename ValueType, typename std::enable_if <
  8347. not std::is_pointer<ValueType>::value and
  8348. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  8349. not std::is_same<ValueType, typename string_t::value_type>::value
  8350. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  8351. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  8352. #endif
  8353. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_MSC_VER) && _MSC_VER >1900 && defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  8354. and not std::is_same<ValueType, typename std::string_view>::value
  8355. #endif
  8356. , int >::type = 0 >
  8357. operator ValueType() const
  8358. {
  8359. // delegate the call to get<>() const
  8360. return get<ValueType>();
  8361. }
  8362. /// @}
  8363. ////////////////////
  8364. // element access //
  8365. ////////////////////
  8366. /// @name element access
  8367. /// Access to the JSON value.
  8368. /// @{
  8369. /*!
  8370. @brief access specified array element with bounds checking
  8371. Returns a reference to the element at specified location @a idx, with
  8372. bounds checking.
  8373. @param[in] idx index of the element to access
  8374. @return reference to the element at index @a idx
  8375. @throw type_error.304 if the JSON value is not an array; in this case,
  8376. calling `at` with an index makes no sense. See example below.
  8377. @throw out_of_range.401 if the index @a idx is out of range of the array;
  8378. that is, `idx >= size()`. See example below.
  8379. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8380. changes in the JSON value.
  8381. @complexity Constant.
  8382. @since version 1.0.0
  8383. @liveexample{The example below shows how array elements can be read and
  8384. written using `at()`. It also demonstrates the different exceptions that
  8385. can be thrown.,at__size_type}
  8386. */
  8387. reference at(size_type idx)
  8388. {
  8389. // at only works for arrays
  8390. if (JSON_LIKELY(is_array()))
  8391. {
  8392. JSON_TRY
  8393. {
  8394. return m_value.array->at(idx);
  8395. }
  8396. JSON_CATCH (std::out_of_range&)
  8397. {
  8398. // create better exception explanation
  8399. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  8400. }
  8401. }
  8402. else
  8403. {
  8404. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8405. }
  8406. }
  8407. /*!
  8408. @brief access specified array element with bounds checking
  8409. Returns a const reference to the element at specified location @a idx,
  8410. with bounds checking.
  8411. @param[in] idx index of the element to access
  8412. @return const reference to the element at index @a idx
  8413. @throw type_error.304 if the JSON value is not an array; in this case,
  8414. calling `at` with an index makes no sense. See example below.
  8415. @throw out_of_range.401 if the index @a idx is out of range of the array;
  8416. that is, `idx >= size()`. See example below.
  8417. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8418. changes in the JSON value.
  8419. @complexity Constant.
  8420. @since version 1.0.0
  8421. @liveexample{The example below shows how array elements can be read using
  8422. `at()`. It also demonstrates the different exceptions that can be thrown.,
  8423. at__size_type_const}
  8424. */
  8425. const_reference at(size_type idx) const
  8426. {
  8427. // at only works for arrays
  8428. if (JSON_LIKELY(is_array()))
  8429. {
  8430. JSON_TRY
  8431. {
  8432. return m_value.array->at(idx);
  8433. }
  8434. JSON_CATCH (std::out_of_range&)
  8435. {
  8436. // create better exception explanation
  8437. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  8438. }
  8439. }
  8440. else
  8441. {
  8442. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8443. }
  8444. }
  8445. /*!
  8446. @brief access specified object element with bounds checking
  8447. Returns a reference to the element at with specified key @a key, with
  8448. bounds checking.
  8449. @param[in] key key of the element to access
  8450. @return reference to the element at key @a key
  8451. @throw type_error.304 if the JSON value is not an object; in this case,
  8452. calling `at` with a key makes no sense. See example below.
  8453. @throw out_of_range.403 if the key @a key is is not stored in the object;
  8454. that is, `find(key) == end()`. See example below.
  8455. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8456. changes in the JSON value.
  8457. @complexity Logarithmic in the size of the container.
  8458. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8459. access by reference
  8460. @sa @ref value() for access by value with a default value
  8461. @since version 1.0.0
  8462. @liveexample{The example below shows how object elements can be read and
  8463. written using `at()`. It also demonstrates the different exceptions that
  8464. can be thrown.,at__object_t_key_type}
  8465. */
  8466. reference at(const typename object_t::key_type& key)
  8467. {
  8468. // at only works for objects
  8469. if (JSON_LIKELY(is_object()))
  8470. {
  8471. JSON_TRY
  8472. {
  8473. return m_value.object->at(key);
  8474. }
  8475. JSON_CATCH (std::out_of_range&)
  8476. {
  8477. // create better exception explanation
  8478. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  8479. }
  8480. }
  8481. else
  8482. {
  8483. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8484. }
  8485. }
  8486. /*!
  8487. @brief access specified object element with bounds checking
  8488. Returns a const reference to the element at with specified key @a key,
  8489. with bounds checking.
  8490. @param[in] key key of the element to access
  8491. @return const reference to the element at key @a key
  8492. @throw type_error.304 if the JSON value is not an object; in this case,
  8493. calling `at` with a key makes no sense. See example below.
  8494. @throw out_of_range.403 if the key @a key is is not stored in the object;
  8495. that is, `find(key) == end()`. See example below.
  8496. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  8497. changes in the JSON value.
  8498. @complexity Logarithmic in the size of the container.
  8499. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8500. access by reference
  8501. @sa @ref value() for access by value with a default value
  8502. @since version 1.0.0
  8503. @liveexample{The example below shows how object elements can be read using
  8504. `at()`. It also demonstrates the different exceptions that can be thrown.,
  8505. at__object_t_key_type_const}
  8506. */
  8507. const_reference at(const typename object_t::key_type& key) const
  8508. {
  8509. // at only works for objects
  8510. if (JSON_LIKELY(is_object()))
  8511. {
  8512. JSON_TRY
  8513. {
  8514. return m_value.object->at(key);
  8515. }
  8516. JSON_CATCH (std::out_of_range&)
  8517. {
  8518. // create better exception explanation
  8519. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  8520. }
  8521. }
  8522. else
  8523. {
  8524. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  8525. }
  8526. }
  8527. /*!
  8528. @brief access specified array element
  8529. Returns a reference to the element at specified location @a idx.
  8530. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  8531. then the array is silently filled up with `null` values to make `idx` a
  8532. valid reference to the last stored element.
  8533. @param[in] idx index of the element to access
  8534. @return reference to the element at index @a idx
  8535. @throw type_error.305 if the JSON value is not an array or null; in that
  8536. cases, using the [] operator with an index makes no sense.
  8537. @complexity Constant if @a idx is in the range of the array. Otherwise
  8538. linear in `idx - size()`.
  8539. @liveexample{The example below shows how array elements can be read and
  8540. written using `[]` operator. Note the addition of `null`
  8541. values.,operatorarray__size_type}
  8542. @since version 1.0.0
  8543. */
  8544. reference operator[](size_type idx)
  8545. {
  8546. // implicitly convert null value to an empty array
  8547. if (is_null())
  8548. {
  8549. m_type = value_t::array;
  8550. m_value.array = create<array_t>();
  8551. assert_invariant();
  8552. }
  8553. // operator[] only works for arrays
  8554. if (JSON_LIKELY(is_array()))
  8555. {
  8556. // fill up array with null values if given idx is outside range
  8557. if (idx >= m_value.array->size())
  8558. {
  8559. m_value.array->insert(m_value.array->end(),
  8560. idx - m_value.array->size() + 1,
  8561. basic_json());
  8562. }
  8563. return m_value.array->operator[](idx);
  8564. }
  8565. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8566. }
  8567. /*!
  8568. @brief access specified array element
  8569. Returns a const reference to the element at specified location @a idx.
  8570. @param[in] idx index of the element to access
  8571. @return const reference to the element at index @a idx
  8572. @throw type_error.305 if the JSON value is not an array; in that cases,
  8573. using the [] operator with an index makes no sense.
  8574. @complexity Constant.
  8575. @liveexample{The example below shows how array elements can be read using
  8576. the `[]` operator.,operatorarray__size_type_const}
  8577. @since version 1.0.0
  8578. */
  8579. const_reference operator[](size_type idx) const
  8580. {
  8581. // const operator[] only works for arrays
  8582. if (JSON_LIKELY(is_array()))
  8583. {
  8584. return m_value.array->operator[](idx);
  8585. }
  8586. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8587. }
  8588. /*!
  8589. @brief access specified object element
  8590. Returns a reference to the element at with specified key @a key.
  8591. @note If @a key is not found in the object, then it is silently added to
  8592. the object and filled with a `null` value to make `key` a valid reference.
  8593. In case the value was `null` before, it is converted to an object.
  8594. @param[in] key key of the element to access
  8595. @return reference to the element at key @a key
  8596. @throw type_error.305 if the JSON value is not an object or null; in that
  8597. cases, using the [] operator with a key makes no sense.
  8598. @complexity Logarithmic in the size of the container.
  8599. @liveexample{The example below shows how object elements can be read and
  8600. written using the `[]` operator.,operatorarray__key_type}
  8601. @sa @ref at(const typename object_t::key_type&) for access by reference
  8602. with range checking
  8603. @sa @ref value() for access by value with a default value
  8604. @since version 1.0.0
  8605. */
  8606. reference operator[](const typename object_t::key_type& key)
  8607. {
  8608. // implicitly convert null value to an empty object
  8609. if (is_null())
  8610. {
  8611. m_type = value_t::object;
  8612. m_value.object = create<object_t>();
  8613. assert_invariant();
  8614. }
  8615. // operator[] only works for objects
  8616. if (JSON_LIKELY(is_object()))
  8617. {
  8618. return m_value.object->operator[](key);
  8619. }
  8620. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8621. }
  8622. /*!
  8623. @brief read-only access specified object element
  8624. Returns a const reference to the element at with specified key @a key. No
  8625. bounds checking is performed.
  8626. @warning If the element with key @a key does not exist, the behavior is
  8627. undefined.
  8628. @param[in] key key of the element to access
  8629. @return const reference to the element at key @a key
  8630. @pre The element with key @a key must exist. **This precondition is
  8631. enforced with an assertion.**
  8632. @throw type_error.305 if the JSON value is not an object; in that cases,
  8633. using the [] operator with a key makes no sense.
  8634. @complexity Logarithmic in the size of the container.
  8635. @liveexample{The example below shows how object elements can be read using
  8636. the `[]` operator.,operatorarray__key_type_const}
  8637. @sa @ref at(const typename object_t::key_type&) for access by reference
  8638. with range checking
  8639. @sa @ref value() for access by value with a default value
  8640. @since version 1.0.0
  8641. */
  8642. const_reference operator[](const typename object_t::key_type& key) const
  8643. {
  8644. // const operator[] only works for objects
  8645. if (JSON_LIKELY(is_object()))
  8646. {
  8647. assert(m_value.object->find(key) != m_value.object->end());
  8648. return m_value.object->find(key)->second;
  8649. }
  8650. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8651. }
  8652. /*!
  8653. @brief access specified object element
  8654. Returns a reference to the element at with specified key @a key.
  8655. @note If @a key is not found in the object, then it is silently added to
  8656. the object and filled with a `null` value to make `key` a valid reference.
  8657. In case the value was `null` before, it is converted to an object.
  8658. @param[in] key key of the element to access
  8659. @return reference to the element at key @a key
  8660. @throw type_error.305 if the JSON value is not an object or null; in that
  8661. cases, using the [] operator with a key makes no sense.
  8662. @complexity Logarithmic in the size of the container.
  8663. @liveexample{The example below shows how object elements can be read and
  8664. written using the `[]` operator.,operatorarray__key_type}
  8665. @sa @ref at(const typename object_t::key_type&) for access by reference
  8666. with range checking
  8667. @sa @ref value() for access by value with a default value
  8668. @since version 1.1.0
  8669. */
  8670. template<typename T>
  8671. reference operator[](T* key)
  8672. {
  8673. // implicitly convert null to object
  8674. if (is_null())
  8675. {
  8676. m_type = value_t::object;
  8677. m_value = value_t::object;
  8678. assert_invariant();
  8679. }
  8680. // at only works for objects
  8681. if (JSON_LIKELY(is_object()))
  8682. {
  8683. return m_value.object->operator[](key);
  8684. }
  8685. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8686. }
  8687. /*!
  8688. @brief read-only access specified object element
  8689. Returns a const reference to the element at with specified key @a key. No
  8690. bounds checking is performed.
  8691. @warning If the element with key @a key does not exist, the behavior is
  8692. undefined.
  8693. @param[in] key key of the element to access
  8694. @return const reference to the element at key @a key
  8695. @pre The element with key @a key must exist. **This precondition is
  8696. enforced with an assertion.**
  8697. @throw type_error.305 if the JSON value is not an object; in that cases,
  8698. using the [] operator with a key makes no sense.
  8699. @complexity Logarithmic in the size of the container.
  8700. @liveexample{The example below shows how object elements can be read using
  8701. the `[]` operator.,operatorarray__key_type_const}
  8702. @sa @ref at(const typename object_t::key_type&) for access by reference
  8703. with range checking
  8704. @sa @ref value() for access by value with a default value
  8705. @since version 1.1.0
  8706. */
  8707. template<typename T>
  8708. const_reference operator[](T* key) const
  8709. {
  8710. // at only works for objects
  8711. if (JSON_LIKELY(is_object()))
  8712. {
  8713. assert(m_value.object->find(key) != m_value.object->end());
  8714. return m_value.object->find(key)->second;
  8715. }
  8716. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  8717. }
  8718. /*!
  8719. @brief access specified object element with default value
  8720. Returns either a copy of an object's element at the specified key @a key
  8721. or a given default value if no element with key @a key exists.
  8722. The function is basically equivalent to executing
  8723. @code {.cpp}
  8724. try {
  8725. return at(key);
  8726. } catch(out_of_range) {
  8727. return default_value;
  8728. }
  8729. @endcode
  8730. @note Unlike @ref at(const typename object_t::key_type&), this function
  8731. does not throw if the given key @a key was not found.
  8732. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  8733. function does not implicitly add an element to the position defined by @a
  8734. key. This function is furthermore also applicable to const objects.
  8735. @param[in] key key of the element to access
  8736. @param[in] default_value the value to return if @a key is not found
  8737. @tparam ValueType type compatible to JSON values, for instance `int` for
  8738. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  8739. JSON arrays. Note the type of the expected value at @a key and the default
  8740. value @a default_value must be compatible.
  8741. @return copy of the element at key @a key or @a default_value if @a key
  8742. is not found
  8743. @throw type_error.306 if the JSON value is not an objec; in that cases,
  8744. using `value()` with a key makes no sense.
  8745. @complexity Logarithmic in the size of the container.
  8746. @liveexample{The example below shows how object elements can be queried
  8747. with a default value.,basic_json__value}
  8748. @sa @ref at(const typename object_t::key_type&) for access by reference
  8749. with range checking
  8750. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  8751. access by reference
  8752. @since version 1.0.0
  8753. */
  8754. template<class ValueType, typename std::enable_if<
  8755. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  8756. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  8757. {
  8758. // at only works for objects
  8759. if (JSON_LIKELY(is_object()))
  8760. {
  8761. // if key is found, return value and given default value otherwise
  8762. const auto it = find(key);
  8763. if (it != end())
  8764. {
  8765. return *it;
  8766. }
  8767. return default_value;
  8768. }
  8769. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  8770. }
  8771. /*!
  8772. @brief overload for a default value of type const char*
  8773. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  8774. */
  8775. string_t value(const typename object_t::key_type& key, const char* default_value) const
  8776. {
  8777. return value(key, string_t(default_value));
  8778. }
  8779. /*!
  8780. @brief access specified object element via JSON Pointer with default value
  8781. Returns either a copy of an object's element at the specified key @a key
  8782. or a given default value if no element with key @a key exists.
  8783. The function is basically equivalent to executing
  8784. @code {.cpp}
  8785. try {
  8786. return at(ptr);
  8787. } catch(out_of_range) {
  8788. return default_value;
  8789. }
  8790. @endcode
  8791. @note Unlike @ref at(const json_pointer&), this function does not throw
  8792. if the given key @a key was not found.
  8793. @param[in] ptr a JSON pointer to the element to access
  8794. @param[in] default_value the value to return if @a ptr found no value
  8795. @tparam ValueType type compatible to JSON values, for instance `int` for
  8796. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  8797. JSON arrays. Note the type of the expected value at @a key and the default
  8798. value @a default_value must be compatible.
  8799. @return copy of the element at key @a key or @a default_value if @a key
  8800. is not found
  8801. @throw type_error.306 if the JSON value is not an objec; in that cases,
  8802. using `value()` with a key makes no sense.
  8803. @complexity Logarithmic in the size of the container.
  8804. @liveexample{The example below shows how object elements can be queried
  8805. with a default value.,basic_json__value_ptr}
  8806. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  8807. @since version 2.0.2
  8808. */
  8809. template<class ValueType, typename std::enable_if<
  8810. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  8811. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  8812. {
  8813. // at only works for objects
  8814. if (JSON_LIKELY(is_object()))
  8815. {
  8816. // if pointer resolves a value, return it or use default value
  8817. JSON_TRY
  8818. {
  8819. return ptr.get_checked(this);
  8820. }
  8821. JSON_CATCH (out_of_range&)
  8822. {
  8823. return default_value;
  8824. }
  8825. }
  8826. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  8827. }
  8828. /*!
  8829. @brief overload for a default value of type const char*
  8830. @copydoc basic_json::value(const json_pointer&, ValueType) const
  8831. */
  8832. string_t value(const json_pointer& ptr, const char* default_value) const
  8833. {
  8834. return value(ptr, string_t(default_value));
  8835. }
  8836. /*!
  8837. @brief access the first element
  8838. Returns a reference to the first element in the container. For a JSON
  8839. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  8840. @return In case of a structured type (array or object), a reference to the
  8841. first element is returned. In case of number, string, or boolean values, a
  8842. reference to the value is returned.
  8843. @complexity Constant.
  8844. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  8845. or an empty array or object (undefined behavior, **guarded by
  8846. assertions**).
  8847. @post The JSON value remains unchanged.
  8848. @throw invalid_iterator.214 when called on `null` value
  8849. @liveexample{The following code shows an example for `front()`.,front}
  8850. @sa @ref back() -- access the last element
  8851. @since version 1.0.0
  8852. */
  8853. reference front()
  8854. {
  8855. return *begin();
  8856. }
  8857. /*!
  8858. @copydoc basic_json::front()
  8859. */
  8860. const_reference front() const
  8861. {
  8862. return *cbegin();
  8863. }
  8864. /*!
  8865. @brief access the last element
  8866. Returns a reference to the last element in the container. For a JSON
  8867. container `c`, the expression `c.back()` is equivalent to
  8868. @code {.cpp}
  8869. auto tmp = c.end();
  8870. --tmp;
  8871. return *tmp;
  8872. @endcode
  8873. @return In case of a structured type (array or object), a reference to the
  8874. last element is returned. In case of number, string, or boolean values, a
  8875. reference to the value is returned.
  8876. @complexity Constant.
  8877. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  8878. or an empty array or object (undefined behavior, **guarded by
  8879. assertions**).
  8880. @post The JSON value remains unchanged.
  8881. @throw invalid_iterator.214 when called on a `null` value. See example
  8882. below.
  8883. @liveexample{The following code shows an example for `back()`.,back}
  8884. @sa @ref front() -- access the first element
  8885. @since version 1.0.0
  8886. */
  8887. reference back()
  8888. {
  8889. auto tmp = end();
  8890. --tmp;
  8891. return *tmp;
  8892. }
  8893. /*!
  8894. @copydoc basic_json::back()
  8895. */
  8896. const_reference back() const
  8897. {
  8898. auto tmp = cend();
  8899. --tmp;
  8900. return *tmp;
  8901. }
  8902. /*!
  8903. @brief remove element given an iterator
  8904. Removes the element specified by iterator @a pos. The iterator @a pos must
  8905. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  8906. but is not dereferenceable) cannot be used as a value for @a pos.
  8907. If called on a primitive type other than `null`, the resulting JSON value
  8908. will be `null`.
  8909. @param[in] pos iterator to the element to remove
  8910. @return Iterator following the last removed element. If the iterator @a
  8911. pos refers to the last element, the `end()` iterator is returned.
  8912. @tparam IteratorType an @ref iterator or @ref const_iterator
  8913. @post Invalidates iterators and references at or after the point of the
  8914. erase, including the `end()` iterator.
  8915. @throw type_error.307 if called on a `null` value; example: `"cannot use
  8916. erase() with null"`
  8917. @throw invalid_iterator.202 if called on an iterator which does not belong
  8918. to the current JSON value; example: `"iterator does not fit current
  8919. value"`
  8920. @throw invalid_iterator.205 if called on a primitive type with invalid
  8921. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  8922. out of range"`
  8923. @complexity The complexity depends on the type:
  8924. - objects: amortized constant
  8925. - arrays: linear in distance between @a pos and the end of the container
  8926. - strings: linear in the length of the string
  8927. - other types: constant
  8928. @liveexample{The example shows the result of `erase()` for different JSON
  8929. types.,erase__IteratorType}
  8930. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  8931. the given range
  8932. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  8933. from an object at the given key
  8934. @sa @ref erase(const size_type) -- removes the element from an array at
  8935. the given index
  8936. @since version 1.0.0
  8937. */
  8938. template<class IteratorType, typename std::enable_if<
  8939. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  8940. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  8941. = 0>
  8942. IteratorType erase(IteratorType pos)
  8943. {
  8944. // make sure iterator fits the current value
  8945. if (JSON_UNLIKELY(this != pos.m_object))
  8946. {
  8947. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  8948. }
  8949. IteratorType result = end();
  8950. switch (m_type)
  8951. {
  8952. case value_t::boolean:
  8953. case value_t::number_float:
  8954. case value_t::number_integer:
  8955. case value_t::number_unsigned:
  8956. case value_t::string:
  8957. {
  8958. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  8959. {
  8960. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  8961. }
  8962. if (is_string())
  8963. {
  8964. AllocatorType<string_t> alloc;
  8965. alloc.destroy(m_value.string);
  8966. alloc.deallocate(m_value.string, 1);
  8967. m_value.string = nullptr;
  8968. }
  8969. m_type = value_t::null;
  8970. assert_invariant();
  8971. break;
  8972. }
  8973. case value_t::object:
  8974. {
  8975. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  8976. break;
  8977. }
  8978. case value_t::array:
  8979. {
  8980. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  8981. break;
  8982. }
  8983. default:
  8984. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  8985. }
  8986. return result;
  8987. }
  8988. /*!
  8989. @brief remove elements given an iterator range
  8990. Removes the element specified by the range `[first; last)`. The iterator
  8991. @a first does not need to be dereferenceable if `first == last`: erasing
  8992. an empty range is a no-op.
  8993. If called on a primitive type other than `null`, the resulting JSON value
  8994. will be `null`.
  8995. @param[in] first iterator to the beginning of the range to remove
  8996. @param[in] last iterator past the end of the range to remove
  8997. @return Iterator following the last removed element. If the iterator @a
  8998. second refers to the last element, the `end()` iterator is returned.
  8999. @tparam IteratorType an @ref iterator or @ref const_iterator
  9000. @post Invalidates iterators and references at or after the point of the
  9001. erase, including the `end()` iterator.
  9002. @throw type_error.307 if called on a `null` value; example: `"cannot use
  9003. erase() with null"`
  9004. @throw invalid_iterator.203 if called on iterators which does not belong
  9005. to the current JSON value; example: `"iterators do not fit current value"`
  9006. @throw invalid_iterator.204 if called on a primitive type with invalid
  9007. iterators (i.e., if `first != begin()` and `last != end()`); example:
  9008. `"iterators out of range"`
  9009. @complexity The complexity depends on the type:
  9010. - objects: `log(size()) + std::distance(first, last)`
  9011. - arrays: linear in the distance between @a first and @a last, plus linear
  9012. in the distance between @a last and end of the container
  9013. - strings: linear in the length of the string
  9014. - other types: constant
  9015. @liveexample{The example shows the result of `erase()` for different JSON
  9016. types.,erase__IteratorType_IteratorType}
  9017. @sa @ref erase(IteratorType) -- removes the element at a given position
  9018. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  9019. from an object at the given key
  9020. @sa @ref erase(const size_type) -- removes the element from an array at
  9021. the given index
  9022. @since version 1.0.0
  9023. */
  9024. template<class IteratorType, typename std::enable_if<
  9025. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  9026. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  9027. = 0>
  9028. IteratorType erase(IteratorType first, IteratorType last)
  9029. {
  9030. // make sure iterator fits the current value
  9031. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  9032. {
  9033. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  9034. }
  9035. IteratorType result = end();
  9036. switch (m_type)
  9037. {
  9038. case value_t::boolean:
  9039. case value_t::number_float:
  9040. case value_t::number_integer:
  9041. case value_t::number_unsigned:
  9042. case value_t::string:
  9043. {
  9044. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  9045. or not last.m_it.primitive_iterator.is_end()))
  9046. {
  9047. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  9048. }
  9049. if (is_string())
  9050. {
  9051. AllocatorType<string_t> alloc;
  9052. alloc.destroy(m_value.string);
  9053. alloc.deallocate(m_value.string, 1);
  9054. m_value.string = nullptr;
  9055. }
  9056. m_type = value_t::null;
  9057. assert_invariant();
  9058. break;
  9059. }
  9060. case value_t::object:
  9061. {
  9062. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  9063. last.m_it.object_iterator);
  9064. break;
  9065. }
  9066. case value_t::array:
  9067. {
  9068. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  9069. last.m_it.array_iterator);
  9070. break;
  9071. }
  9072. default:
  9073. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9074. }
  9075. return result;
  9076. }
  9077. /*!
  9078. @brief remove element from a JSON object given a key
  9079. Removes elements from a JSON object with the key value @a key.
  9080. @param[in] key value of the elements to remove
  9081. @return Number of elements removed. If @a ObjectType is the default
  9082. `std::map` type, the return value will always be `0` (@a key was not
  9083. found) or `1` (@a key was found).
  9084. @post References and iterators to the erased elements are invalidated.
  9085. Other references and iterators are not affected.
  9086. @throw type_error.307 when called on a type other than JSON object;
  9087. example: `"cannot use erase() with null"`
  9088. @complexity `log(size()) + count(key)`
  9089. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  9090. @sa @ref erase(IteratorType) -- removes the element at a given position
  9091. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  9092. the given range
  9093. @sa @ref erase(const size_type) -- removes the element from an array at
  9094. the given index
  9095. @since version 1.0.0
  9096. */
  9097. size_type erase(const typename object_t::key_type& key)
  9098. {
  9099. // this erase only works for objects
  9100. if (JSON_LIKELY(is_object()))
  9101. {
  9102. return m_value.object->erase(key);
  9103. }
  9104. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9105. }
  9106. /*!
  9107. @brief remove element from a JSON array given an index
  9108. Removes element from a JSON array at the index @a idx.
  9109. @param[in] idx index of the element to remove
  9110. @throw type_error.307 when called on a type other than JSON object;
  9111. example: `"cannot use erase() with null"`
  9112. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  9113. is out of range"`
  9114. @complexity Linear in distance between @a idx and the end of the container.
  9115. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  9116. @sa @ref erase(IteratorType) -- removes the element at a given position
  9117. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  9118. the given range
  9119. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  9120. from an object at the given key
  9121. @since version 1.0.0
  9122. */
  9123. void erase(const size_type idx)
  9124. {
  9125. // this erase only works for arrays
  9126. if (JSON_LIKELY(is_array()))
  9127. {
  9128. if (JSON_UNLIKELY(idx >= size()))
  9129. {
  9130. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  9131. }
  9132. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  9133. }
  9134. else
  9135. {
  9136. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  9137. }
  9138. }
  9139. /// @}
  9140. ////////////
  9141. // lookup //
  9142. ////////////
  9143. /// @name lookup
  9144. /// @{
  9145. /*!
  9146. @brief find an element in a JSON object
  9147. Finds an element in a JSON object with key equivalent to @a key. If the
  9148. element is not found or the JSON value is not an object, end() is
  9149. returned.
  9150. @note This method always returns @ref end() when executed on a JSON type
  9151. that is not an object.
  9152. @param[in] key key value of the element to search for
  9153. @return Iterator to an element with key equivalent to @a key. If no such
  9154. element is found or the JSON value is not an object, past-the-end (see
  9155. @ref end()) iterator is returned.
  9156. @complexity Logarithmic in the size of the JSON object.
  9157. @liveexample{The example shows how `find()` is used.,find__key_type}
  9158. @since version 1.0.0
  9159. */
  9160. iterator find(typename object_t::key_type key)
  9161. {
  9162. auto result = end();
  9163. if (is_object())
  9164. {
  9165. result.m_it.object_iterator = m_value.object->find(key);
  9166. }
  9167. return result;
  9168. }
  9169. /*!
  9170. @brief find an element in a JSON object
  9171. @copydoc find(typename object_t::key_type)
  9172. */
  9173. const_iterator find(typename object_t::key_type key) const
  9174. {
  9175. auto result = cend();
  9176. if (is_object())
  9177. {
  9178. result.m_it.object_iterator = m_value.object->find(key);
  9179. }
  9180. return result;
  9181. }
  9182. /*!
  9183. @brief returns the number of occurrences of a key in a JSON object
  9184. Returns the number of elements with key @a key. If ObjectType is the
  9185. default `std::map` type, the return value will always be `0` (@a key was
  9186. not found) or `1` (@a key was found).
  9187. @note This method always returns `0` when executed on a JSON type that is
  9188. not an object.
  9189. @param[in] key key value of the element to count
  9190. @return Number of elements with key @a key. If the JSON value is not an
  9191. object, the return value will be `0`.
  9192. @complexity Logarithmic in the size of the JSON object.
  9193. @liveexample{The example shows how `count()` is used.,count}
  9194. @since version 1.0.0
  9195. */
  9196. size_type count(typename object_t::key_type key) const
  9197. {
  9198. // return 0 for all nonobject types
  9199. return is_object() ? m_value.object->count(key) : 0;
  9200. }
  9201. /// @}
  9202. ///////////////
  9203. // iterators //
  9204. ///////////////
  9205. /// @name iterators
  9206. /// @{
  9207. /*!
  9208. @brief returns an iterator to the first element
  9209. Returns an iterator to the first element.
  9210. @image html range-begin-end.svg "Illustration from cppreference.com"
  9211. @return iterator to the first element
  9212. @complexity Constant.
  9213. @requirement This function helps `basic_json` satisfying the
  9214. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9215. requirements:
  9216. - The complexity is constant.
  9217. @liveexample{The following code shows an example for `begin()`.,begin}
  9218. @sa @ref cbegin() -- returns a const iterator to the beginning
  9219. @sa @ref end() -- returns an iterator to the end
  9220. @sa @ref cend() -- returns a const iterator to the end
  9221. @since version 1.0.0
  9222. */
  9223. iterator begin() noexcept
  9224. {
  9225. iterator result(this);
  9226. result.set_begin();
  9227. return result;
  9228. }
  9229. /*!
  9230. @copydoc basic_json::cbegin()
  9231. */
  9232. const_iterator begin() const noexcept
  9233. {
  9234. return cbegin();
  9235. }
  9236. /*!
  9237. @brief returns a const iterator to the first element
  9238. Returns a const iterator to the first element.
  9239. @image html range-begin-end.svg "Illustration from cppreference.com"
  9240. @return const iterator to the first element
  9241. @complexity Constant.
  9242. @requirement This function helps `basic_json` satisfying the
  9243. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9244. requirements:
  9245. - The complexity is constant.
  9246. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  9247. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  9248. @sa @ref begin() -- returns an iterator to the beginning
  9249. @sa @ref end() -- returns an iterator to the end
  9250. @sa @ref cend() -- returns a const iterator to the end
  9251. @since version 1.0.0
  9252. */
  9253. const_iterator cbegin() const noexcept
  9254. {
  9255. const_iterator result(this);
  9256. result.set_begin();
  9257. return result;
  9258. }
  9259. /*!
  9260. @brief returns an iterator to one past the last element
  9261. Returns an iterator to one past the last element.
  9262. @image html range-begin-end.svg "Illustration from cppreference.com"
  9263. @return iterator one past the last element
  9264. @complexity Constant.
  9265. @requirement This function helps `basic_json` satisfying the
  9266. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9267. requirements:
  9268. - The complexity is constant.
  9269. @liveexample{The following code shows an example for `end()`.,end}
  9270. @sa @ref cend() -- returns a const iterator to the end
  9271. @sa @ref begin() -- returns an iterator to the beginning
  9272. @sa @ref cbegin() -- returns a const iterator to the beginning
  9273. @since version 1.0.0
  9274. */
  9275. iterator end() noexcept
  9276. {
  9277. iterator result(this);
  9278. result.set_end();
  9279. return result;
  9280. }
  9281. /*!
  9282. @copydoc basic_json::cend()
  9283. */
  9284. const_iterator end() const noexcept
  9285. {
  9286. return cend();
  9287. }
  9288. /*!
  9289. @brief returns a const iterator to one past the last element
  9290. Returns a const iterator to one past the last element.
  9291. @image html range-begin-end.svg "Illustration from cppreference.com"
  9292. @return const iterator one past the last element
  9293. @complexity Constant.
  9294. @requirement This function helps `basic_json` satisfying the
  9295. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9296. requirements:
  9297. - The complexity is constant.
  9298. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  9299. @liveexample{The following code shows an example for `cend()`.,cend}
  9300. @sa @ref end() -- returns an iterator to the end
  9301. @sa @ref begin() -- returns an iterator to the beginning
  9302. @sa @ref cbegin() -- returns a const iterator to the beginning
  9303. @since version 1.0.0
  9304. */
  9305. const_iterator cend() const noexcept
  9306. {
  9307. const_iterator result(this);
  9308. result.set_end();
  9309. return result;
  9310. }
  9311. /*!
  9312. @brief returns an iterator to the reverse-beginning
  9313. Returns an iterator to the reverse-beginning; that is, the last element.
  9314. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9315. @complexity Constant.
  9316. @requirement This function helps `basic_json` satisfying the
  9317. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9318. requirements:
  9319. - The complexity is constant.
  9320. - Has the semantics of `reverse_iterator(end())`.
  9321. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  9322. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9323. @sa @ref rend() -- returns a reverse iterator to the end
  9324. @sa @ref crend() -- returns a const reverse iterator to the end
  9325. @since version 1.0.0
  9326. */
  9327. reverse_iterator rbegin() noexcept
  9328. {
  9329. return reverse_iterator(end());
  9330. }
  9331. /*!
  9332. @copydoc basic_json::crbegin()
  9333. */
  9334. const_reverse_iterator rbegin() const noexcept
  9335. {
  9336. return crbegin();
  9337. }
  9338. /*!
  9339. @brief returns an iterator to the reverse-end
  9340. Returns an iterator to the reverse-end; that is, one before the first
  9341. element.
  9342. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9343. @complexity Constant.
  9344. @requirement This function helps `basic_json` satisfying the
  9345. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9346. requirements:
  9347. - The complexity is constant.
  9348. - Has the semantics of `reverse_iterator(begin())`.
  9349. @liveexample{The following code shows an example for `rend()`.,rend}
  9350. @sa @ref crend() -- returns a const reverse iterator to the end
  9351. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9352. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9353. @since version 1.0.0
  9354. */
  9355. reverse_iterator rend() noexcept
  9356. {
  9357. return reverse_iterator(begin());
  9358. }
  9359. /*!
  9360. @copydoc basic_json::crend()
  9361. */
  9362. const_reverse_iterator rend() const noexcept
  9363. {
  9364. return crend();
  9365. }
  9366. /*!
  9367. @brief returns a const reverse iterator to the last element
  9368. Returns a const iterator to the reverse-beginning; that is, the last
  9369. element.
  9370. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9371. @complexity Constant.
  9372. @requirement This function helps `basic_json` satisfying the
  9373. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9374. requirements:
  9375. - The complexity is constant.
  9376. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  9377. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  9378. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9379. @sa @ref rend() -- returns a reverse iterator to the end
  9380. @sa @ref crend() -- returns a const reverse iterator to the end
  9381. @since version 1.0.0
  9382. */
  9383. const_reverse_iterator crbegin() const noexcept
  9384. {
  9385. return const_reverse_iterator(cend());
  9386. }
  9387. /*!
  9388. @brief returns a const reverse iterator to one before the first
  9389. Returns a const reverse iterator to the reverse-end; that is, one before
  9390. the first element.
  9391. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  9392. @complexity Constant.
  9393. @requirement This function helps `basic_json` satisfying the
  9394. [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
  9395. requirements:
  9396. - The complexity is constant.
  9397. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  9398. @liveexample{The following code shows an example for `crend()`.,crend}
  9399. @sa @ref rend() -- returns a reverse iterator to the end
  9400. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  9401. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  9402. @since version 1.0.0
  9403. */
  9404. const_reverse_iterator crend() const noexcept
  9405. {
  9406. return const_reverse_iterator(cbegin());
  9407. }
  9408. public:
  9409. /*!
  9410. @brief wrapper to access iterator member functions in range-based for
  9411. This function allows to access @ref iterator::key() and @ref
  9412. iterator::value() during range-based for loops. In these loops, a
  9413. reference to the JSON values is returned, so there is no access to the
  9414. underlying iterator.
  9415. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  9416. @note The name of this function is not yet final and may change in the
  9417. future.
  9418. */
  9419. static iteration_proxy<iterator> iterator_wrapper(reference cont)
  9420. {
  9421. return iteration_proxy<iterator>(cont);
  9422. }
  9423. /*!
  9424. @copydoc iterator_wrapper(reference)
  9425. */
  9426. static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
  9427. {
  9428. return iteration_proxy<const_iterator>(cont);
  9429. }
  9430. /// @}
  9431. //////////////
  9432. // capacity //
  9433. //////////////
  9434. /// @name capacity
  9435. /// @{
  9436. /*!
  9437. @brief checks whether the container is empty.
  9438. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  9439. @return The return value depends on the different types and is
  9440. defined as follows:
  9441. Value type | return value
  9442. ----------- | -------------
  9443. null | `true`
  9444. boolean | `false`
  9445. string | `false`
  9446. number | `false`
  9447. object | result of function `object_t::empty()`
  9448. array | result of function `array_t::empty()`
  9449. @liveexample{The following code uses `empty()` to check if a JSON
  9450. object contains any elements.,empty}
  9451. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9452. the Container concept; that is, their `empty()` functions have constant
  9453. complexity.
  9454. @iterators No changes.
  9455. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9456. @note This function does not return whether a string stored as JSON value
  9457. is empty - it returns whether the JSON container itself is empty which is
  9458. false in the case of a string.
  9459. @requirement This function helps `basic_json` satisfying the
  9460. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9461. requirements:
  9462. - The complexity is constant.
  9463. - Has the semantics of `begin() == end()`.
  9464. @sa @ref size() -- returns the number of elements
  9465. @since version 1.0.0
  9466. */
  9467. bool empty() const noexcept
  9468. {
  9469. switch (m_type)
  9470. {
  9471. case value_t::null:
  9472. {
  9473. // null values are empty
  9474. return true;
  9475. }
  9476. case value_t::array:
  9477. {
  9478. // delegate call to array_t::empty()
  9479. return m_value.array->empty();
  9480. }
  9481. case value_t::object:
  9482. {
  9483. // delegate call to object_t::empty()
  9484. return m_value.object->empty();
  9485. }
  9486. default:
  9487. {
  9488. // all other types are nonempty
  9489. return false;
  9490. }
  9491. }
  9492. }
  9493. /*!
  9494. @brief returns the number of elements
  9495. Returns the number of elements in a JSON value.
  9496. @return The return value depends on the different types and is
  9497. defined as follows:
  9498. Value type | return value
  9499. ----------- | -------------
  9500. null | `0`
  9501. boolean | `1`
  9502. string | `1`
  9503. number | `1`
  9504. object | result of function object_t::size()
  9505. array | result of function array_t::size()
  9506. @liveexample{The following code calls `size()` on the different value
  9507. types.,size}
  9508. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9509. the Container concept; that is, their size() functions have constant
  9510. complexity.
  9511. @iterators No changes.
  9512. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9513. @note This function does not return the length of a string stored as JSON
  9514. value - it returns the number of elements in the JSON value which is 1 in
  9515. the case of a string.
  9516. @requirement This function helps `basic_json` satisfying the
  9517. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9518. requirements:
  9519. - The complexity is constant.
  9520. - Has the semantics of `std::distance(begin(), end())`.
  9521. @sa @ref empty() -- checks whether the container is empty
  9522. @sa @ref max_size() -- returns the maximal number of elements
  9523. @since version 1.0.0
  9524. */
  9525. size_type size() const noexcept
  9526. {
  9527. switch (m_type)
  9528. {
  9529. case value_t::null:
  9530. {
  9531. // null values are empty
  9532. return 0;
  9533. }
  9534. case value_t::array:
  9535. {
  9536. // delegate call to array_t::size()
  9537. return m_value.array->size();
  9538. }
  9539. case value_t::object:
  9540. {
  9541. // delegate call to object_t::size()
  9542. return m_value.object->size();
  9543. }
  9544. default:
  9545. {
  9546. // all other types have size 1
  9547. return 1;
  9548. }
  9549. }
  9550. }
  9551. /*!
  9552. @brief returns the maximum possible number of elements
  9553. Returns the maximum number of elements a JSON value is able to hold due to
  9554. system or library implementation limitations, i.e. `std::distance(begin(),
  9555. end())` for the JSON value.
  9556. @return The return value depends on the different types and is
  9557. defined as follows:
  9558. Value type | return value
  9559. ----------- | -------------
  9560. null | `0` (same as `size()`)
  9561. boolean | `1` (same as `size()`)
  9562. string | `1` (same as `size()`)
  9563. number | `1` (same as `size()`)
  9564. object | result of function `object_t::max_size()`
  9565. array | result of function `array_t::max_size()`
  9566. @liveexample{The following code calls `max_size()` on the different value
  9567. types. Note the output is implementation specific.,max_size}
  9568. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  9569. the Container concept; that is, their `max_size()` functions have constant
  9570. complexity.
  9571. @iterators No changes.
  9572. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9573. @requirement This function helps `basic_json` satisfying the
  9574. [Container](http://en.cppreference.com/w/cpp/concept/Container)
  9575. requirements:
  9576. - The complexity is constant.
  9577. - Has the semantics of returning `b.size()` where `b` is the largest
  9578. possible JSON value.
  9579. @sa @ref size() -- returns the number of elements
  9580. @since version 1.0.0
  9581. */
  9582. size_type max_size() const noexcept
  9583. {
  9584. switch (m_type)
  9585. {
  9586. case value_t::array:
  9587. {
  9588. // delegate call to array_t::max_size()
  9589. return m_value.array->max_size();
  9590. }
  9591. case value_t::object:
  9592. {
  9593. // delegate call to object_t::max_size()
  9594. return m_value.object->max_size();
  9595. }
  9596. default:
  9597. {
  9598. // all other types have max_size() == size()
  9599. return size();
  9600. }
  9601. }
  9602. }
  9603. /// @}
  9604. ///////////////
  9605. // modifiers //
  9606. ///////////////
  9607. /// @name modifiers
  9608. /// @{
  9609. /*!
  9610. @brief clears the contents
  9611. Clears the content of a JSON value and resets it to the default value as
  9612. if @ref basic_json(value_t) would have been called with the current value
  9613. type from @ref type():
  9614. Value type | initial value
  9615. ----------- | -------------
  9616. null | `null`
  9617. boolean | `false`
  9618. string | `""`
  9619. number | `0`
  9620. object | `{}`
  9621. array | `[]`
  9622. @post Has the same effect as calling
  9623. @code {.cpp}
  9624. *this = basic_json(type());
  9625. @endcode
  9626. @liveexample{The example below shows the effect of `clear()` to different
  9627. JSON types.,clear}
  9628. @complexity Linear in the size of the JSON value.
  9629. @iterators All iterators, pointers and references related to this container
  9630. are invalidated.
  9631. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  9632. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  9633. same value than calling `clear()`
  9634. @since version 1.0.0
  9635. */
  9636. void clear() noexcept
  9637. {
  9638. switch (m_type)
  9639. {
  9640. case value_t::number_integer:
  9641. {
  9642. m_value.number_integer = 0;
  9643. break;
  9644. }
  9645. case value_t::number_unsigned:
  9646. {
  9647. m_value.number_unsigned = 0;
  9648. break;
  9649. }
  9650. case value_t::number_float:
  9651. {
  9652. m_value.number_float = 0.0;
  9653. break;
  9654. }
  9655. case value_t::boolean:
  9656. {
  9657. m_value.boolean = false;
  9658. break;
  9659. }
  9660. case value_t::string:
  9661. {
  9662. m_value.string->clear();
  9663. break;
  9664. }
  9665. case value_t::array:
  9666. {
  9667. m_value.array->clear();
  9668. break;
  9669. }
  9670. case value_t::object:
  9671. {
  9672. m_value.object->clear();
  9673. break;
  9674. }
  9675. default:
  9676. break;
  9677. }
  9678. }
  9679. /*!
  9680. @brief add an object to an array
  9681. Appends the given element @a val to the end of the JSON value. If the
  9682. function is called on a JSON null value, an empty array is created before
  9683. appending @a val.
  9684. @param[in] val the value to add to the JSON array
  9685. @throw type_error.308 when called on a type other than JSON array or
  9686. null; example: `"cannot use push_back() with number"`
  9687. @complexity Amortized constant.
  9688. @liveexample{The example shows how `push_back()` and `+=` can be used to
  9689. add elements to a JSON array. Note how the `null` value was silently
  9690. converted to a JSON array.,push_back}
  9691. @since version 1.0.0
  9692. */
  9693. void push_back(basic_json&& val)
  9694. {
  9695. // push_back only works for null objects or arrays
  9696. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9697. {
  9698. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9699. }
  9700. // transform null object into an array
  9701. if (is_null())
  9702. {
  9703. m_type = value_t::array;
  9704. m_value = value_t::array;
  9705. assert_invariant();
  9706. }
  9707. // add element to array (move semantics)
  9708. m_value.array->push_back(std::move(val));
  9709. // invalidate object
  9710. val.m_type = value_t::null;
  9711. }
  9712. /*!
  9713. @brief add an object to an array
  9714. @copydoc push_back(basic_json&&)
  9715. */
  9716. reference operator+=(basic_json&& val)
  9717. {
  9718. push_back(std::move(val));
  9719. return *this;
  9720. }
  9721. /*!
  9722. @brief add an object to an array
  9723. @copydoc push_back(basic_json&&)
  9724. */
  9725. void push_back(const basic_json& val)
  9726. {
  9727. // push_back only works for null objects or arrays
  9728. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9729. {
  9730. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9731. }
  9732. // transform null object into an array
  9733. if (is_null())
  9734. {
  9735. m_type = value_t::array;
  9736. m_value = value_t::array;
  9737. assert_invariant();
  9738. }
  9739. // add element to array
  9740. m_value.array->push_back(val);
  9741. }
  9742. /*!
  9743. @brief add an object to an array
  9744. @copydoc push_back(basic_json&&)
  9745. */
  9746. reference operator+=(const basic_json& val)
  9747. {
  9748. push_back(val);
  9749. return *this;
  9750. }
  9751. /*!
  9752. @brief add an object to an object
  9753. Inserts the given element @a val to the JSON object. If the function is
  9754. called on a JSON null value, an empty object is created before inserting
  9755. @a val.
  9756. @param[in] val the value to add to the JSON object
  9757. @throw type_error.308 when called on a type other than JSON object or
  9758. null; example: `"cannot use push_back() with number"`
  9759. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  9760. @liveexample{The example shows how `push_back()` and `+=` can be used to
  9761. add elements to a JSON object. Note how the `null` value was silently
  9762. converted to a JSON object.,push_back__object_t__value}
  9763. @since version 1.0.0
  9764. */
  9765. void push_back(const typename object_t::value_type& val)
  9766. {
  9767. // push_back only works for null objects or objects
  9768. if (JSON_UNLIKELY(not(is_null() or is_object())))
  9769. {
  9770. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  9771. }
  9772. // transform null object into an object
  9773. if (is_null())
  9774. {
  9775. m_type = value_t::object;
  9776. m_value = value_t::object;
  9777. assert_invariant();
  9778. }
  9779. // add element to array
  9780. m_value.object->insert(val);
  9781. }
  9782. /*!
  9783. @brief add an object to an object
  9784. @copydoc push_back(const typename object_t::value_type&)
  9785. */
  9786. reference operator+=(const typename object_t::value_type& val)
  9787. {
  9788. push_back(val);
  9789. return *this;
  9790. }
  9791. /*!
  9792. @brief add an object to an object
  9793. This function allows to use `push_back` with an initializer list. In case
  9794. 1. the current value is an object,
  9795. 2. the initializer list @a init contains only two elements, and
  9796. 3. the first element of @a init is a string,
  9797. @a init is converted into an object element and added using
  9798. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  9799. is converted to a JSON value and added using @ref push_back(basic_json&&).
  9800. @param[in] init an initializer list
  9801. @complexity Linear in the size of the initializer list @a init.
  9802. @note This function is required to resolve an ambiguous overload error,
  9803. because pairs like `{"key", "value"}` can be both interpreted as
  9804. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  9805. https://github.com/nlohmann/json/issues/235 for more information.
  9806. @liveexample{The example shows how initializer lists are treated as
  9807. objects when possible.,push_back__initializer_list}
  9808. */
  9809. void push_back(initializer_list_t init)
  9810. {
  9811. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  9812. {
  9813. basic_json&& key = init.begin()->moved_or_copied();
  9814. push_back(typename object_t::value_type(
  9815. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  9816. }
  9817. else
  9818. {
  9819. push_back(basic_json(init));
  9820. }
  9821. }
  9822. /*!
  9823. @brief add an object to an object
  9824. @copydoc push_back(initializer_list_t)
  9825. */
  9826. reference operator+=(initializer_list_t init)
  9827. {
  9828. push_back(init);
  9829. return *this;
  9830. }
  9831. /*!
  9832. @brief add an object to an array
  9833. Creates a JSON value from the passed parameters @a args to the end of the
  9834. JSON value. If the function is called on a JSON null value, an empty array
  9835. is created before appending the value created from @a args.
  9836. @param[in] args arguments to forward to a constructor of @ref basic_json
  9837. @tparam Args compatible types to create a @ref basic_json object
  9838. @throw type_error.311 when called on a type other than JSON array or
  9839. null; example: `"cannot use emplace_back() with number"`
  9840. @complexity Amortized constant.
  9841. @liveexample{The example shows how `push_back()` can be used to add
  9842. elements to a JSON array. Note how the `null` value was silently converted
  9843. to a JSON array.,emplace_back}
  9844. @since version 2.0.8
  9845. */
  9846. template<class... Args>
  9847. void emplace_back(Args&& ... args)
  9848. {
  9849. // emplace_back only works for null objects or arrays
  9850. if (JSON_UNLIKELY(not(is_null() or is_array())))
  9851. {
  9852. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  9853. }
  9854. // transform null object into an array
  9855. if (is_null())
  9856. {
  9857. m_type = value_t::array;
  9858. m_value = value_t::array;
  9859. assert_invariant();
  9860. }
  9861. // add element to array (perfect forwarding)
  9862. m_value.array->emplace_back(std::forward<Args>(args)...);
  9863. }
  9864. /*!
  9865. @brief add an object to an object if key does not exist
  9866. Inserts a new element into a JSON object constructed in-place with the
  9867. given @a args if there is no element with the key in the container. If the
  9868. function is called on a JSON null value, an empty object is created before
  9869. appending the value created from @a args.
  9870. @param[in] args arguments to forward to a constructor of @ref basic_json
  9871. @tparam Args compatible types to create a @ref basic_json object
  9872. @return a pair consisting of an iterator to the inserted element, or the
  9873. already-existing element if no insertion happened, and a bool
  9874. denoting whether the insertion took place.
  9875. @throw type_error.311 when called on a type other than JSON object or
  9876. null; example: `"cannot use emplace() with number"`
  9877. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  9878. @liveexample{The example shows how `emplace()` can be used to add elements
  9879. to a JSON object. Note how the `null` value was silently converted to a
  9880. JSON object. Further note how no value is added if there was already one
  9881. value stored with the same key.,emplace}
  9882. @since version 2.0.8
  9883. */
  9884. template<class... Args>
  9885. std::pair<iterator, bool> emplace(Args&& ... args)
  9886. {
  9887. // emplace only works for null objects or arrays
  9888. if (JSON_UNLIKELY(not(is_null() or is_object())))
  9889. {
  9890. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  9891. }
  9892. // transform null object into an object
  9893. if (is_null())
  9894. {
  9895. m_type = value_t::object;
  9896. m_value = value_t::object;
  9897. assert_invariant();
  9898. }
  9899. // add element to array (perfect forwarding)
  9900. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  9901. // create result iterator and set iterator to the result of emplace
  9902. auto it = begin();
  9903. it.m_it.object_iterator = res.first;
  9904. // return pair of iterator and boolean
  9905. return {it, res.second};
  9906. }
  9907. /*!
  9908. @brief inserts element
  9909. Inserts element @a val before iterator @a pos.
  9910. @param[in] pos iterator before which the content will be inserted; may be
  9911. the end() iterator
  9912. @param[in] val element to insert
  9913. @return iterator pointing to the inserted @a val.
  9914. @throw type_error.309 if called on JSON values other than arrays;
  9915. example: `"cannot use insert() with string"`
  9916. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  9917. example: `"iterator does not fit current value"`
  9918. @complexity Constant plus linear in the distance between @a pos and end of
  9919. the container.
  9920. @liveexample{The example shows how `insert()` is used.,insert}
  9921. @since version 1.0.0
  9922. */
  9923. iterator insert(const_iterator pos, const basic_json& val)
  9924. {
  9925. // insert only works for arrays
  9926. if (JSON_LIKELY(is_array()))
  9927. {
  9928. // check if iterator pos fits to this JSON value
  9929. if (JSON_UNLIKELY(pos.m_object != this))
  9930. {
  9931. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  9932. }
  9933. // insert to array and return iterator
  9934. iterator result(this);
  9935. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  9936. return result;
  9937. }
  9938. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  9939. }
  9940. /*!
  9941. @brief inserts element
  9942. @copydoc insert(const_iterator, const basic_json&)
  9943. */
  9944. iterator insert(const_iterator pos, basic_json&& val)
  9945. {
  9946. return insert(pos, val);
  9947. }
  9948. /*!
  9949. @brief inserts elements
  9950. Inserts @a cnt copies of @a val before iterator @a pos.
  9951. @param[in] pos iterator before which the content will be inserted; may be
  9952. the end() iterator
  9953. @param[in] cnt number of copies of @a val to insert
  9954. @param[in] val element to insert
  9955. @return iterator pointing to the first element inserted, or @a pos if
  9956. `cnt==0`
  9957. @throw type_error.309 if called on JSON values other than arrays; example:
  9958. `"cannot use insert() with string"`
  9959. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  9960. example: `"iterator does not fit current value"`
  9961. @complexity Linear in @a cnt plus linear in the distance between @a pos
  9962. and end of the container.
  9963. @liveexample{The example shows how `insert()` is used.,insert__count}
  9964. @since version 1.0.0
  9965. */
  9966. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  9967. {
  9968. // insert only works for arrays
  9969. if (JSON_LIKELY(is_array()))
  9970. {
  9971. // check if iterator pos fits to this JSON value
  9972. if (JSON_UNLIKELY(pos.m_object != this))
  9973. {
  9974. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  9975. }
  9976. // insert to array and return iterator
  9977. iterator result(this);
  9978. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  9979. return result;
  9980. }
  9981. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  9982. }
  9983. /*!
  9984. @brief inserts elements
  9985. Inserts elements from range `[first, last)` before iterator @a pos.
  9986. @param[in] pos iterator before which the content will be inserted; may be
  9987. the end() iterator
  9988. @param[in] first begin of the range of elements to insert
  9989. @param[in] last end of the range of elements to insert
  9990. @throw type_error.309 if called on JSON values other than arrays; example:
  9991. `"cannot use insert() with string"`
  9992. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  9993. example: `"iterator does not fit current value"`
  9994. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  9995. same JSON value; example: `"iterators do not fit"`
  9996. @throw invalid_iterator.211 if @a first or @a last are iterators into
  9997. container for which insert is called; example: `"passed iterators may not
  9998. belong to container"`
  9999. @return iterator pointing to the first element inserted, or @a pos if
  10000. `first==last`
  10001. @complexity Linear in `std::distance(first, last)` plus linear in the
  10002. distance between @a pos and end of the container.
  10003. @liveexample{The example shows how `insert()` is used.,insert__range}
  10004. @since version 1.0.0
  10005. */
  10006. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  10007. {
  10008. // insert only works for arrays
  10009. if (JSON_UNLIKELY(not is_array()))
  10010. {
  10011. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10012. }
  10013. // check if iterator pos fits to this JSON value
  10014. if (JSON_UNLIKELY(pos.m_object != this))
  10015. {
  10016. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10017. }
  10018. // check if range iterators belong to the same JSON object
  10019. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10020. {
  10021. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10022. }
  10023. if (JSON_UNLIKELY(first.m_object == this or last.m_object == this))
  10024. {
  10025. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  10026. }
  10027. // insert to array and return iterator
  10028. iterator result(this);
  10029. result.m_it.array_iterator = m_value.array->insert(
  10030. pos.m_it.array_iterator,
  10031. first.m_it.array_iterator,
  10032. last.m_it.array_iterator);
  10033. return result;
  10034. }
  10035. /*!
  10036. @brief inserts elements
  10037. Inserts elements from initializer list @a ilist before iterator @a pos.
  10038. @param[in] pos iterator before which the content will be inserted; may be
  10039. the end() iterator
  10040. @param[in] ilist initializer list to insert the values from
  10041. @throw type_error.309 if called on JSON values other than arrays; example:
  10042. `"cannot use insert() with string"`
  10043. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  10044. example: `"iterator does not fit current value"`
  10045. @return iterator pointing to the first element inserted, or @a pos if
  10046. `ilist` is empty
  10047. @complexity Linear in `ilist.size()` plus linear in the distance between
  10048. @a pos and end of the container.
  10049. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  10050. @since version 1.0.0
  10051. */
  10052. iterator insert(const_iterator pos, initializer_list_t ilist)
  10053. {
  10054. // insert only works for arrays
  10055. if (JSON_UNLIKELY(not is_array()))
  10056. {
  10057. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10058. }
  10059. // check if iterator pos fits to this JSON value
  10060. if (JSON_UNLIKELY(pos.m_object != this))
  10061. {
  10062. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  10063. }
  10064. // insert to array and return iterator
  10065. iterator result(this);
  10066. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
  10067. return result;
  10068. }
  10069. /*!
  10070. @brief inserts elements
  10071. Inserts elements from range `[first, last)`.
  10072. @param[in] first begin of the range of elements to insert
  10073. @param[in] last end of the range of elements to insert
  10074. @throw type_error.309 if called on JSON values other than objects; example:
  10075. `"cannot use insert() with string"`
  10076. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  10077. point to an object; example: `"iterators first and last must point to
  10078. objects"`
  10079. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  10080. same JSON value; example: `"iterators do not fit"`
  10081. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  10082. of elements to insert.
  10083. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  10084. @since version 3.0.0
  10085. */
  10086. void insert(const_iterator first, const_iterator last)
  10087. {
  10088. // insert only works for objects
  10089. if (JSON_UNLIKELY(not is_object()))
  10090. {
  10091. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  10092. }
  10093. // check if range iterators belong to the same JSON object
  10094. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10095. {
  10096. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10097. }
  10098. // passed iterators must belong to objects
  10099. if (JSON_UNLIKELY(not first.m_object->is_object()
  10100. or not last.m_object->is_object()))
  10101. {
  10102. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  10103. }
  10104. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  10105. }
  10106. /*!
  10107. @brief updates a JSON object from another object, overwriting existing keys
  10108. Inserts all values from JSON object @a j and overwrites existing keys.
  10109. @param[in] j JSON object to read values from
  10110. @throw type_error.312 if called on JSON values other than objects; example:
  10111. `"cannot use update() with string"`
  10112. @complexity O(N*log(size() + N)), where N is the number of elements to
  10113. insert.
  10114. @liveexample{The example shows how `update()` is used.,update}
  10115. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  10116. @since version 3.0.0
  10117. */
  10118. void update(const_reference j)
  10119. {
  10120. // implicitly convert null value to an empty object
  10121. if (is_null())
  10122. {
  10123. m_type = value_t::object;
  10124. m_value.object = create<object_t>();
  10125. assert_invariant();
  10126. }
  10127. if (JSON_UNLIKELY(not is_object()))
  10128. {
  10129. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  10130. }
  10131. if (JSON_UNLIKELY(not j.is_object()))
  10132. {
  10133. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  10134. }
  10135. for (auto it = j.begin(); it != j.end(); ++it)
  10136. {
  10137. m_value.object->operator[](it.key()) = it.value();
  10138. }
  10139. }
  10140. /*!
  10141. @brief updates a JSON object from another object, overwriting existing keys
  10142. Inserts all values from from range `[first, last)` and overwrites existing
  10143. keys.
  10144. @param[in] first begin of the range of elements to insert
  10145. @param[in] last end of the range of elements to insert
  10146. @throw type_error.312 if called on JSON values other than objects; example:
  10147. `"cannot use update() with string"`
  10148. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  10149. point to an object; example: `"iterators first and last must point to
  10150. objects"`
  10151. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  10152. same JSON value; example: `"iterators do not fit"`
  10153. @complexity O(N*log(size() + N)), where N is the number of elements to
  10154. insert.
  10155. @liveexample{The example shows how `update()` is used__range.,update}
  10156. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  10157. @since version 3.0.0
  10158. */
  10159. void update(const_iterator first, const_iterator last)
  10160. {
  10161. // implicitly convert null value to an empty object
  10162. if (is_null())
  10163. {
  10164. m_type = value_t::object;
  10165. m_value.object = create<object_t>();
  10166. assert_invariant();
  10167. }
  10168. if (JSON_UNLIKELY(not is_object()))
  10169. {
  10170. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  10171. }
  10172. // check if range iterators belong to the same JSON object
  10173. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10174. {
  10175. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  10176. }
  10177. // passed iterators must belong to objects
  10178. if (JSON_UNLIKELY(not first.m_object->is_object()
  10179. or not first.m_object->is_object()))
  10180. {
  10181. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  10182. }
  10183. for (auto it = first; it != last; ++it)
  10184. {
  10185. m_value.object->operator[](it.key()) = it.value();
  10186. }
  10187. }
  10188. /*!
  10189. @brief exchanges the values
  10190. Exchanges the contents of the JSON value with those of @a other. Does not
  10191. invoke any move, copy, or swap operations on individual elements. All
  10192. iterators and references remain valid. The past-the-end iterator is
  10193. invalidated.
  10194. @param[in,out] other JSON value to exchange the contents with
  10195. @complexity Constant.
  10196. @liveexample{The example below shows how JSON values can be swapped with
  10197. `swap()`.,swap__reference}
  10198. @since version 1.0.0
  10199. */
  10200. void swap(reference other) noexcept (
  10201. std::is_nothrow_move_constructible<value_t>::value and
  10202. std::is_nothrow_move_assignable<value_t>::value and
  10203. std::is_nothrow_move_constructible<json_value>::value and
  10204. std::is_nothrow_move_assignable<json_value>::value
  10205. )
  10206. {
  10207. std::swap(m_type, other.m_type);
  10208. std::swap(m_value, other.m_value);
  10209. assert_invariant();
  10210. }
  10211. /*!
  10212. @brief exchanges the values
  10213. Exchanges the contents of a JSON array with those of @a other. Does not
  10214. invoke any move, copy, or swap operations on individual elements. All
  10215. iterators and references remain valid. The past-the-end iterator is
  10216. invalidated.
  10217. @param[in,out] other array to exchange the contents with
  10218. @throw type_error.310 when JSON value is not an array; example: `"cannot
  10219. use swap() with string"`
  10220. @complexity Constant.
  10221. @liveexample{The example below shows how arrays can be swapped with
  10222. `swap()`.,swap__array_t}
  10223. @since version 1.0.0
  10224. */
  10225. void swap(array_t& other)
  10226. {
  10227. // swap only works for arrays
  10228. if (JSON_LIKELY(is_array()))
  10229. {
  10230. std::swap(*(m_value.array), other);
  10231. }
  10232. else
  10233. {
  10234. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10235. }
  10236. }
  10237. /*!
  10238. @brief exchanges the values
  10239. Exchanges the contents of a JSON object with those of @a other. Does not
  10240. invoke any move, copy, or swap operations on individual elements. All
  10241. iterators and references remain valid. The past-the-end iterator is
  10242. invalidated.
  10243. @param[in,out] other object to exchange the contents with
  10244. @throw type_error.310 when JSON value is not an object; example:
  10245. `"cannot use swap() with string"`
  10246. @complexity Constant.
  10247. @liveexample{The example below shows how objects can be swapped with
  10248. `swap()`.,swap__object_t}
  10249. @since version 1.0.0
  10250. */
  10251. void swap(object_t& other)
  10252. {
  10253. // swap only works for objects
  10254. if (JSON_LIKELY(is_object()))
  10255. {
  10256. std::swap(*(m_value.object), other);
  10257. }
  10258. else
  10259. {
  10260. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10261. }
  10262. }
  10263. /*!
  10264. @brief exchanges the values
  10265. Exchanges the contents of a JSON string with those of @a other. Does not
  10266. invoke any move, copy, or swap operations on individual elements. All
  10267. iterators and references remain valid. The past-the-end iterator is
  10268. invalidated.
  10269. @param[in,out] other string to exchange the contents with
  10270. @throw type_error.310 when JSON value is not a string; example: `"cannot
  10271. use swap() with boolean"`
  10272. @complexity Constant.
  10273. @liveexample{The example below shows how strings can be swapped with
  10274. `swap()`.,swap__string_t}
  10275. @since version 1.0.0
  10276. */
  10277. void swap(string_t& other)
  10278. {
  10279. // swap only works for strings
  10280. if (JSON_LIKELY(is_string()))
  10281. {
  10282. std::swap(*(m_value.string), other);
  10283. }
  10284. else
  10285. {
  10286. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  10287. }
  10288. }
  10289. /// @}
  10290. public:
  10291. //////////////////////////////////////////
  10292. // lexicographical comparison operators //
  10293. //////////////////////////////////////////
  10294. /// @name lexicographical comparison operators
  10295. /// @{
  10296. /*!
  10297. @brief comparison: equal
  10298. Compares two JSON values for equality according to the following rules:
  10299. - Two JSON values are equal if (1) they are from the same type and (2)
  10300. their stored values are the same according to their respective
  10301. `operator==`.
  10302. - Integer and floating-point numbers are automatically converted before
  10303. comparison. Note than two NaN values are always treated as unequal.
  10304. - Two JSON null values are equal.
  10305. @note Floating-point inside JSON values numbers are compared with
  10306. `json::number_float_t::operator==` which is `double::operator==` by
  10307. default. To compare floating-point while respecting an epsilon, an alternative
  10308. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  10309. could be used, for instance
  10310. @code {.cpp}
  10311. template <typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  10312. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  10313. {
  10314. return std::abs(a - b) <= epsilon;
  10315. }
  10316. @endcode
  10317. @note NaN values never compare equal to themselves or to other NaN values.
  10318. @param[in] lhs first JSON value to consider
  10319. @param[in] rhs second JSON value to consider
  10320. @return whether the values @a lhs and @a rhs are equal
  10321. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10322. @complexity Linear.
  10323. @liveexample{The example demonstrates comparing several JSON
  10324. types.,operator__equal}
  10325. @since version 1.0.0
  10326. */
  10327. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  10328. {
  10329. const auto lhs_type = lhs.type();
  10330. const auto rhs_type = rhs.type();
  10331. if (lhs_type == rhs_type)
  10332. {
  10333. switch (lhs_type)
  10334. {
  10335. case value_t::array:
  10336. return (*lhs.m_value.array == *rhs.m_value.array);
  10337. case value_t::object:
  10338. return (*lhs.m_value.object == *rhs.m_value.object);
  10339. case value_t::null:
  10340. return true;
  10341. case value_t::string:
  10342. return (*lhs.m_value.string == *rhs.m_value.string);
  10343. case value_t::boolean:
  10344. return (lhs.m_value.boolean == rhs.m_value.boolean);
  10345. case value_t::number_integer:
  10346. return (lhs.m_value.number_integer == rhs.m_value.number_integer);
  10347. case value_t::number_unsigned:
  10348. return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
  10349. case value_t::number_float:
  10350. return (lhs.m_value.number_float == rhs.m_value.number_float);
  10351. default:
  10352. return false;
  10353. }
  10354. }
  10355. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  10356. {
  10357. return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
  10358. }
  10359. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  10360. {
  10361. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
  10362. }
  10363. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  10364. {
  10365. return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
  10366. }
  10367. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  10368. {
  10369. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
  10370. }
  10371. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  10372. {
  10373. return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
  10374. }
  10375. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  10376. {
  10377. return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
  10378. }
  10379. return false;
  10380. }
  10381. /*!
  10382. @brief comparison: equal
  10383. @copydoc operator==(const_reference, const_reference)
  10384. */
  10385. template<typename ScalarType, typename std::enable_if<
  10386. std::is_scalar<ScalarType>::value, int>::type = 0>
  10387. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  10388. {
  10389. return (lhs == basic_json(rhs));
  10390. }
  10391. /*!
  10392. @brief comparison: equal
  10393. @copydoc operator==(const_reference, const_reference)
  10394. */
  10395. template<typename ScalarType, typename std::enable_if<
  10396. std::is_scalar<ScalarType>::value, int>::type = 0>
  10397. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  10398. {
  10399. return (basic_json(lhs) == rhs);
  10400. }
  10401. /*!
  10402. @brief comparison: not equal
  10403. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  10404. @param[in] lhs first JSON value to consider
  10405. @param[in] rhs second JSON value to consider
  10406. @return whether the values @a lhs and @a rhs are not equal
  10407. @complexity Linear.
  10408. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10409. @liveexample{The example demonstrates comparing several JSON
  10410. types.,operator__notequal}
  10411. @since version 1.0.0
  10412. */
  10413. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  10414. {
  10415. return not (lhs == rhs);
  10416. }
  10417. /*!
  10418. @brief comparison: not equal
  10419. @copydoc operator!=(const_reference, const_reference)
  10420. */
  10421. template<typename ScalarType, typename std::enable_if<
  10422. std::is_scalar<ScalarType>::value, int>::type = 0>
  10423. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  10424. {
  10425. return (lhs != basic_json(rhs));
  10426. }
  10427. /*!
  10428. @brief comparison: not equal
  10429. @copydoc operator!=(const_reference, const_reference)
  10430. */
  10431. template<typename ScalarType, typename std::enable_if<
  10432. std::is_scalar<ScalarType>::value, int>::type = 0>
  10433. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  10434. {
  10435. return (basic_json(lhs) != rhs);
  10436. }
  10437. /*!
  10438. @brief comparison: less than
  10439. Compares whether one JSON value @a lhs is less than another JSON value @a
  10440. rhs according to the following rules:
  10441. - If @a lhs and @a rhs have the same type, the values are compared using
  10442. the default `<` operator.
  10443. - Integer and floating-point numbers are automatically converted before
  10444. comparison
  10445. - In case @a lhs and @a rhs have different types, the values are ignored
  10446. and the order of the types is considered, see
  10447. @ref operator<(const value_t, const value_t).
  10448. @param[in] lhs first JSON value to consider
  10449. @param[in] rhs second JSON value to consider
  10450. @return whether @a lhs is less than @a rhs
  10451. @complexity Linear.
  10452. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10453. @liveexample{The example demonstrates comparing several JSON
  10454. types.,operator__less}
  10455. @since version 1.0.0
  10456. */
  10457. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  10458. {
  10459. const auto lhs_type = lhs.type();
  10460. const auto rhs_type = rhs.type();
  10461. if (lhs_type == rhs_type)
  10462. {
  10463. switch (lhs_type)
  10464. {
  10465. case value_t::array:
  10466. return (*lhs.m_value.array) < (*rhs.m_value.array);
  10467. case value_t::object:
  10468. return *lhs.m_value.object < *rhs.m_value.object;
  10469. case value_t::null:
  10470. return false;
  10471. case value_t::string:
  10472. return *lhs.m_value.string < *rhs.m_value.string;
  10473. case value_t::boolean:
  10474. return lhs.m_value.boolean < rhs.m_value.boolean;
  10475. case value_t::number_integer:
  10476. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  10477. case value_t::number_unsigned:
  10478. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  10479. case value_t::number_float:
  10480. return lhs.m_value.number_float < rhs.m_value.number_float;
  10481. default:
  10482. return false;
  10483. }
  10484. }
  10485. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  10486. {
  10487. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  10488. }
  10489. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  10490. {
  10491. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  10492. }
  10493. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  10494. {
  10495. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  10496. }
  10497. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  10498. {
  10499. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  10500. }
  10501. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  10502. {
  10503. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  10504. }
  10505. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  10506. {
  10507. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  10508. }
  10509. // We only reach this line if we cannot compare values. In that case,
  10510. // we compare types. Note we have to call the operator explicitly,
  10511. // because MSVC has problems otherwise.
  10512. return operator<(lhs_type, rhs_type);
  10513. }
  10514. /*!
  10515. @brief comparison: less than
  10516. @copydoc operator<(const_reference, const_reference)
  10517. */
  10518. template<typename ScalarType, typename std::enable_if<
  10519. std::is_scalar<ScalarType>::value, int>::type = 0>
  10520. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  10521. {
  10522. return (lhs < basic_json(rhs));
  10523. }
  10524. /*!
  10525. @brief comparison: less than
  10526. @copydoc operator<(const_reference, const_reference)
  10527. */
  10528. template<typename ScalarType, typename std::enable_if<
  10529. std::is_scalar<ScalarType>::value, int>::type = 0>
  10530. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  10531. {
  10532. return (basic_json(lhs) < rhs);
  10533. }
  10534. /*!
  10535. @brief comparison: less than or equal
  10536. Compares whether one JSON value @a lhs is less than or equal to another
  10537. JSON value by calculating `not (rhs < lhs)`.
  10538. @param[in] lhs first JSON value to consider
  10539. @param[in] rhs second JSON value to consider
  10540. @return whether @a lhs is less than or equal to @a rhs
  10541. @complexity Linear.
  10542. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10543. @liveexample{The example demonstrates comparing several JSON
  10544. types.,operator__greater}
  10545. @since version 1.0.0
  10546. */
  10547. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  10548. {
  10549. return not (rhs < lhs);
  10550. }
  10551. /*!
  10552. @brief comparison: less than or equal
  10553. @copydoc operator<=(const_reference, const_reference)
  10554. */
  10555. template<typename ScalarType, typename std::enable_if<
  10556. std::is_scalar<ScalarType>::value, int>::type = 0>
  10557. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  10558. {
  10559. return (lhs <= basic_json(rhs));
  10560. }
  10561. /*!
  10562. @brief comparison: less than or equal
  10563. @copydoc operator<=(const_reference, const_reference)
  10564. */
  10565. template<typename ScalarType, typename std::enable_if<
  10566. std::is_scalar<ScalarType>::value, int>::type = 0>
  10567. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  10568. {
  10569. return (basic_json(lhs) <= rhs);
  10570. }
  10571. /*!
  10572. @brief comparison: greater than
  10573. Compares whether one JSON value @a lhs is greater than another
  10574. JSON value by calculating `not (lhs <= rhs)`.
  10575. @param[in] lhs first JSON value to consider
  10576. @param[in] rhs second JSON value to consider
  10577. @return whether @a lhs is greater than to @a rhs
  10578. @complexity Linear.
  10579. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10580. @liveexample{The example demonstrates comparing several JSON
  10581. types.,operator__lessequal}
  10582. @since version 1.0.0
  10583. */
  10584. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  10585. {
  10586. return not (lhs <= rhs);
  10587. }
  10588. /*!
  10589. @brief comparison: greater than
  10590. @copydoc operator>(const_reference, const_reference)
  10591. */
  10592. template<typename ScalarType, typename std::enable_if<
  10593. std::is_scalar<ScalarType>::value, int>::type = 0>
  10594. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  10595. {
  10596. return (lhs > basic_json(rhs));
  10597. }
  10598. /*!
  10599. @brief comparison: greater than
  10600. @copydoc operator>(const_reference, const_reference)
  10601. */
  10602. template<typename ScalarType, typename std::enable_if<
  10603. std::is_scalar<ScalarType>::value, int>::type = 0>
  10604. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  10605. {
  10606. return (basic_json(lhs) > rhs);
  10607. }
  10608. /*!
  10609. @brief comparison: greater than or equal
  10610. Compares whether one JSON value @a lhs is greater than or equal to another
  10611. JSON value by calculating `not (lhs < rhs)`.
  10612. @param[in] lhs first JSON value to consider
  10613. @param[in] rhs second JSON value to consider
  10614. @return whether @a lhs is greater than or equal to @a rhs
  10615. @complexity Linear.
  10616. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10617. @liveexample{The example demonstrates comparing several JSON
  10618. types.,operator__greaterequal}
  10619. @since version 1.0.0
  10620. */
  10621. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  10622. {
  10623. return not (lhs < rhs);
  10624. }
  10625. /*!
  10626. @brief comparison: greater than or equal
  10627. @copydoc operator>=(const_reference, const_reference)
  10628. */
  10629. template<typename ScalarType, typename std::enable_if<
  10630. std::is_scalar<ScalarType>::value, int>::type = 0>
  10631. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  10632. {
  10633. return (lhs >= basic_json(rhs));
  10634. }
  10635. /*!
  10636. @brief comparison: greater than or equal
  10637. @copydoc operator>=(const_reference, const_reference)
  10638. */
  10639. template<typename ScalarType, typename std::enable_if<
  10640. std::is_scalar<ScalarType>::value, int>::type = 0>
  10641. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  10642. {
  10643. return (basic_json(lhs) >= rhs);
  10644. }
  10645. /// @}
  10646. ///////////////////
  10647. // serialization //
  10648. ///////////////////
  10649. /// @name serialization
  10650. /// @{
  10651. /*!
  10652. @brief serialize to stream
  10653. Serialize the given JSON value @a j to the output stream @a o. The JSON
  10654. value will be serialized using the @ref dump member function.
  10655. - The indentation of the output can be controlled with the member variable
  10656. `width` of the output stream @a o. For instance, using the manipulator
  10657. `std::setw(4)` on @a o sets the indentation level to `4` and the
  10658. serialization result is the same as calling `dump(4)`.
  10659. - The indentation characrer can be controlled with the member variable
  10660. `fill` of the output stream @a o. For instance, the manipulator
  10661. `std::setfill('\\t')` sets indentation to use a tab character rather than
  10662. the default space character.
  10663. @param[in,out] o stream to serialize to
  10664. @param[in] j JSON value to serialize
  10665. @return the stream @a o
  10666. @complexity Linear.
  10667. @liveexample{The example below shows the serialization with different
  10668. parameters to `width` to adjust the indentation level.,operator_serialize}
  10669. @since version 1.0.0; indentaction character added in version 3.0.0
  10670. */
  10671. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  10672. {
  10673. // read width member and use it as indentation parameter if nonzero
  10674. const bool pretty_print = (o.width() > 0);
  10675. const auto indentation = (pretty_print ? o.width() : 0);
  10676. // reset width to 0 for subsequent calls to this stream
  10677. o.width(0);
  10678. // do the actual serialization
  10679. serializer s(detail::output_adapter<char>(o), o.fill());
  10680. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  10681. return o;
  10682. }
  10683. /*!
  10684. @brief serialize to stream
  10685. @deprecated This stream operator is deprecated and will be removed in a
  10686. future version of the library. Please use
  10687. @ref operator<<(std::ostream&, const basic_json&)
  10688. instead; that is, replace calls like `j >> o;` with `o << j;`.
  10689. */
  10690. JSON_DEPRECATED
  10691. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  10692. {
  10693. return o << j;
  10694. }
  10695. /// @}
  10696. /////////////////////
  10697. // deserialization //
  10698. /////////////////////
  10699. /// @name deserialization
  10700. /// @{
  10701. /*!
  10702. @brief deserialize from a compatible input
  10703. This function reads from a compatible input. Examples are:
  10704. - an array of 1-byte values
  10705. - strings with character/literal type with size of 1 byte
  10706. - input streams
  10707. - container with contiguous storage of 1-byte values. Compatible container
  10708. types include `std::vector`, `std::string`, `std::array`,
  10709. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  10710. arrays can be used with `std::begin()`/`std::end()`. User-defined
  10711. containers can be used as long as they implement random-access iterators
  10712. and a contiguous storage.
  10713. @pre Each element of the container has a size of 1 byte. Violating this
  10714. precondition yields undefined behavior. **This precondition is enforced
  10715. with a static assertion.**
  10716. @pre The container storage is contiguous. Violating this precondition
  10717. yields undefined behavior. **This precondition is enforced with an
  10718. assertion.**
  10719. @pre Each element of the container has a size of 1 byte. Violating this
  10720. precondition yields undefined behavior. **This precondition is enforced
  10721. with a static assertion.**
  10722. @warning There is no way to enforce all preconditions at compile-time. If
  10723. the function is called with a noncompliant container and with
  10724. assertions switched off, the behavior is undefined and will most
  10725. likely yield segmentation violation.
  10726. @param[in] i input to read from
  10727. @param[in] cb a parser callback function of type @ref parser_callback_t
  10728. which is used to control the deserialization by filtering unwanted values
  10729. (optional)
  10730. @return result of the deserialization
  10731. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  10732. of input; expected string literal""`
  10733. @throw parse_error.102 if to_unicode fails or surrogate error
  10734. @throw parse_error.103 if to_unicode fails
  10735. @complexity Linear in the length of the input. The parser is a predictive
  10736. LL(1) parser. The complexity can be higher if the parser callback function
  10737. @a cb has a super-linear complexity.
  10738. @note A UTF-8 byte order mark is silently ignored.
  10739. @liveexample{The example below demonstrates the `parse()` function reading
  10740. from an array.,parse__array__parser_callback_t}
  10741. @liveexample{The example below demonstrates the `parse()` function with
  10742. and without callback function.,parse__string__parser_callback_t}
  10743. @liveexample{The example below demonstrates the `parse()` function with
  10744. and without callback function.,parse__istream__parser_callback_t}
  10745. @liveexample{The example below demonstrates the `parse()` function reading
  10746. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  10747. @since version 2.0.3 (contiguous containers)
  10748. */
  10749. static basic_json parse(detail::input_adapter i,
  10750. const parser_callback_t cb = nullptr,
  10751. const bool allow_exceptions = true)
  10752. {
  10753. basic_json result;
  10754. parser(i, cb, allow_exceptions).parse(true, result);
  10755. return result;
  10756. }
  10757. /*!
  10758. @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)
  10759. */
  10760. static basic_json parse(detail::input_adapter& i,
  10761. const parser_callback_t cb = nullptr,
  10762. const bool allow_exceptions = true)
  10763. {
  10764. basic_json result;
  10765. parser(i, cb, allow_exceptions).parse(true, result);
  10766. return result;
  10767. }
  10768. static bool accept(detail::input_adapter i)
  10769. {
  10770. return parser(i).accept(true);
  10771. }
  10772. static bool accept(detail::input_adapter& i)
  10773. {
  10774. return parser(i).accept(true);
  10775. }
  10776. /*!
  10777. @brief deserialize from an iterator range with contiguous storage
  10778. This function reads from an iterator range of a container with contiguous
  10779. storage of 1-byte values. Compatible container types include
  10780. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  10781. `std::initializer_list`. Furthermore, C-style arrays can be used with
  10782. `std::begin()`/`std::end()`. User-defined containers can be used as long
  10783. as they implement random-access iterators and a contiguous storage.
  10784. @pre The iterator range is contiguous. Violating this precondition yields
  10785. undefined behavior. **This precondition is enforced with an assertion.**
  10786. @pre Each element in the range has a size of 1 byte. Violating this
  10787. precondition yields undefined behavior. **This precondition is enforced
  10788. with a static assertion.**
  10789. @warning There is no way to enforce all preconditions at compile-time. If
  10790. the function is called with noncompliant iterators and with
  10791. assertions switched off, the behavior is undefined and will most
  10792. likely yield segmentation violation.
  10793. @tparam IteratorType iterator of container with contiguous storage
  10794. @param[in] first begin of the range to parse (included)
  10795. @param[in] last end of the range to parse (excluded)
  10796. @param[in] cb a parser callback function of type @ref parser_callback_t
  10797. which is used to control the deserialization by filtering unwanted values
  10798. (optional)
  10799. @return result of the deserialization
  10800. @throw parse_error.101 in case of an unexpected token
  10801. @throw parse_error.102 if to_unicode fails or surrogate error
  10802. @throw parse_error.103 if to_unicode fails
  10803. @complexity Linear in the length of the input. The parser is a predictive
  10804. LL(1) parser. The complexity can be higher if the parser callback function
  10805. @a cb has a super-linear complexity.
  10806. @note A UTF-8 byte order mark is silently ignored.
  10807. @liveexample{The example below demonstrates the `parse()` function reading
  10808. from an iterator range.,parse__iteratortype__parser_callback_t}
  10809. @since version 2.0.3
  10810. */
  10811. template<class IteratorType, typename std::enable_if<
  10812. std::is_base_of<
  10813. std::random_access_iterator_tag,
  10814. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  10815. static basic_json parse(IteratorType first, IteratorType last,
  10816. const parser_callback_t cb = nullptr,
  10817. const bool allow_exceptions = true)
  10818. {
  10819. basic_json result;
  10820. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  10821. return result;
  10822. }
  10823. template<class IteratorType, typename std::enable_if<
  10824. std::is_base_of<
  10825. std::random_access_iterator_tag,
  10826. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  10827. static bool accept(IteratorType first, IteratorType last)
  10828. {
  10829. return parser(detail::input_adapter(first, last)).accept(true);
  10830. }
  10831. /*!
  10832. @brief deserialize from stream
  10833. @deprecated This stream operator is deprecated and will be removed in a
  10834. future version of the library. Please use
  10835. @ref operator>>(std::istream&, basic_json&)
  10836. instead; that is, replace calls like `j << i;` with `i >> j;`.
  10837. */
  10838. JSON_DEPRECATED
  10839. friend std::istream& operator<<(basic_json& j, std::istream& i)
  10840. {
  10841. return operator>>(i, j);
  10842. }
  10843. /*!
  10844. @brief deserialize from stream
  10845. Deserializes an input stream to a JSON value.
  10846. @param[in,out] i input stream to read a serialized JSON value from
  10847. @param[in,out] j JSON value to write the deserialized input to
  10848. @throw parse_error.101 in case of an unexpected token
  10849. @throw parse_error.102 if to_unicode fails or surrogate error
  10850. @throw parse_error.103 if to_unicode fails
  10851. @complexity Linear in the length of the input. The parser is a predictive
  10852. LL(1) parser.
  10853. @note A UTF-8 byte order mark is silently ignored.
  10854. @liveexample{The example below shows how a JSON value is constructed by
  10855. reading a serialization from a stream.,operator_deserialize}
  10856. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  10857. parser callback function to filter values while parsing
  10858. @since version 1.0.0
  10859. */
  10860. friend std::istream& operator>>(std::istream& i, basic_json& j)
  10861. {
  10862. parser(detail::input_adapter(i)).parse(false, j);
  10863. return i;
  10864. }
  10865. /// @}
  10866. ///////////////////////////
  10867. // convenience functions //
  10868. ///////////////////////////
  10869. /*!
  10870. @brief return the type as string
  10871. Returns the type name as string to be used in error messages - usually to
  10872. indicate that a function was called on a wrong JSON type.
  10873. @return a string representation of a the @a m_type member:
  10874. Value type | return value
  10875. ----------- | -------------
  10876. null | `"null"`
  10877. boolean | `"boolean"`
  10878. string | `"string"`
  10879. number | `"number"` (for all number types)
  10880. object | `"object"`
  10881. array | `"array"`
  10882. discarded | `"discarded"`
  10883. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  10884. @complexity Constant.
  10885. @liveexample{The following code exemplifies `type_name()` for all JSON
  10886. types.,type_name}
  10887. @sa @ref type() -- return the type of the JSON value
  10888. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  10889. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  10890. since 3.0.0
  10891. */
  10892. const char* type_name() const noexcept
  10893. {
  10894. {
  10895. switch (m_type)
  10896. {
  10897. case value_t::null:
  10898. return "null";
  10899. case value_t::object:
  10900. return "object";
  10901. case value_t::array:
  10902. return "array";
  10903. case value_t::string:
  10904. return "string";
  10905. case value_t::boolean:
  10906. return "boolean";
  10907. case value_t::discarded:
  10908. return "discarded";
  10909. default:
  10910. return "number";
  10911. }
  10912. }
  10913. }
  10914. private:
  10915. //////////////////////
  10916. // member variables //
  10917. //////////////////////
  10918. /// the type of the current element
  10919. value_t m_type = value_t::null;
  10920. /// the value of the current element
  10921. json_value m_value = {};
  10922. //////////////////////////////////////////
  10923. // binary serialization/deserialization //
  10924. //////////////////////////////////////////
  10925. /// @name binary serialization/deserialization support
  10926. /// @{
  10927. public:
  10928. /*!
  10929. @brief create a CBOR serialization of a given JSON value
  10930. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  10931. Binary Object Representation) serialization format. CBOR is a binary
  10932. serialization format which aims to be more compact than JSON itself, yet
  10933. more efficient to parse.
  10934. The library uses the following mapping from JSON values types to
  10935. CBOR types according to the CBOR specification (RFC 7049):
  10936. JSON value type | value/range | CBOR type | first byte
  10937. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  10938. null | `null` | Null | 0xf6
  10939. boolean | `true` | True | 0xf5
  10940. boolean | `false` | False | 0xf4
  10941. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3b
  10942. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3a
  10943. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  10944. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  10945. number_integer | -24..-1 | Negative integer | 0x20..0x37
  10946. number_integer | 0..23 | Integer | 0x00..0x17
  10947. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  10948. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  10949. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  10950. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  10951. number_unsigned | 0..23 | Integer | 0x00..0x17
  10952. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  10953. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  10954. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1a
  10955. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1b
  10956. number_float | *any value* | Double-Precision Float | 0xfb
  10957. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  10958. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  10959. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  10960. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7a
  10961. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7b
  10962. array | *size*: 0..23 | array | 0x80..0x97
  10963. array | *size*: 23..255 | array (1 byte follow) | 0x98
  10964. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  10965. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9a
  10966. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9b
  10967. object | *size*: 0..23 | map | 0xa0..0xb7
  10968. object | *size*: 23..255 | map (1 byte follow) | 0xb8
  10969. object | *size*: 256..65535 | map (2 bytes follow) | 0xb9
  10970. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xba
  10971. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xbb
  10972. @note The mapping is **complete** in the sense that any JSON value type
  10973. can be converted to a CBOR value.
  10974. @note If NaN or Infinity are stored inside a JSON number, they are
  10975. serialized properly. This behavior differs from the @ref dump()
  10976. function which serializes NaN or Infinity to `null`.
  10977. @note The following CBOR types are not used in the conversion:
  10978. - byte strings (0x40..0x5f)
  10979. - UTF-8 strings terminated by "break" (0x7f)
  10980. - arrays terminated by "break" (0x9f)
  10981. - maps terminated by "break" (0xbf)
  10982. - date/time (0xc0..0xc1)
  10983. - bignum (0xc2..0xc3)
  10984. - decimal fraction (0xc4)
  10985. - bigfloat (0xc5)
  10986. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  10987. - expected conversions (0xd5..0xd7)
  10988. - simple values (0xe0..0xf3, 0xf8)
  10989. - undefined (0xf7)
  10990. - half and single-precision floats (0xf9-0xfa)
  10991. - break (0xff)
  10992. @param[in] j JSON value to serialize
  10993. @return MessagePack serialization as byte vector
  10994. @complexity Linear in the size of the JSON value @a j.
  10995. @liveexample{The example shows the serialization of a JSON value to a byte
  10996. vector in CBOR format.,to_cbor}
  10997. @sa http://cbor.io
  10998. @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
  10999. analogous deserialization
  11000. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  11001. @since version 2.0.9
  11002. */
  11003. static std::vector<uint8_t> to_cbor(const basic_json& j)
  11004. {
  11005. std::vector<uint8_t> result;
  11006. to_cbor(j, result);
  11007. return result;
  11008. }
  11009. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  11010. {
  11011. binary_writer<uint8_t>(o).write_cbor(j);
  11012. }
  11013. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  11014. {
  11015. binary_writer<char>(o).write_cbor(j);
  11016. }
  11017. /*!
  11018. @brief create a MessagePack serialization of a given JSON value
  11019. Serializes a given JSON value @a j to a byte vector using the MessagePack
  11020. serialization format. MessagePack is a binary serialization format which
  11021. aims to be more compact than JSON itself, yet more efficient to parse.
  11022. The library uses the following mapping from JSON values types to
  11023. MessagePack types according to the MessagePack specification:
  11024. JSON value type | value/range | MessagePack type | first byte
  11025. --------------- | --------------------------------- | ---------------- | ----------
  11026. null | `null` | nil | 0xc0
  11027. boolean | `true` | true | 0xc3
  11028. boolean | `false` | false | 0xc2
  11029. number_integer | -9223372036854775808..-2147483649 | int64 | 0xd3
  11030. number_integer | -2147483648..-32769 | int32 | 0xd2
  11031. number_integer | -32768..-129 | int16 | 0xd1
  11032. number_integer | -128..-33 | int8 | 0xd0
  11033. number_integer | -32..-1 | negative fixint | 0xe0..0xff
  11034. number_integer | 0..127 | positive fixint | 0x00..0x7f
  11035. number_integer | 128..255 | uint 8 | 0xcc
  11036. number_integer | 256..65535 | uint 16 | 0xcd
  11037. number_integer | 65536..4294967295 | uint 32 | 0xce
  11038. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xcf
  11039. number_unsigned | 0..127 | positive fixint | 0x00..0x7f
  11040. number_unsigned | 128..255 | uint 8 | 0xcc
  11041. number_unsigned | 256..65535 | uint 16 | 0xcd
  11042. number_unsigned | 65536..4294967295 | uint 32 | 0xce
  11043. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xcf
  11044. number_float | *any value* | float 64 | 0xcb
  11045. string | *length*: 0..31 | fixstr | 0xa0..0xbf
  11046. string | *length*: 32..255 | str 8 | 0xd9
  11047. string | *length*: 256..65535 | str 16 | 0xda
  11048. string | *length*: 65536..4294967295 | str 32 | 0xdb
  11049. array | *size*: 0..15 | fixarray | 0x90..0x9f
  11050. array | *size*: 16..65535 | array 16 | 0xdc
  11051. array | *size*: 65536..4294967295 | array 32 | 0xdd
  11052. object | *size*: 0..15 | fix map | 0x80..0x8f
  11053. object | *size*: 16..65535 | map 16 | 0xde
  11054. object | *size*: 65536..4294967295 | map 32 | 0xdf
  11055. @note The mapping is **complete** in the sense that any JSON value type
  11056. can be converted to a MessagePack value.
  11057. @note The following values can **not** be converted to a MessagePack value:
  11058. - strings with more than 4294967295 bytes
  11059. - arrays with more than 4294967295 elements
  11060. - objects with more than 4294967295 elements
  11061. @note The following MessagePack types are not used in the conversion:
  11062. - bin 8 - bin 32 (0xc4..0xc6)
  11063. - ext 8 - ext 32 (0xc7..0xc9)
  11064. - float 32 (0xca)
  11065. - fixext 1 - fixext 16 (0xd4..0xd8)
  11066. @note Any MessagePack output created @ref to_msgpack can be successfully
  11067. parsed by @ref from_msgpack.
  11068. @note If NaN or Infinity are stored inside a JSON number, they are
  11069. serialized properly. This behavior differs from the @ref dump()
  11070. function which serializes NaN or Infinity to `null`.
  11071. @param[in] j JSON value to serialize
  11072. @return MessagePack serialization as byte vector
  11073. @complexity Linear in the size of the JSON value @a j.
  11074. @liveexample{The example shows the serialization of a JSON value to a byte
  11075. vector in MessagePack format.,to_msgpack}
  11076. @sa http://msgpack.org
  11077. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  11078. analogous deserialization
  11079. @sa @ref to_cbor(const basic_json& for the related CBOR format
  11080. @since version 2.0.9
  11081. */
  11082. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  11083. {
  11084. std::vector<uint8_t> result;
  11085. to_msgpack(j, result);
  11086. return result;
  11087. }
  11088. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  11089. {
  11090. binary_writer<uint8_t>(o).write_msgpack(j);
  11091. }
  11092. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  11093. {
  11094. binary_writer<char>(o).write_msgpack(j);
  11095. }
  11096. /*!
  11097. @brief create a JSON value from an input in CBOR format
  11098. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  11099. Binary Object Representation) serialization format.
  11100. The library maps CBOR types to JSON value types as follows:
  11101. CBOR type | JSON value type | first byte
  11102. ---------------------- | --------------- | ----------
  11103. Integer | number_unsigned | 0x00..0x17
  11104. Unsigned integer | number_unsigned | 0x18
  11105. Unsigned integer | number_unsigned | 0x19
  11106. Unsigned integer | number_unsigned | 0x1a
  11107. Unsigned integer | number_unsigned | 0x1b
  11108. Negative integer | number_integer | 0x20..0x37
  11109. Negative integer | number_integer | 0x38
  11110. Negative integer | number_integer | 0x39
  11111. Negative integer | number_integer | 0x3a
  11112. Negative integer | number_integer | 0x3b
  11113. Negative integer | number_integer | 0x40..0x57
  11114. UTF-8 string | string | 0x60..0x77
  11115. UTF-8 string | string | 0x78
  11116. UTF-8 string | string | 0x79
  11117. UTF-8 string | string | 0x7a
  11118. UTF-8 string | string | 0x7b
  11119. UTF-8 string | string | 0x7f
  11120. array | array | 0x80..0x97
  11121. array | array | 0x98
  11122. array | array | 0x99
  11123. array | array | 0x9a
  11124. array | array | 0x9b
  11125. array | array | 0x9f
  11126. map | object | 0xa0..0xb7
  11127. map | object | 0xb8
  11128. map | object | 0xb9
  11129. map | object | 0xba
  11130. map | object | 0xbb
  11131. map | object | 0xbf
  11132. False | `false` | 0xf4
  11133. True | `true` | 0xf5
  11134. Nill | `null` | 0xf6
  11135. Half-Precision Float | number_float | 0xf9
  11136. Single-Precision Float | number_float | 0xfa
  11137. Double-Precision Float | number_float | 0xfb
  11138. @warning The mapping is **incomplete** in the sense that not all CBOR
  11139. types can be converted to a JSON value. The following CBOR types
  11140. are not supported and will yield parse errors (parse_error.112):
  11141. - byte strings (0x40..0x5f)
  11142. - date/time (0xc0..0xc1)
  11143. - bignum (0xc2..0xc3)
  11144. - decimal fraction (0xc4)
  11145. - bigfloat (0xc5)
  11146. - tagged items (0xc6..0xd4, 0xd8..0xdb)
  11147. - expected conversions (0xd5..0xd7)
  11148. - simple values (0xe0..0xf3, 0xf8)
  11149. - undefined (0xf7)
  11150. @warning CBOR allows map keys of any type, whereas JSON only allows
  11151. strings as keys in object values. Therefore, CBOR maps with keys
  11152. other than UTF-8 strings are rejected (parse_error.113).
  11153. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  11154. @ref from_cbor.
  11155. @param[in] i an input in CBOR format convertible to an input adapter
  11156. @param[in] strict whether to expect the input to be consumed until EOF
  11157. (true by default)
  11158. @return deserialized JSON value
  11159. @throw parse_error.110 if the given input ends prematurely or the end of
  11160. file was not reached when @a strict was set to true
  11161. @throw parse_error.112 if unsupported features from CBOR were
  11162. used in the given input @a v or if the input is not valid CBOR
  11163. @throw parse_error.113 if a string was expected as map key, but not found
  11164. @complexity Linear in the size of the input @a i.
  11165. @liveexample{The example shows the deserialization of a byte vector in CBOR
  11166. format to a JSON value.,from_cbor}
  11167. @sa http://cbor.io
  11168. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  11169. @sa @ref from_msgpack(detail::input_adapter, const bool) for the
  11170. related MessagePack format
  11171. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  11172. consume input adapters, removed start_index parameter, and added
  11173. @a strict parameter since 3.0.0
  11174. */
  11175. static basic_json from_cbor(detail::input_adapter i,
  11176. const bool strict = true)
  11177. {
  11178. return binary_reader(i).parse_cbor(strict);
  11179. }
  11180. /*!
  11181. @copydoc from_cbor(detail::input_adapter, const bool)
  11182. */
  11183. template<typename A1, typename A2,
  11184. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  11185. static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)
  11186. {
  11187. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);
  11188. }
  11189. /*!
  11190. @brief create a JSON value from an input in MessagePack format
  11191. Deserializes a given input @a i to a JSON value using the MessagePack
  11192. serialization format.
  11193. The library maps MessagePack types to JSON value types as follows:
  11194. MessagePack type | JSON value type | first byte
  11195. ---------------- | --------------- | ----------
  11196. positive fixint | number_unsigned | 0x00..0x7f
  11197. fixmap | object | 0x80..0x8f
  11198. fixarray | array | 0x90..0x9f
  11199. fixstr | string | 0xa0..0xbf
  11200. nil | `null` | 0xc0
  11201. false | `false` | 0xc2
  11202. true | `true` | 0xc3
  11203. float 32 | number_float | 0xca
  11204. float 64 | number_float | 0xcb
  11205. uint 8 | number_unsigned | 0xcc
  11206. uint 16 | number_unsigned | 0xcd
  11207. uint 32 | number_unsigned | 0xce
  11208. uint 64 | number_unsigned | 0xcf
  11209. int 8 | number_integer | 0xd0
  11210. int 16 | number_integer | 0xd1
  11211. int 32 | number_integer | 0xd2
  11212. int 64 | number_integer | 0xd3
  11213. str 8 | string | 0xd9
  11214. str 16 | string | 0xda
  11215. str 32 | string | 0xdb
  11216. array 16 | array | 0xdc
  11217. array 32 | array | 0xdd
  11218. map 16 | object | 0xde
  11219. map 32 | object | 0xdf
  11220. negative fixint | number_integer | 0xe0-0xff
  11221. @warning The mapping is **incomplete** in the sense that not all
  11222. MessagePack types can be converted to a JSON value. The following
  11223. MessagePack types are not supported and will yield parse errors:
  11224. - bin 8 - bin 32 (0xc4..0xc6)
  11225. - ext 8 - ext 32 (0xc7..0xc9)
  11226. - fixext 1 - fixext 16 (0xd4..0xd8)
  11227. @note Any MessagePack output created @ref to_msgpack can be successfully
  11228. parsed by @ref from_msgpack.
  11229. @param[in] i an input in MessagePack format convertible to an input
  11230. adapter
  11231. @param[in] strict whether to expect the input to be consumed until EOF
  11232. (true by default)
  11233. @throw parse_error.110 if the given input ends prematurely or the end of
  11234. file was not reached when @a strict was set to true
  11235. @throw parse_error.112 if unsupported features from MessagePack were
  11236. used in the given input @a i or if the input is not valid MessagePack
  11237. @throw parse_error.113 if a string was expected as map key, but not found
  11238. @complexity Linear in the size of the input @a i.
  11239. @liveexample{The example shows the deserialization of a byte vector in
  11240. MessagePack format to a JSON value.,from_msgpack}
  11241. @sa http://msgpack.org
  11242. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  11243. @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR
  11244. format
  11245. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  11246. consume input adapters, removed start_index parameter, and added
  11247. @a strict parameter since 3.0.0
  11248. */
  11249. static basic_json from_msgpack(detail::input_adapter i,
  11250. const bool strict = true)
  11251. {
  11252. return binary_reader(i).parse_msgpack(strict);
  11253. }
  11254. /*!
  11255. @copydoc from_msgpack(detail::input_adapter, const bool)
  11256. */
  11257. template<typename A1, typename A2,
  11258. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  11259. static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)
  11260. {
  11261. return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);
  11262. }
  11263. /// @}
  11264. //////////////////////////
  11265. // JSON Pointer support //
  11266. //////////////////////////
  11267. /// @name JSON Pointer functions
  11268. /// @{
  11269. /*!
  11270. @brief access specified element via JSON Pointer
  11271. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11272. No bound checking is performed. Similar to @ref operator[](const typename
  11273. object_t::key_type&), `null` values are created in arrays and objects if
  11274. necessary.
  11275. In particular:
  11276. - If the JSON pointer points to an object key that does not exist, it
  11277. is created an filled with a `null` value before a reference to it
  11278. is returned.
  11279. - If the JSON pointer points to an array index that does not exist, it
  11280. is created an filled with a `null` value before a reference to it
  11281. is returned. All indices between the current maximum and the given
  11282. index are also filled with `null`.
  11283. - The special value `-` is treated as a synonym for the index past the
  11284. end.
  11285. @param[in] ptr a JSON pointer
  11286. @return reference to the element pointed to by @a ptr
  11287. @complexity Constant.
  11288. @throw parse_error.106 if an array index begins with '0'
  11289. @throw parse_error.109 if an array index was not a number
  11290. @throw out_of_range.404 if the JSON pointer can not be resolved
  11291. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  11292. @since version 2.0.0
  11293. */
  11294. reference operator[](const json_pointer& ptr)
  11295. {
  11296. return ptr.get_unchecked(this);
  11297. }
  11298. /*!
  11299. @brief access specified element via JSON Pointer
  11300. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  11301. No bound checking is performed. The function does not change the JSON
  11302. value; no `null` values are created. In particular, the the special value
  11303. `-` yields an exception.
  11304. @param[in] ptr JSON pointer to the desired element
  11305. @return const reference to the element pointed to by @a ptr
  11306. @complexity Constant.
  11307. @throw parse_error.106 if an array index begins with '0'
  11308. @throw parse_error.109 if an array index was not a number
  11309. @throw out_of_range.402 if the array index '-' is used
  11310. @throw out_of_range.404 if the JSON pointer can not be resolved
  11311. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  11312. @since version 2.0.0
  11313. */
  11314. const_reference operator[](const json_pointer& ptr) const
  11315. {
  11316. return ptr.get_unchecked(this);
  11317. }
  11318. /*!
  11319. @brief access specified element via JSON Pointer
  11320. Returns a reference to the element at with specified JSON pointer @a ptr,
  11321. with bounds checking.
  11322. @param[in] ptr JSON pointer to the desired element
  11323. @return reference to the element pointed to by @a ptr
  11324. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11325. begins with '0'. See example below.
  11326. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11327. is not a number. See example below.
  11328. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11329. is out of range. See example below.
  11330. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11331. pointer @a ptr. As `at` provides checked access (and no elements are
  11332. implicitly inserted), the index '-' is always invalid. See example below.
  11333. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11334. See example below.
  11335. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11336. changes in the JSON value.
  11337. @complexity Constant.
  11338. @since version 2.0.0
  11339. @liveexample{The behavior is shown in the example.,at_json_pointer}
  11340. */
  11341. reference at(const json_pointer& ptr)
  11342. {
  11343. return ptr.get_checked(this);
  11344. }
  11345. /*!
  11346. @brief access specified element via JSON Pointer
  11347. Returns a const reference to the element at with specified JSON pointer @a
  11348. ptr, with bounds checking.
  11349. @param[in] ptr JSON pointer to the desired element
  11350. @return reference to the element pointed to by @a ptr
  11351. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  11352. begins with '0'. See example below.
  11353. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  11354. is not a number. See example below.
  11355. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  11356. is out of range. See example below.
  11357. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  11358. pointer @a ptr. As `at` provides checked access (and no elements are
  11359. implicitly inserted), the index '-' is always invalid. See example below.
  11360. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  11361. See example below.
  11362. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11363. changes in the JSON value.
  11364. @complexity Constant.
  11365. @since version 2.0.0
  11366. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  11367. */
  11368. const_reference at(const json_pointer& ptr) const
  11369. {
  11370. return ptr.get_checked(this);
  11371. }
  11372. /*!
  11373. @brief return flattened JSON value
  11374. The function creates a JSON object whose keys are JSON pointers (see [RFC
  11375. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  11376. primitive. The original JSON value can be restored using the @ref
  11377. unflatten() function.
  11378. @return an object that maps JSON pointers to primitive values
  11379. @note Empty objects and arrays are flattened to `null` and will not be
  11380. reconstructed correctly by the @ref unflatten() function.
  11381. @complexity Linear in the size the JSON value.
  11382. @liveexample{The following code shows how a JSON object is flattened to an
  11383. object whose keys consist of JSON pointers.,flatten}
  11384. @sa @ref unflatten() for the reverse function
  11385. @since version 2.0.0
  11386. */
  11387. basic_json flatten() const
  11388. {
  11389. basic_json result(value_t::object);
  11390. json_pointer::flatten("", *this, result);
  11391. return result;
  11392. }
  11393. /*!
  11394. @brief unflatten a previously flattened JSON value
  11395. The function restores the arbitrary nesting of a JSON value that has been
  11396. flattened before using the @ref flatten() function. The JSON value must
  11397. meet certain constraints:
  11398. 1. The value must be an object.
  11399. 2. The keys must be JSON pointers (see
  11400. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  11401. 3. The mapped values must be primitive JSON types.
  11402. @return the original JSON from a flattened version
  11403. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  11404. values and can not unflattened to their original type. Apart from
  11405. this example, for a JSON value `j`, the following is always true:
  11406. `j == j.flatten().unflatten()`.
  11407. @complexity Linear in the size the JSON value.
  11408. @throw type_error.314 if value is not an object
  11409. @throw type_error.315 if object values are not primitive
  11410. @liveexample{The following code shows how a flattened JSON object is
  11411. unflattened into the original nested JSON object.,unflatten}
  11412. @sa @ref flatten() for the reverse function
  11413. @since version 2.0.0
  11414. */
  11415. basic_json unflatten() const
  11416. {
  11417. return json_pointer::unflatten(*this);
  11418. }
  11419. /// @}
  11420. //////////////////////////
  11421. // JSON Patch functions //
  11422. //////////////////////////
  11423. /// @name JSON Patch functions
  11424. /// @{
  11425. /*!
  11426. @brief applies a JSON patch
  11427. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  11428. expressing a sequence of operations to apply to a JSON) document. With
  11429. this function, a JSON Patch is applied to the current JSON value by
  11430. executing all operations from the patch.
  11431. @param[in] json_patch JSON patch document
  11432. @return patched document
  11433. @note The application of a patch is atomic: Either all operations succeed
  11434. and the patched document is returned or an exception is thrown. In
  11435. any case, the original value is not changed: the patch is applied
  11436. to a copy of the value.
  11437. @throw parse_error.104 if the JSON patch does not consist of an array of
  11438. objects
  11439. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  11440. attributes are missing); example: `"operation add must have member path"`
  11441. @throw out_of_range.401 if an array index is out of range.
  11442. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  11443. resolved successfully in the current JSON value; example: `"key baz not
  11444. found"`
  11445. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  11446. "move")
  11447. @throw other_error.501 if "test" operation was unsuccessful
  11448. @complexity Linear in the size of the JSON value and the length of the
  11449. JSON patch. As usually only a fraction of the JSON value is affected by
  11450. the patch, the complexity can usually be neglected.
  11451. @liveexample{The following code shows how a JSON patch is applied to a
  11452. value.,patch}
  11453. @sa @ref diff -- create a JSON patch by comparing two JSON values
  11454. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11455. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  11456. @since version 2.0.0
  11457. */
  11458. basic_json patch(const basic_json& json_patch) const
  11459. {
  11460. // make a working copy to apply the patch to
  11461. basic_json result = *this;
  11462. // the valid JSON Patch operations
  11463. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  11464. const auto get_op = [](const std::string & op)
  11465. {
  11466. if (op == "add")
  11467. {
  11468. return patch_operations::add;
  11469. }
  11470. if (op == "remove")
  11471. {
  11472. return patch_operations::remove;
  11473. }
  11474. if (op == "replace")
  11475. {
  11476. return patch_operations::replace;
  11477. }
  11478. if (op == "move")
  11479. {
  11480. return patch_operations::move;
  11481. }
  11482. if (op == "copy")
  11483. {
  11484. return patch_operations::copy;
  11485. }
  11486. if (op == "test")
  11487. {
  11488. return patch_operations::test;
  11489. }
  11490. return patch_operations::invalid;
  11491. };
  11492. // wrapper for "add" operation; add value at ptr
  11493. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  11494. {
  11495. // adding to the root of the target document means replacing it
  11496. if (ptr.is_root())
  11497. {
  11498. result = val;
  11499. }
  11500. else
  11501. {
  11502. // make sure the top element of the pointer exists
  11503. json_pointer top_pointer = ptr.top();
  11504. if (top_pointer != ptr)
  11505. {
  11506. result.at(top_pointer);
  11507. }
  11508. // get reference to parent of JSON pointer ptr
  11509. const auto last_path = ptr.pop_back();
  11510. basic_json& parent = result[ptr];
  11511. switch (parent.m_type)
  11512. {
  11513. case value_t::null:
  11514. case value_t::object:
  11515. {
  11516. // use operator[] to add value
  11517. parent[last_path] = val;
  11518. break;
  11519. }
  11520. case value_t::array:
  11521. {
  11522. if (last_path == "-")
  11523. {
  11524. // special case: append to back
  11525. parent.push_back(val);
  11526. }
  11527. else
  11528. {
  11529. const auto idx = std::stoi(last_path);
  11530. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  11531. {
  11532. // avoid undefined behavior
  11533. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11534. }
  11535. else
  11536. {
  11537. // default case: insert add offset
  11538. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  11539. }
  11540. }
  11541. break;
  11542. }
  11543. default:
  11544. {
  11545. // if there exists a parent it cannot be primitive
  11546. assert(false); // LCOV_EXCL_LINE
  11547. }
  11548. }
  11549. }
  11550. };
  11551. // wrapper for "remove" operation; remove value at ptr
  11552. const auto operation_remove = [&result](json_pointer & ptr)
  11553. {
  11554. // get reference to parent of JSON pointer ptr
  11555. const auto last_path = ptr.pop_back();
  11556. basic_json& parent = result.at(ptr);
  11557. // remove child
  11558. if (parent.is_object())
  11559. {
  11560. // perform range check
  11561. auto it = parent.find(last_path);
  11562. if (JSON_LIKELY(it != parent.end()))
  11563. {
  11564. parent.erase(it);
  11565. }
  11566. else
  11567. {
  11568. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  11569. }
  11570. }
  11571. else if (parent.is_array())
  11572. {
  11573. // note erase performs range check
  11574. parent.erase(static_cast<size_type>(std::stoi(last_path)));
  11575. }
  11576. };
  11577. // type check: top level value must be an array
  11578. if (JSON_UNLIKELY(not json_patch.is_array()))
  11579. {
  11580. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11581. }
  11582. // iterate and apply the operations
  11583. for (const auto& val : json_patch)
  11584. {
  11585. // wrapper to get a value for an operation
  11586. const auto get_value = [&val](const std::string & op,
  11587. const std::string & member,
  11588. bool string_type) -> basic_json&
  11589. {
  11590. // find value
  11591. auto it = val.m_value.object->find(member);
  11592. // context-sensitive error message
  11593. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  11594. // check if desired value is present
  11595. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  11596. {
  11597. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  11598. }
  11599. // check if result is of type string
  11600. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  11601. {
  11602. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  11603. }
  11604. // no error: return value
  11605. return it->second;
  11606. };
  11607. // type check: every element of the array must be an object
  11608. if (JSON_UNLIKELY(not val.is_object()))
  11609. {
  11610. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  11611. }
  11612. // collect mandatory members
  11613. const std::string op = get_value("op", "op", true);
  11614. const std::string path = get_value(op, "path", true);
  11615. json_pointer ptr(path);
  11616. switch (get_op(op))
  11617. {
  11618. case patch_operations::add:
  11619. {
  11620. operation_add(ptr, get_value("add", "value", false));
  11621. break;
  11622. }
  11623. case patch_operations::remove:
  11624. {
  11625. operation_remove(ptr);
  11626. break;
  11627. }
  11628. case patch_operations::replace:
  11629. {
  11630. // the "path" location must exist - use at()
  11631. result.at(ptr) = get_value("replace", "value", false);
  11632. break;
  11633. }
  11634. case patch_operations::move:
  11635. {
  11636. const std::string from_path = get_value("move", "from", true);
  11637. json_pointer from_ptr(from_path);
  11638. // the "from" location must exist - use at()
  11639. basic_json v = result.at(from_ptr);
  11640. // The move operation is functionally identical to a
  11641. // "remove" operation on the "from" location, followed
  11642. // immediately by an "add" operation at the target
  11643. // location with the value that was just removed.
  11644. operation_remove(from_ptr);
  11645. operation_add(ptr, v);
  11646. break;
  11647. }
  11648. case patch_operations::copy:
  11649. {
  11650. const std::string from_path = get_value("copy", "from", true);
  11651. const json_pointer from_ptr(from_path);
  11652. // the "from" location must exist - use at()
  11653. result[ptr] = result.at(from_ptr);
  11654. break;
  11655. }
  11656. case patch_operations::test:
  11657. {
  11658. bool success = false;
  11659. JSON_TRY
  11660. {
  11661. // check if "value" matches the one at "path"
  11662. // the "path" location must exist - use at()
  11663. success = (result.at(ptr) == get_value("test", "value", false));
  11664. }
  11665. JSON_CATCH (out_of_range&)
  11666. {
  11667. // ignore out of range errors: success remains false
  11668. }
  11669. // throw an exception if test fails
  11670. if (JSON_UNLIKELY(not success))
  11671. {
  11672. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  11673. }
  11674. break;
  11675. }
  11676. case patch_operations::invalid:
  11677. {
  11678. // op must be "add", "remove", "replace", "move", "copy", or
  11679. // "test"
  11680. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  11681. }
  11682. }
  11683. }
  11684. return result;
  11685. }
  11686. /*!
  11687. @brief creates a diff as a JSON patch
  11688. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  11689. be changed into the value @a target by calling @ref patch function.
  11690. @invariant For two JSON values @a source and @a target, the following code
  11691. yields always `true`:
  11692. @code {.cpp}
  11693. source.patch(diff(source, target)) == target;
  11694. @endcode
  11695. @note Currently, only `remove`, `add`, and `replace` operations are
  11696. generated.
  11697. @param[in] source JSON value to compare from
  11698. @param[in] target JSON value to compare against
  11699. @param[in] path helper value to create JSON pointers
  11700. @return a JSON patch to convert the @a source to @a target
  11701. @complexity Linear in the lengths of @a source and @a target.
  11702. @liveexample{The following code shows how a JSON patch is created as a
  11703. diff for two JSON values.,diff}
  11704. @sa @ref patch -- apply a JSON patch
  11705. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  11706. @since version 2.0.0
  11707. */
  11708. static basic_json diff(const basic_json& source, const basic_json& target,
  11709. const std::string& path = "")
  11710. {
  11711. // the patch
  11712. basic_json result(value_t::array);
  11713. // if the values are the same, return empty patch
  11714. if (source == target)
  11715. {
  11716. return result;
  11717. }
  11718. if (source.type() != target.type())
  11719. {
  11720. // different types: replace value
  11721. result.push_back(
  11722. {
  11723. {"op", "replace"}, {"path", path}, {"value", target}
  11724. });
  11725. }
  11726. else
  11727. {
  11728. switch (source.type())
  11729. {
  11730. case value_t::array:
  11731. {
  11732. // first pass: traverse common elements
  11733. std::size_t i = 0;
  11734. while (i < source.size() and i < target.size())
  11735. {
  11736. // recursive call to compare array values at index i
  11737. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  11738. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11739. ++i;
  11740. }
  11741. // i now reached the end of at least one array
  11742. // in a second pass, traverse the remaining elements
  11743. // remove my remaining elements
  11744. const auto end_index = static_cast<difference_type>(result.size());
  11745. while (i < source.size())
  11746. {
  11747. // add operations in reverse order to avoid invalid
  11748. // indices
  11749. result.insert(result.begin() + end_index, object(
  11750. {
  11751. {"op", "remove"},
  11752. {"path", path + "/" + std::to_string(i)}
  11753. }));
  11754. ++i;
  11755. }
  11756. // add other remaining elements
  11757. while (i < target.size())
  11758. {
  11759. result.push_back(
  11760. {
  11761. {"op", "add"},
  11762. {"path", path + "/" + std::to_string(i)},
  11763. {"value", target[i]}
  11764. });
  11765. ++i;
  11766. }
  11767. break;
  11768. }
  11769. case value_t::object:
  11770. {
  11771. // first pass: traverse this object's elements
  11772. for (auto it = source.begin(); it != source.end(); ++it)
  11773. {
  11774. // escape the key name to be used in a JSON patch
  11775. const auto key = json_pointer::escape(it.key());
  11776. if (target.find(it.key()) != target.end())
  11777. {
  11778. // recursive call to compare object values at key it
  11779. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  11780. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  11781. }
  11782. else
  11783. {
  11784. // found a key that is not in o -> remove it
  11785. result.push_back(object(
  11786. {
  11787. {"op", "remove"}, {"path", path + "/" + key}
  11788. }));
  11789. }
  11790. }
  11791. // second pass: traverse other object's elements
  11792. for (auto it = target.begin(); it != target.end(); ++it)
  11793. {
  11794. if (source.find(it.key()) == source.end())
  11795. {
  11796. // found a key that is not in this -> add it
  11797. const auto key = json_pointer::escape(it.key());
  11798. result.push_back(
  11799. {
  11800. {"op", "add"}, {"path", path + "/" + key},
  11801. {"value", it.value()}
  11802. });
  11803. }
  11804. }
  11805. break;
  11806. }
  11807. default:
  11808. {
  11809. // both primitive type: replace value
  11810. result.push_back(
  11811. {
  11812. {"op", "replace"}, {"path", path}, {"value", target}
  11813. });
  11814. break;
  11815. }
  11816. }
  11817. }
  11818. return result;
  11819. }
  11820. /// @}
  11821. };
  11822. /////////////
  11823. // presets //
  11824. /////////////
  11825. /*!
  11826. @brief default JSON class
  11827. This type is the default specialization of the @ref basic_json class which
  11828. uses the standard template types.
  11829. @since version 1.0.0
  11830. */
  11831. using json = basic_json<>;
  11832. //////////////////
  11833. // json_pointer //
  11834. //////////////////
  11835. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11836. NLOHMANN_BASIC_JSON_TPL&
  11837. json_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const
  11838. {
  11839. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  11840. auto result = &j;
  11841. // in case no reference tokens exist, return a reference to the JSON value
  11842. // j which will be overwritten by a primitive value
  11843. for (const auto& reference_token : reference_tokens)
  11844. {
  11845. switch (result->m_type)
  11846. {
  11847. case detail::value_t::null:
  11848. {
  11849. if (reference_token == "0")
  11850. {
  11851. // start a new array if reference token is 0
  11852. result = &result->operator[](0);
  11853. }
  11854. else
  11855. {
  11856. // start a new object otherwise
  11857. result = &result->operator[](reference_token);
  11858. }
  11859. break;
  11860. }
  11861. case detail::value_t::object:
  11862. {
  11863. // create an entry in the object
  11864. result = &result->operator[](reference_token);
  11865. break;
  11866. }
  11867. case detail::value_t::array:
  11868. {
  11869. // create an entry in the array
  11870. JSON_TRY
  11871. {
  11872. result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
  11873. }
  11874. JSON_CATCH(std::invalid_argument&)
  11875. {
  11876. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11877. }
  11878. break;
  11879. }
  11880. /*
  11881. The following code is only reached if there exists a reference
  11882. token _and_ the current value is primitive. In this case, we have
  11883. an error situation, because primitive values may only occur as
  11884. single value; that is, with an empty list of reference tokens.
  11885. */
  11886. default:
  11887. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  11888. }
  11889. }
  11890. return *result;
  11891. }
  11892. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11893. NLOHMANN_BASIC_JSON_TPL&
  11894. json_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const
  11895. {
  11896. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  11897. for (const auto& reference_token : reference_tokens)
  11898. {
  11899. // convert null values to arrays or objects before continuing
  11900. if (ptr->m_type == detail::value_t::null)
  11901. {
  11902. // check if reference token is a number
  11903. const bool nums =
  11904. std::all_of(reference_token.begin(), reference_token.end(),
  11905. [](const char x)
  11906. {
  11907. return (x >= '0' and x <= '9');
  11908. });
  11909. // change value to array for numbers or "-" or to object otherwise
  11910. *ptr = (nums or reference_token == "-")
  11911. ? detail::value_t::array
  11912. : detail::value_t::object;
  11913. }
  11914. switch (ptr->m_type)
  11915. {
  11916. case detail::value_t::object:
  11917. {
  11918. // use unchecked object access
  11919. ptr = &ptr->operator[](reference_token);
  11920. break;
  11921. }
  11922. case detail::value_t::array:
  11923. {
  11924. // error condition (cf. RFC 6901, Sect. 4)
  11925. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  11926. {
  11927. JSON_THROW(detail::parse_error::create(106, 0,
  11928. "array index '" + reference_token +
  11929. "' must not begin with '0'"));
  11930. }
  11931. if (reference_token == "-")
  11932. {
  11933. // explicitly treat "-" as index beyond the end
  11934. ptr = &ptr->operator[](ptr->m_value.array->size());
  11935. }
  11936. else
  11937. {
  11938. // convert array index to number; unchecked access
  11939. JSON_TRY
  11940. {
  11941. ptr = &ptr->operator[](
  11942. static_cast<size_type>(std::stoi(reference_token)));
  11943. }
  11944. JSON_CATCH(std::invalid_argument&)
  11945. {
  11946. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11947. }
  11948. }
  11949. break;
  11950. }
  11951. default:
  11952. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  11953. }
  11954. }
  11955. return *ptr;
  11956. }
  11957. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  11958. NLOHMANN_BASIC_JSON_TPL&
  11959. json_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const
  11960. {
  11961. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  11962. for (const auto& reference_token : reference_tokens)
  11963. {
  11964. switch (ptr->m_type)
  11965. {
  11966. case detail::value_t::object:
  11967. {
  11968. // note: at performs range check
  11969. ptr = &ptr->at(reference_token);
  11970. break;
  11971. }
  11972. case detail::value_t::array:
  11973. {
  11974. if (JSON_UNLIKELY(reference_token == "-"))
  11975. {
  11976. // "-" always fails the range check
  11977. JSON_THROW(detail::out_of_range::create(402,
  11978. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  11979. ") is out of range"));
  11980. }
  11981. // error condition (cf. RFC 6901, Sect. 4)
  11982. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  11983. {
  11984. JSON_THROW(detail::parse_error::create(106, 0,
  11985. "array index '" + reference_token +
  11986. "' must not begin with '0'"));
  11987. }
  11988. // note: at performs range check
  11989. JSON_TRY
  11990. {
  11991. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  11992. }
  11993. JSON_CATCH(std::invalid_argument&)
  11994. {
  11995. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  11996. }
  11997. break;
  11998. }
  11999. default:
  12000. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12001. }
  12002. }
  12003. return *ptr;
  12004. }
  12005. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12006. const NLOHMANN_BASIC_JSON_TPL&
  12007. json_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
  12008. {
  12009. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12010. for (const auto& reference_token : reference_tokens)
  12011. {
  12012. switch (ptr->m_type)
  12013. {
  12014. case detail::value_t::object:
  12015. {
  12016. // use unchecked object access
  12017. ptr = &ptr->operator[](reference_token);
  12018. break;
  12019. }
  12020. case detail::value_t::array:
  12021. {
  12022. if (JSON_UNLIKELY(reference_token == "-"))
  12023. {
  12024. // "-" cannot be used for const access
  12025. JSON_THROW(detail::out_of_range::create(402,
  12026. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  12027. ") is out of range"));
  12028. }
  12029. // error condition (cf. RFC 6901, Sect. 4)
  12030. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12031. {
  12032. JSON_THROW(detail::parse_error::create(106, 0,
  12033. "array index '" + reference_token +
  12034. "' must not begin with '0'"));
  12035. }
  12036. // use unchecked array access
  12037. JSON_TRY
  12038. {
  12039. ptr = &ptr->operator[](
  12040. static_cast<size_type>(std::stoi(reference_token)));
  12041. }
  12042. JSON_CATCH(std::invalid_argument&)
  12043. {
  12044. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12045. }
  12046. break;
  12047. }
  12048. default:
  12049. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12050. }
  12051. }
  12052. return *ptr;
  12053. }
  12054. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12055. const NLOHMANN_BASIC_JSON_TPL&
  12056. json_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const
  12057. {
  12058. using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;
  12059. for (const auto& reference_token : reference_tokens)
  12060. {
  12061. switch (ptr->m_type)
  12062. {
  12063. case detail::value_t::object:
  12064. {
  12065. // note: at performs range check
  12066. ptr = &ptr->at(reference_token);
  12067. break;
  12068. }
  12069. case detail::value_t::array:
  12070. {
  12071. if (JSON_UNLIKELY(reference_token == "-"))
  12072. {
  12073. // "-" always fails the range check
  12074. JSON_THROW(detail::out_of_range::create(402,
  12075. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  12076. ") is out of range"));
  12077. }
  12078. // error condition (cf. RFC 6901, Sect. 4)
  12079. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  12080. {
  12081. JSON_THROW(detail::parse_error::create(106, 0,
  12082. "array index '" + reference_token +
  12083. "' must not begin with '0'"));
  12084. }
  12085. // note: at performs range check
  12086. JSON_TRY
  12087. {
  12088. ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
  12089. }
  12090. JSON_CATCH(std::invalid_argument&)
  12091. {
  12092. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  12093. }
  12094. break;
  12095. }
  12096. default:
  12097. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  12098. }
  12099. }
  12100. return *ptr;
  12101. }
  12102. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12103. void json_pointer::flatten(const std::string& reference_string,
  12104. const NLOHMANN_BASIC_JSON_TPL& value,
  12105. NLOHMANN_BASIC_JSON_TPL& result)
  12106. {
  12107. switch (value.m_type)
  12108. {
  12109. case detail::value_t::array:
  12110. {
  12111. if (value.m_value.array->empty())
  12112. {
  12113. // flatten empty array as null
  12114. result[reference_string] = nullptr;
  12115. }
  12116. else
  12117. {
  12118. // iterate array and use index as reference string
  12119. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  12120. {
  12121. flatten(reference_string + "/" + std::to_string(i),
  12122. value.m_value.array->operator[](i), result);
  12123. }
  12124. }
  12125. break;
  12126. }
  12127. case detail::value_t::object:
  12128. {
  12129. if (value.m_value.object->empty())
  12130. {
  12131. // flatten empty object as null
  12132. result[reference_string] = nullptr;
  12133. }
  12134. else
  12135. {
  12136. // iterate object and use keys as reference string
  12137. for (const auto& element : *value.m_value.object)
  12138. {
  12139. flatten(reference_string + "/" + escape(element.first), element.second, result);
  12140. }
  12141. }
  12142. break;
  12143. }
  12144. default:
  12145. {
  12146. // add primitive value with its reference string
  12147. result[reference_string] = value;
  12148. break;
  12149. }
  12150. }
  12151. }
  12152. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12153. NLOHMANN_BASIC_JSON_TPL
  12154. json_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)
  12155. {
  12156. if (JSON_UNLIKELY(not value.is_object()))
  12157. {
  12158. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  12159. }
  12160. NLOHMANN_BASIC_JSON_TPL result;
  12161. // iterate the JSON object values
  12162. for (const auto& element : *value.m_value.object)
  12163. {
  12164. if (JSON_UNLIKELY(not element.second.is_primitive()))
  12165. {
  12166. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  12167. }
  12168. // assign value to reference pointed to by JSON pointer; Note that if
  12169. // the JSON pointer is "" (i.e., points to the whole value), function
  12170. // get_and_create returns a reference to result itself. An assignment
  12171. // will then create a primitive value.
  12172. json_pointer(element.first).get_and_create(result) = element.second;
  12173. }
  12174. return result;
  12175. }
  12176. inline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept
  12177. {
  12178. return (lhs.reference_tokens == rhs.reference_tokens);
  12179. }
  12180. inline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept
  12181. {
  12182. return not (lhs == rhs);
  12183. }
  12184. } // namespace nlohmann
  12185. ///////////////////////
  12186. // nonmember support //
  12187. ///////////////////////
  12188. // specialization of std::swap, and std::hash
  12189. namespace std
  12190. {
  12191. /*!
  12192. @brief exchanges the values of two JSON objects
  12193. @since version 1.0.0
  12194. */
  12195. template<>
  12196. inline void swap(nlohmann::json& j1,
  12197. nlohmann::json& j2) noexcept(
  12198. is_nothrow_move_constructible<nlohmann::json>::value and
  12199. is_nothrow_move_assignable<nlohmann::json>::value
  12200. )
  12201. {
  12202. j1.swap(j2);
  12203. }
  12204. /// hash value for JSON objects
  12205. template<>
  12206. struct hash<nlohmann::json>
  12207. {
  12208. /*!
  12209. @brief return a hash value for a JSON object
  12210. @since version 1.0.0
  12211. */
  12212. std::size_t operator()(const nlohmann::json& j) const
  12213. {
  12214. // a naive hashing via the string representation
  12215. const auto& h = hash<nlohmann::json::string_t>();
  12216. return h(j.dump());
  12217. }
  12218. };
  12219. /// specialization for std::less<value_t>
  12220. /// @note: do not remove the space after '<',
  12221. /// see https://github.com/nlohmann/json/pull/679
  12222. template<>
  12223. struct less< ::nlohmann::detail::value_t>
  12224. {
  12225. /*!
  12226. @brief compare two value_t enum values
  12227. @since version 3.0.0
  12228. */
  12229. bool operator()(nlohmann::detail::value_t lhs,
  12230. nlohmann::detail::value_t rhs) const noexcept
  12231. {
  12232. return nlohmann::detail::operator<(lhs, rhs);
  12233. }
  12234. };
  12235. } // namespace std
  12236. /*!
  12237. @brief user-defined string literal for JSON values
  12238. This operator implements a user-defined string literal for JSON objects. It
  12239. can be used by adding `"_json"` to a string literal and returns a JSON object
  12240. if no parse error occurred.
  12241. @param[in] s a string representation of a JSON object
  12242. @param[in] n the length of string @a s
  12243. @return a JSON object
  12244. @since version 1.0.0
  12245. */
  12246. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  12247. {
  12248. return nlohmann::json::parse(s, s + n);
  12249. }
  12250. /*!
  12251. @brief user-defined string literal for JSON pointer
  12252. This operator implements a user-defined string literal for JSON Pointers. It
  12253. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  12254. object if no parse error occurred.
  12255. @param[in] s a string representation of a JSON Pointer
  12256. @param[in] n the length of string @a s
  12257. @return a JSON pointer object
  12258. @since version 2.0.0
  12259. */
  12260. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  12261. {
  12262. return nlohmann::json::json_pointer(std::string(s, n));
  12263. }
  12264. // restore GCC/clang diagnostic settings
  12265. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  12266. #pragma GCC diagnostic pop
  12267. #endif
  12268. #if defined(__clang__)
  12269. #pragma GCC diagnostic pop
  12270. #endif
  12271. // clean up
  12272. #undef JSON_CATCH
  12273. #undef JSON_THROW
  12274. #undef JSON_TRY
  12275. #undef JSON_LIKELY
  12276. #undef JSON_UNLIKELY
  12277. #undef JSON_DEPRECATED
  12278. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  12279. #undef NLOHMANN_BASIC_JSON_TPL
  12280. #endif