json.hpp 327 KB

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