json.hpp 338 KB

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