json.hpp 636 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912
  1. /*
  2. __ _____ _____ _____
  3. __| | __| | | | JSON for Modern C++
  4. | | |__ | | | | | | version 3.2.0
  5. |_____|_____|_____|_|___| https://github.com/nlohmann/json
  6. Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  7. SPDX-License-Identifier: MIT
  8. Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>.
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights
  12. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. copies of the Software, and to permit persons to whom the Software is
  14. furnished to do so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. #ifndef NLOHMANN_JSON_HPP
  26. #define NLOHMANN_JSON_HPP
  27. #define NLOHMANN_JSON_VERSION_MAJOR 3
  28. #define NLOHMANN_JSON_VERSION_MINOR 2
  29. #define NLOHMANN_JSON_VERSION_PATCH 0
  30. #include <algorithm> // all_of, find, for_each
  31. #include <cassert> // assert
  32. #include <ciso646> // and, not, or
  33. #include <cstddef> // nullptr_t, ptrdiff_t, size_t
  34. #include <functional> // hash, less
  35. #include <initializer_list> // initializer_list
  36. #include <iosfwd> // istream, ostream
  37. #include <iterator> // iterator_traits, random_access_iterator_tag
  38. #include <numeric> // accumulate
  39. #include <string> // string, stoi, to_string
  40. #include <utility> // declval, forward, move, pair, swap
  41. // #include <nlohmann/json_fwd.hpp>
  42. #ifndef NLOHMANN_JSON_FWD_HPP
  43. #define NLOHMANN_JSON_FWD_HPP
  44. #include <cstdint> // int64_t, uint64_t
  45. #include <map> // map
  46. #include <memory> // allocator
  47. #include <string> // string
  48. #include <vector> // vector
  49. /*!
  50. @brief namespace for Niels Lohmann
  51. @see https://github.com/nlohmann
  52. @since version 1.0.0
  53. */
  54. namespace nlohmann
  55. {
  56. /*!
  57. @brief default JSONSerializer template argument
  58. This serializer ignores the template arguments and uses ADL
  59. ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
  60. for serialization.
  61. */
  62. template<typename T = void, typename SFINAE = void>
  63. struct adl_serializer;
  64. template<template<typename U, typename V, typename... Args> class ObjectType =
  65. std::map,
  66. template<typename U, typename... Args> class ArrayType = std::vector,
  67. class StringType = std::string, class BooleanType = bool,
  68. class NumberIntegerType = std::int64_t,
  69. class NumberUnsignedType = std::uint64_t,
  70. class NumberFloatType = double,
  71. template<typename U> class AllocatorType = std::allocator,
  72. template<typename T, typename SFINAE = void> class JSONSerializer =
  73. adl_serializer>
  74. class basic_json;
  75. /*!
  76. @brief JSON Pointer
  77. A JSON pointer defines a string syntax for identifying a specific value
  78. within a JSON document. It can be used with functions `at` and
  79. `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
  80. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
  81. @since version 2.0.0
  82. */
  83. template<typename BasicJsonType>
  84. class json_pointer;
  85. /*!
  86. @brief default JSON class
  87. This type is the default specialization of the @ref basic_json class which
  88. uses the standard template types.
  89. @since version 1.0.0
  90. */
  91. using json = basic_json<>;
  92. }
  93. #endif
  94. // #include <nlohmann/detail/macro_scope.hpp>
  95. // This file contains all internal macro definitions
  96. // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them
  97. // exclude unsupported compilers
  98. #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK)
  99. #if defined(__clang__)
  100. #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400
  101. #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers"
  102. #endif
  103. #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))
  104. #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900
  105. #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers"
  106. #endif
  107. #endif
  108. #endif
  109. // disable float-equal warnings on GCC/clang
  110. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  111. #pragma GCC diagnostic push
  112. #pragma GCC diagnostic ignored "-Wfloat-equal"
  113. #endif
  114. // disable documentation warnings on clang
  115. #if defined(__clang__)
  116. #pragma GCC diagnostic push
  117. #pragma GCC diagnostic ignored "-Wdocumentation"
  118. #endif
  119. // allow for portable deprecation warnings
  120. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  121. #define JSON_DEPRECATED __attribute__((deprecated))
  122. #elif defined(_MSC_VER)
  123. #define JSON_DEPRECATED __declspec(deprecated)
  124. #else
  125. #define JSON_DEPRECATED
  126. #endif
  127. // allow to disable exceptions
  128. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION)
  129. #define JSON_THROW(exception) throw exception
  130. #define JSON_TRY try
  131. #define JSON_CATCH(exception) catch(exception)
  132. #define JSON_INTERNAL_CATCH(exception) catch(exception)
  133. #else
  134. #define JSON_THROW(exception) std::abort()
  135. #define JSON_TRY if(true)
  136. #define JSON_CATCH(exception) if(false)
  137. #define JSON_INTERNAL_CATCH(exception) if(false)
  138. #endif
  139. // override exception macros
  140. #if defined(JSON_THROW_USER)
  141. #undef JSON_THROW
  142. #define JSON_THROW JSON_THROW_USER
  143. #endif
  144. #if defined(JSON_TRY_USER)
  145. #undef JSON_TRY
  146. #define JSON_TRY JSON_TRY_USER
  147. #endif
  148. #if defined(JSON_CATCH_USER)
  149. #undef JSON_CATCH
  150. #define JSON_CATCH JSON_CATCH_USER
  151. #define JSON_INTERNAL_CATCH JSON_CATCH_USER
  152. #endif
  153. #if defined(JSON_INTERNAL_CATCH_USER)
  154. #undef JSON_INTERNAL_CATCH
  155. #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER
  156. #endif
  157. // manual branch prediction
  158. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  159. #define JSON_LIKELY(x) __builtin_expect(!!(x), 1)
  160. #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
  161. #else
  162. #define JSON_LIKELY(x) x
  163. #define JSON_UNLIKELY(x) x
  164. #endif
  165. // C++ language standard detection
  166. #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464
  167. #define JSON_HAS_CPP_17
  168. #define JSON_HAS_CPP_14
  169. #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)
  170. #define JSON_HAS_CPP_14
  171. #endif
  172. // Ugly macros to avoid uglier copy-paste when specializing basic_json. They
  173. // may be removed in the future once the class is split.
  174. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \
  175. template<template<typename, typename, typename...> class ObjectType, \
  176. template<typename, typename...> class ArrayType, \
  177. class StringType, class BooleanType, class NumberIntegerType, \
  178. class NumberUnsignedType, class NumberFloatType, \
  179. template<typename> class AllocatorType, \
  180. template<typename, typename = void> class JSONSerializer>
  181. #define NLOHMANN_BASIC_JSON_TPL \
  182. basic_json<ObjectType, ArrayType, StringType, BooleanType, \
  183. NumberIntegerType, NumberUnsignedType, NumberFloatType, \
  184. AllocatorType, JSONSerializer>
  185. /*!
  186. @brief Helper to determine whether there's a key_type for T.
  187. This helper is used to tell associative containers apart from other containers
  188. such as sequence containers. For instance, `std::map` passes the test as it
  189. contains a `mapped_type`, whereas `std::vector` fails the test.
  190. @sa http://stackoverflow.com/a/7728728/266378
  191. @since version 1.0.0, overworked in version 2.0.6
  192. */
  193. #define NLOHMANN_JSON_HAS_HELPER(type) \
  194. template<typename T> struct has_##type { \
  195. private: \
  196. template<typename U, typename = typename U::type> \
  197. static int detect(U &&); \
  198. static void detect(...); \
  199. public: \
  200. static constexpr bool value = \
  201. std::is_integral<decltype(detect(std::declval<T>()))>::value; \
  202. }
  203. // #include <nlohmann/detail/meta/cpp_future.hpp>
  204. #include <ciso646> // not
  205. #include <cstddef> // size_t
  206. #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type
  207. namespace nlohmann
  208. {
  209. namespace detail
  210. {
  211. // alias templates to reduce boilerplate
  212. template<bool B, typename T = void>
  213. using enable_if_t = typename std::enable_if<B, T>::type;
  214. template<typename T>
  215. using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
  216. // implementation of C++14 index_sequence and affiliates
  217. // source: https://stackoverflow.com/a/32223343
  218. template<std::size_t... Ints>
  219. struct index_sequence
  220. {
  221. using type = index_sequence;
  222. using value_type = std::size_t;
  223. static constexpr std::size_t size() noexcept
  224. {
  225. return sizeof...(Ints);
  226. }
  227. };
  228. template<class Sequence1, class Sequence2>
  229. struct merge_and_renumber;
  230. template<std::size_t... I1, std::size_t... I2>
  231. struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>
  232. : index_sequence < I1..., (sizeof...(I1) + I2)... > {};
  233. template<std::size_t N>
  234. struct make_index_sequence
  235. : merge_and_renumber < typename make_index_sequence < N / 2 >::type,
  236. typename make_index_sequence < N - N / 2 >::type > {};
  237. template<> struct make_index_sequence<0> : index_sequence<> {};
  238. template<> struct make_index_sequence<1> : index_sequence<0> {};
  239. template<typename... Ts>
  240. using index_sequence_for = make_index_sequence<sizeof...(Ts)>;
  241. /*
  242. Implementation of two C++17 constructs: conjunction, negation. This is needed
  243. to avoid evaluating all the traits in a condition
  244. For example: not std::is_same<void, T>::value and has_value_type<T>::value
  245. will not compile when T = void (on MSVC at least). Whereas
  246. conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
  247. stop evaluating if negation<...>::value == false
  248. Please note that those constructs must be used with caution, since symbols can
  249. become very long quickly (which can slow down compilation and cause MSVC
  250. internal compiler errors). Only use it when you have to (see example ahead).
  251. */
  252. template<class...> struct conjunction : std::true_type {};
  253. template<class B1> struct conjunction<B1> : B1 {};
  254. template<class B1, class... Bn>
  255. struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
  256. template<class B> struct negation : std::integral_constant<bool, not B::value> {};
  257. // dispatch utility (taken from ranges-v3)
  258. template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
  259. template<> struct priority_tag<0> {};
  260. // taken from ranges-v3
  261. template<typename T>
  262. struct static_const
  263. {
  264. static constexpr T value{};
  265. };
  266. template<typename T>
  267. constexpr T static_const<T>::value;
  268. }
  269. }
  270. // #include <nlohmann/detail/meta/type_traits.hpp>
  271. #include <ciso646> // not
  272. #include <limits> // numeric_limits
  273. #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type
  274. #include <utility> // declval
  275. // #include <nlohmann/json_fwd.hpp>
  276. // #include <nlohmann/detail/meta/cpp_future.hpp>
  277. // #include <nlohmann/detail/macro_scope.hpp>
  278. namespace nlohmann
  279. {
  280. /*!
  281. @brief detail namespace with internal helper functions
  282. This namespace collects functions that should not be exposed,
  283. implementations of some @ref basic_json methods, and meta-programming helpers.
  284. @since version 2.1.0
  285. */
  286. namespace detail
  287. {
  288. /////////////
  289. // helpers //
  290. /////////////
  291. template<typename> struct is_basic_json : std::false_type {};
  292. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  293. struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};
  294. ////////////////////////
  295. // has_/is_ functions //
  296. ////////////////////////
  297. // source: https://stackoverflow.com/a/37193089/4116453
  298. template <typename T, typename = void>
  299. struct is_complete_type : std::false_type {};
  300. template <typename T>
  301. struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {};
  302. NLOHMANN_JSON_HAS_HELPER(mapped_type);
  303. NLOHMANN_JSON_HAS_HELPER(key_type);
  304. NLOHMANN_JSON_HAS_HELPER(value_type);
  305. NLOHMANN_JSON_HAS_HELPER(iterator);
  306. template<bool B, class RealType, class CompatibleObjectType>
  307. struct is_compatible_object_type_impl : std::false_type {};
  308. template<class RealType, class CompatibleObjectType>
  309. struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
  310. {
  311. static constexpr auto value =
  312. std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and
  313. std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;
  314. };
  315. template<bool B, class RealType, class CompatibleStringType>
  316. struct is_compatible_string_type_impl : std::false_type {};
  317. template<class RealType, class CompatibleStringType>
  318. struct is_compatible_string_type_impl<true, RealType, CompatibleStringType>
  319. {
  320. static constexpr auto value =
  321. std::is_same<typename RealType::value_type, typename CompatibleStringType::value_type>::value and
  322. std::is_constructible<RealType, CompatibleStringType>::value;
  323. };
  324. template<class BasicJsonType, class CompatibleObjectType>
  325. struct is_compatible_object_type
  326. {
  327. static auto constexpr value = is_compatible_object_type_impl <
  328. conjunction<negation<std::is_same<void, CompatibleObjectType>>,
  329. has_mapped_type<CompatibleObjectType>,
  330. has_key_type<CompatibleObjectType>>::value,
  331. typename BasicJsonType::object_t, CompatibleObjectType >::value;
  332. };
  333. template<class BasicJsonType, class CompatibleStringType>
  334. struct is_compatible_string_type
  335. {
  336. static auto constexpr value = is_compatible_string_type_impl <
  337. conjunction<negation<std::is_same<void, CompatibleStringType>>,
  338. has_value_type<CompatibleStringType>>::value,
  339. typename BasicJsonType::string_t, CompatibleStringType >::value;
  340. };
  341. template<typename BasicJsonType, typename T>
  342. struct is_basic_json_nested_type
  343. {
  344. static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
  345. std::is_same<T, typename BasicJsonType::const_iterator>::value or
  346. std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
  347. std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;
  348. };
  349. template<class BasicJsonType, class CompatibleArrayType>
  350. struct is_compatible_array_type
  351. {
  352. static auto constexpr value =
  353. conjunction<negation<std::is_same<void, CompatibleArrayType>>,
  354. negation<is_compatible_object_type<
  355. BasicJsonType, CompatibleArrayType>>,
  356. negation<std::is_constructible<typename BasicJsonType::string_t,
  357. CompatibleArrayType>>,
  358. negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
  359. has_value_type<CompatibleArrayType>,
  360. has_iterator<CompatibleArrayType>>::value;
  361. };
  362. template<bool, typename, typename>
  363. struct is_compatible_integer_type_impl : std::false_type {};
  364. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  365. struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
  366. {
  367. // is there an assert somewhere on overflows?
  368. using RealLimits = std::numeric_limits<RealIntegerType>;
  369. using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
  370. static constexpr auto value =
  371. std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and
  372. CompatibleLimits::is_integer and
  373. RealLimits::is_signed == CompatibleLimits::is_signed;
  374. };
  375. template<typename RealIntegerType, typename CompatibleNumberIntegerType>
  376. struct is_compatible_integer_type
  377. {
  378. static constexpr auto value =
  379. is_compatible_integer_type_impl <
  380. std::is_integral<CompatibleNumberIntegerType>::value and
  381. not std::is_same<bool, CompatibleNumberIntegerType>::value,
  382. RealIntegerType, CompatibleNumberIntegerType > ::value;
  383. };
  384. // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
  385. template<typename BasicJsonType, typename T>
  386. struct has_from_json
  387. {
  388. private:
  389. // also check the return type of from_json
  390. template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
  391. std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
  392. static int detect(U&&);
  393. static void detect(...);
  394. public:
  395. static constexpr bool value = std::is_integral<decltype(
  396. detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  397. };
  398. // This trait checks if JSONSerializer<T>::from_json(json const&) exists
  399. // this overload is used for non-default-constructible user-defined-types
  400. template<typename BasicJsonType, typename T>
  401. struct has_non_default_from_json
  402. {
  403. private:
  404. template <
  405. typename U,
  406. typename = enable_if_t<std::is_same<
  407. T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
  408. static int detect(U&&);
  409. static void detect(...);
  410. public:
  411. static constexpr bool value = std::is_integral<decltype(detect(
  412. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  413. };
  414. // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
  415. template<typename BasicJsonType, typename T>
  416. struct has_to_json
  417. {
  418. private:
  419. template<typename U, typename = decltype(uncvref_t<U>::to_json(
  420. std::declval<BasicJsonType&>(), std::declval<T>()))>
  421. static int detect(U&&);
  422. static void detect(...);
  423. public:
  424. static constexpr bool value = std::is_integral<decltype(detect(
  425. std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;
  426. };
  427. template <typename BasicJsonType, typename CompatibleCompleteType>
  428. struct is_compatible_complete_type
  429. {
  430. static constexpr bool value =
  431. not std::is_base_of<std::istream, CompatibleCompleteType>::value and
  432. not is_basic_json<CompatibleCompleteType>::value and
  433. not is_basic_json_nested_type<BasicJsonType, CompatibleCompleteType>::value and
  434. has_to_json<BasicJsonType, CompatibleCompleteType>::value;
  435. };
  436. template <typename BasicJsonType, typename CompatibleType>
  437. struct is_compatible_type
  438. : conjunction<is_complete_type<CompatibleType>,
  439. is_compatible_complete_type<BasicJsonType, CompatibleType>>
  440. {
  441. };
  442. }
  443. }
  444. // #include <nlohmann/detail/exceptions.hpp>
  445. #include <exception> // exception
  446. #include <stdexcept> // runtime_error
  447. #include <string> // to_string
  448. namespace nlohmann
  449. {
  450. namespace detail
  451. {
  452. ////////////////
  453. // exceptions //
  454. ////////////////
  455. /*!
  456. @brief general exception of the @ref basic_json class
  457. This class is an extension of `std::exception` objects with a member @a id for
  458. exception ids. It is used as the base class for all exceptions thrown by the
  459. @ref basic_json class. This class can hence be used as "wildcard" to catch
  460. exceptions.
  461. Subclasses:
  462. - @ref parse_error for exceptions indicating a parse error
  463. - @ref invalid_iterator for exceptions indicating errors with iterators
  464. - @ref type_error for exceptions indicating executing a member function with
  465. a wrong type
  466. - @ref out_of_range for exceptions indicating access out of the defined range
  467. - @ref other_error for exceptions indicating other library errors
  468. @internal
  469. @note To have nothrow-copy-constructible exceptions, we internally use
  470. `std::runtime_error` which can cope with arbitrary-length error messages.
  471. Intermediate strings are built with static functions and then passed to
  472. the actual constructor.
  473. @endinternal
  474. @liveexample{The following code shows how arbitrary library exceptions can be
  475. caught.,exception}
  476. @since version 3.0.0
  477. */
  478. class exception : public std::exception
  479. {
  480. public:
  481. /// returns the explanatory string
  482. const char* what() const noexcept override
  483. {
  484. return m.what();
  485. }
  486. /// the id of the exception
  487. const int id;
  488. protected:
  489. exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}
  490. static std::string name(const std::string& ename, int id_)
  491. {
  492. return "[json.exception." + ename + "." + std::to_string(id_) + "] ";
  493. }
  494. private:
  495. /// an exception object as storage for error messages
  496. std::runtime_error m;
  497. };
  498. /*!
  499. @brief exception indicating a parse error
  500. This exception is thrown by the library when a parse error occurs. Parse errors
  501. can occur during the deserialization of JSON text, CBOR, MessagePack, as well
  502. as when using JSON Patch.
  503. Member @a byte holds the byte index of the last read character in the input
  504. file.
  505. Exceptions have ids 1xx.
  506. name / id | example message | description
  507. ------------------------------ | --------------- | -------------------------
  508. json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.
  509. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
  510. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
  511. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.
  512. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors.
  513. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.
  514. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.
  515. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
  516. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.
  517. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
  518. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.
  519. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.
  520. @note For an input with n bytes, 1 is the index of the first character and n+1
  521. is the index of the terminating null byte or the end of file. This also
  522. holds true when reading a byte vector (CBOR or MessagePack).
  523. @liveexample{The following code shows how a `parse_error` exception can be
  524. caught.,parse_error}
  525. @sa @ref exception for the base class of the library exceptions
  526. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  527. @sa @ref type_error for exceptions indicating executing a member function with
  528. a wrong type
  529. @sa @ref out_of_range for exceptions indicating access out of the defined range
  530. @sa @ref other_error for exceptions indicating other library errors
  531. @since version 3.0.0
  532. */
  533. class parse_error : public exception
  534. {
  535. public:
  536. /*!
  537. @brief create a parse error exception
  538. @param[in] id_ the id of the exception
  539. @param[in] byte_ the byte index where the error occurred (or 0 if the
  540. position cannot be determined)
  541. @param[in] what_arg the explanatory string
  542. @return parse_error object
  543. */
  544. static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)
  545. {
  546. std::string w = exception::name("parse_error", id_) + "parse error" +
  547. (byte_ != 0 ? (" at " + std::to_string(byte_)) : "") +
  548. ": " + what_arg;
  549. return parse_error(id_, byte_, w.c_str());
  550. }
  551. /*!
  552. @brief byte index of the parse error
  553. The byte index of the last read character in the input file.
  554. @note For an input with n bytes, 1 is the index of the first character and
  555. n+1 is the index of the terminating null byte or the end of file.
  556. This also holds true when reading a byte vector (CBOR or MessagePack).
  557. */
  558. const std::size_t byte;
  559. private:
  560. parse_error(int id_, std::size_t byte_, const char* what_arg)
  561. : exception(id_, what_arg), byte(byte_) {}
  562. };
  563. /*!
  564. @brief exception indicating errors with iterators
  565. This exception is thrown if iterators passed to a library function do not match
  566. the expected semantics.
  567. Exceptions have ids 2xx.
  568. name / id | example message | description
  569. ----------------------------------- | --------------- | -------------------------
  570. json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  571. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
  572. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
  573. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.
  574. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.
  575. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.
  576. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
  577. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  578. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
  579. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.
  580. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.
  581. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.
  582. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.
  583. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().
  584. @liveexample{The following code shows how an `invalid_iterator` exception can be
  585. caught.,invalid_iterator}
  586. @sa @ref exception for the base class of the library exceptions
  587. @sa @ref parse_error for exceptions indicating a parse error
  588. @sa @ref type_error for exceptions indicating executing a member function with
  589. a wrong type
  590. @sa @ref out_of_range for exceptions indicating access out of the defined range
  591. @sa @ref other_error for exceptions indicating other library errors
  592. @since version 3.0.0
  593. */
  594. class invalid_iterator : public exception
  595. {
  596. public:
  597. static invalid_iterator create(int id_, const std::string& what_arg)
  598. {
  599. std::string w = exception::name("invalid_iterator", id_) + what_arg;
  600. return invalid_iterator(id_, w.c_str());
  601. }
  602. private:
  603. invalid_iterator(int id_, const char* what_arg)
  604. : exception(id_, what_arg) {}
  605. };
  606. /*!
  607. @brief exception indicating executing a member function with a wrong type
  608. This exception is thrown in case of a type error; that is, a library function is
  609. executed on a JSON value whose type does not match the expected semantics.
  610. Exceptions have ids 3xx.
  611. name / id | example message | description
  612. ----------------------------- | --------------- | -------------------------
  613. json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
  614. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
  615. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.
  616. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.
  617. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.
  618. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.
  619. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.
  620. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.
  621. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.
  622. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.
  623. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.
  624. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.
  625. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.
  626. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.
  627. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.
  628. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |
  629. @liveexample{The following code shows how a `type_error` exception can be
  630. caught.,type_error}
  631. @sa @ref exception for the base class of the library exceptions
  632. @sa @ref parse_error for exceptions indicating a parse error
  633. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  634. @sa @ref out_of_range for exceptions indicating access out of the defined range
  635. @sa @ref other_error for exceptions indicating other library errors
  636. @since version 3.0.0
  637. */
  638. class type_error : public exception
  639. {
  640. public:
  641. static type_error create(int id_, const std::string& what_arg)
  642. {
  643. std::string w = exception::name("type_error", id_) + what_arg;
  644. return type_error(id_, w.c_str());
  645. }
  646. private:
  647. type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  648. };
  649. /*!
  650. @brief exception indicating access out of the defined range
  651. This exception is thrown in case a library function is called on an input
  652. parameter that exceeds the expected range, for instance in case of array
  653. indices or nonexisting object keys.
  654. Exceptions have ids 4xx.
  655. name / id | example message | description
  656. ------------------------------- | --------------- | -------------------------
  657. json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.
  658. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
  659. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.
  660. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.
  661. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.
  662. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.
  663. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON only supports integers numbers up to 9223372036854775807. |
  664. json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. |
  665. @liveexample{The following code shows how an `out_of_range` exception can be
  666. caught.,out_of_range}
  667. @sa @ref exception for the base class of the library exceptions
  668. @sa @ref parse_error for exceptions indicating a parse error
  669. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  670. @sa @ref type_error for exceptions indicating executing a member function with
  671. a wrong type
  672. @sa @ref other_error for exceptions indicating other library errors
  673. @since version 3.0.0
  674. */
  675. class out_of_range : public exception
  676. {
  677. public:
  678. static out_of_range create(int id_, const std::string& what_arg)
  679. {
  680. std::string w = exception::name("out_of_range", id_) + what_arg;
  681. return out_of_range(id_, w.c_str());
  682. }
  683. private:
  684. out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}
  685. };
  686. /*!
  687. @brief exception indicating other library errors
  688. This exception is thrown in case of errors that cannot be classified with the
  689. other exception types.
  690. Exceptions have ids 5xx.
  691. name / id | example message | description
  692. ------------------------------ | --------------- | -------------------------
  693. json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.
  694. @sa @ref exception for the base class of the library exceptions
  695. @sa @ref parse_error for exceptions indicating a parse error
  696. @sa @ref invalid_iterator for exceptions indicating errors with iterators
  697. @sa @ref type_error for exceptions indicating executing a member function with
  698. a wrong type
  699. @sa @ref out_of_range for exceptions indicating access out of the defined range
  700. @liveexample{The following code shows how an `other_error` exception can be
  701. caught.,other_error}
  702. @since version 3.0.0
  703. */
  704. class other_error : public exception
  705. {
  706. public:
  707. static other_error create(int id_, const std::string& what_arg)
  708. {
  709. std::string w = exception::name("other_error", id_) + what_arg;
  710. return other_error(id_, w.c_str());
  711. }
  712. private:
  713. other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}
  714. };
  715. }
  716. }
  717. // #include <nlohmann/detail/value_t.hpp>
  718. #include <array> // array
  719. #include <ciso646> // and
  720. #include <cstddef> // size_t
  721. #include <cstdint> // uint8_t
  722. namespace nlohmann
  723. {
  724. namespace detail
  725. {
  726. ///////////////////////////
  727. // JSON type enumeration //
  728. ///////////////////////////
  729. /*!
  730. @brief the JSON type enumeration
  731. This enumeration collects the different JSON types. It is internally used to
  732. distinguish the stored values, and the functions @ref basic_json::is_null(),
  733. @ref basic_json::is_object(), @ref basic_json::is_array(),
  734. @ref basic_json::is_string(), @ref basic_json::is_boolean(),
  735. @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
  736. @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
  737. @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
  738. @ref basic_json::is_structured() rely on it.
  739. @note There are three enumeration entries (number_integer, number_unsigned, and
  740. number_float), because the library distinguishes these three types for numbers:
  741. @ref basic_json::number_unsigned_t is used for unsigned integers,
  742. @ref basic_json::number_integer_t is used for signed integers, and
  743. @ref basic_json::number_float_t is used for floating-point numbers or to
  744. approximate integers which do not fit in the limits of their respective type.
  745. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
  746. value with the default value for a given type
  747. @since version 1.0.0
  748. */
  749. enum class value_t : std::uint8_t
  750. {
  751. null, ///< null value
  752. object, ///< object (unordered set of name/value pairs)
  753. array, ///< array (ordered collection of values)
  754. string, ///< string value
  755. boolean, ///< boolean value
  756. number_integer, ///< number value (signed integer)
  757. number_unsigned, ///< number value (unsigned integer)
  758. number_float, ///< number value (floating-point)
  759. discarded ///< discarded by the the parser callback function
  760. };
  761. /*!
  762. @brief comparison operator for JSON types
  763. Returns an ordering that is similar to Python:
  764. - order: null < boolean < number < object < array < string
  765. - furthermore, each type is not smaller than itself
  766. - discarded values are not comparable
  767. @since version 1.0.0
  768. */
  769. inline bool operator<(const value_t lhs, const value_t rhs) noexcept
  770. {
  771. static constexpr std::array<std::uint8_t, 8> order = {{
  772. 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,
  773. 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */
  774. }
  775. };
  776. const auto l_index = static_cast<std::size_t>(lhs);
  777. const auto r_index = static_cast<std::size_t>(rhs);
  778. return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];
  779. }
  780. }
  781. }
  782. // #include <nlohmann/detail/conversions/from_json.hpp>
  783. #include <algorithm> // transform
  784. #include <array> // array
  785. #include <ciso646> // and, not
  786. #include <forward_list> // forward_list
  787. #include <iterator> // inserter, front_inserter, end
  788. #include <map> // map
  789. #include <string> // string
  790. #include <tuple> // tuple, make_tuple
  791. #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
  792. #include <unordered_map> // unordered_map
  793. #include <utility> // pair, declval
  794. #include <valarray> // valarray
  795. // #include <nlohmann/detail/exceptions.hpp>
  796. // #include <nlohmann/detail/macro_scope.hpp>
  797. // #include <nlohmann/detail/meta/cpp_future.hpp>
  798. // #include <nlohmann/detail/meta/type_traits.hpp>
  799. // #include <nlohmann/detail/value_t.hpp>
  800. namespace nlohmann
  801. {
  802. namespace detail
  803. {
  804. template<typename BasicJsonType>
  805. void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
  806. {
  807. if (JSON_UNLIKELY(not j.is_null()))
  808. {
  809. JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name())));
  810. }
  811. n = nullptr;
  812. }
  813. // overloads for basic_json template parameters
  814. template<typename BasicJsonType, typename ArithmeticType,
  815. enable_if_t<std::is_arithmetic<ArithmeticType>::value and
  816. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  817. int> = 0>
  818. void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
  819. {
  820. switch (static_cast<value_t>(j))
  821. {
  822. case value_t::number_unsigned:
  823. {
  824. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  825. break;
  826. }
  827. case value_t::number_integer:
  828. {
  829. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  830. break;
  831. }
  832. case value_t::number_float:
  833. {
  834. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  835. break;
  836. }
  837. default:
  838. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  839. }
  840. }
  841. template<typename BasicJsonType>
  842. void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
  843. {
  844. if (JSON_UNLIKELY(not j.is_boolean()))
  845. {
  846. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name())));
  847. }
  848. b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
  849. }
  850. template<typename BasicJsonType>
  851. void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
  852. {
  853. if (JSON_UNLIKELY(not j.is_string()))
  854. {
  855. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  856. }
  857. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  858. }
  859. template <
  860. typename BasicJsonType, typename CompatibleStringType,
  861. enable_if_t <
  862. is_compatible_string_type<BasicJsonType, CompatibleStringType>::value and
  863. not std::is_same<typename BasicJsonType::string_t,
  864. CompatibleStringType>::value,
  865. int > = 0 >
  866. void from_json(const BasicJsonType& j, CompatibleStringType& s)
  867. {
  868. if (JSON_UNLIKELY(not j.is_string()))
  869. {
  870. JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name())));
  871. }
  872. s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
  873. }
  874. template<typename BasicJsonType>
  875. void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
  876. {
  877. get_arithmetic_value(j, val);
  878. }
  879. template<typename BasicJsonType>
  880. void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
  881. {
  882. get_arithmetic_value(j, val);
  883. }
  884. template<typename BasicJsonType>
  885. void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
  886. {
  887. get_arithmetic_value(j, val);
  888. }
  889. template<typename BasicJsonType, typename EnumType,
  890. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  891. void from_json(const BasicJsonType& j, EnumType& e)
  892. {
  893. typename std::underlying_type<EnumType>::type val;
  894. get_arithmetic_value(j, val);
  895. e = static_cast<EnumType>(val);
  896. }
  897. template<typename BasicJsonType>
  898. void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
  899. {
  900. if (JSON_UNLIKELY(not j.is_array()))
  901. {
  902. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  903. }
  904. arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
  905. }
  906. // forward_list doesn't have an insert method
  907. template<typename BasicJsonType, typename T, typename Allocator,
  908. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  909. void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
  910. {
  911. if (JSON_UNLIKELY(not j.is_array()))
  912. {
  913. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  914. }
  915. std::transform(j.rbegin(), j.rend(),
  916. std::front_inserter(l), [](const BasicJsonType & i)
  917. {
  918. return i.template get<T>();
  919. });
  920. }
  921. // valarray doesn't have an insert method
  922. template<typename BasicJsonType, typename T,
  923. enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>
  924. void from_json(const BasicJsonType& j, std::valarray<T>& l)
  925. {
  926. if (JSON_UNLIKELY(not j.is_array()))
  927. {
  928. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  929. }
  930. l.resize(j.size());
  931. std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));
  932. }
  933. template<typename BasicJsonType, typename CompatibleArrayType>
  934. void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)
  935. {
  936. using std::end;
  937. std::transform(j.begin(), j.end(),
  938. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  939. {
  940. // get<BasicJsonType>() returns *this, this won't call a from_json
  941. // method when value_type is BasicJsonType
  942. return i.template get<typename CompatibleArrayType::value_type>();
  943. });
  944. }
  945. template<typename BasicJsonType, typename CompatibleArrayType>
  946. auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)
  947. -> decltype(
  948. arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
  949. void())
  950. {
  951. using std::end;
  952. arr.reserve(j.size());
  953. std::transform(j.begin(), j.end(),
  954. std::inserter(arr, end(arr)), [](const BasicJsonType & i)
  955. {
  956. // get<BasicJsonType>() returns *this, this won't call a from_json
  957. // method when value_type is BasicJsonType
  958. return i.template get<typename CompatibleArrayType::value_type>();
  959. });
  960. }
  961. template<typename BasicJsonType, typename T, std::size_t N>
  962. void from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)
  963. {
  964. for (std::size_t i = 0; i < N; ++i)
  965. {
  966. arr[i] = j.at(i).template get<T>();
  967. }
  968. }
  969. template <
  970. typename BasicJsonType, typename CompatibleArrayType,
  971. enable_if_t <
  972. is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
  973. not std::is_same<typename BasicJsonType::array_t,
  974. CompatibleArrayType>::value and
  975. std::is_constructible <
  976. BasicJsonType, typename CompatibleArrayType::value_type >::value,
  977. int > = 0 >
  978. void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
  979. {
  980. if (JSON_UNLIKELY(not j.is_array()))
  981. {
  982. JSON_THROW(type_error::create(302, "type must be array, but is " +
  983. std::string(j.type_name())));
  984. }
  985. from_json_array_impl(j, arr, priority_tag<2> {});
  986. }
  987. template<typename BasicJsonType, typename CompatibleObjectType,
  988. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  989. void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
  990. {
  991. if (JSON_UNLIKELY(not j.is_object()))
  992. {
  993. JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name())));
  994. }
  995. auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
  996. using value_type = typename CompatibleObjectType::value_type;
  997. std::transform(
  998. inner_object->begin(), inner_object->end(),
  999. std::inserter(obj, obj.begin()),
  1000. [](typename BasicJsonType::object_t::value_type const & p)
  1001. {
  1002. return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());
  1003. });
  1004. }
  1005. // overload for arithmetic types, not chosen for basic_json template arguments
  1006. // (BooleanType, etc..); note: Is it really necessary to provide explicit
  1007. // overloads for boolean_t etc. in case of a custom BooleanType which is not
  1008. // an arithmetic type?
  1009. template<typename BasicJsonType, typename ArithmeticType,
  1010. enable_if_t <
  1011. std::is_arithmetic<ArithmeticType>::value and
  1012. not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
  1013. not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
  1014. not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
  1015. not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
  1016. int> = 0>
  1017. void from_json(const BasicJsonType& j, ArithmeticType& val)
  1018. {
  1019. switch (static_cast<value_t>(j))
  1020. {
  1021. case value_t::number_unsigned:
  1022. {
  1023. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
  1024. break;
  1025. }
  1026. case value_t::number_integer:
  1027. {
  1028. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
  1029. break;
  1030. }
  1031. case value_t::number_float:
  1032. {
  1033. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
  1034. break;
  1035. }
  1036. case value_t::boolean:
  1037. {
  1038. val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
  1039. break;
  1040. }
  1041. default:
  1042. JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name())));
  1043. }
  1044. }
  1045. template<typename BasicJsonType, typename A1, typename A2>
  1046. void from_json(const BasicJsonType& j, std::pair<A1, A2>& p)
  1047. {
  1048. p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};
  1049. }
  1050. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1051. void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)
  1052. {
  1053. t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);
  1054. }
  1055. template<typename BasicJsonType, typename... Args>
  1056. void from_json(const BasicJsonType& j, std::tuple<Args...>& t)
  1057. {
  1058. from_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1059. }
  1060. template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
  1061. typename = enable_if_t<not std::is_constructible<
  1062. typename BasicJsonType::string_t, Key>::value>>
  1063. void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
  1064. {
  1065. if (JSON_UNLIKELY(not j.is_array()))
  1066. {
  1067. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1068. }
  1069. for (const auto& p : j)
  1070. {
  1071. if (JSON_UNLIKELY(not p.is_array()))
  1072. {
  1073. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1074. }
  1075. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1076. }
  1077. }
  1078. template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
  1079. typename = enable_if_t<not std::is_constructible<
  1080. typename BasicJsonType::string_t, Key>::value>>
  1081. void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
  1082. {
  1083. if (JSON_UNLIKELY(not j.is_array()))
  1084. {
  1085. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name())));
  1086. }
  1087. for (const auto& p : j)
  1088. {
  1089. if (JSON_UNLIKELY(not p.is_array()))
  1090. {
  1091. JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name())));
  1092. }
  1093. m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
  1094. }
  1095. }
  1096. struct from_json_fn
  1097. {
  1098. private:
  1099. template<typename BasicJsonType, typename T>
  1100. auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const
  1101. noexcept(noexcept(from_json(j, val)))
  1102. -> decltype(from_json(j, val), void())
  1103. {
  1104. return from_json(j, val);
  1105. }
  1106. template<typename BasicJsonType, typename T>
  1107. void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1108. {
  1109. static_assert(sizeof(BasicJsonType) == 0,
  1110. "could not find from_json() method in T's namespace");
  1111. #ifdef _MSC_VER
  1112. // MSVC does not show a stacktrace for the above assert
  1113. using decayed = uncvref_t<T>;
  1114. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1115. "forcing MSVC stacktrace to show which T we're talking about.");
  1116. #endif
  1117. }
  1118. public:
  1119. template<typename BasicJsonType, typename T>
  1120. void operator()(const BasicJsonType& j, T& val) const
  1121. noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
  1122. {
  1123. return call(j, val, priority_tag<1> {});
  1124. }
  1125. };
  1126. }
  1127. /// namespace to hold default `from_json` function
  1128. /// to see why this is required:
  1129. /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
  1130. namespace
  1131. {
  1132. constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
  1133. }
  1134. }
  1135. // #include <nlohmann/detail/conversions/to_json.hpp>
  1136. #include <ciso646> // or, and, not
  1137. #include <iterator> // begin, end
  1138. #include <tuple> // tuple, get
  1139. #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type
  1140. #include <utility> // move, forward, declval, pair
  1141. #include <valarray> // valarray
  1142. #include <vector> // vector
  1143. // #include <nlohmann/detail/meta/cpp_future.hpp>
  1144. // #include <nlohmann/detail/meta/type_traits.hpp>
  1145. // #include <nlohmann/detail/value_t.hpp>
  1146. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  1147. #include <cstddef> // size_t
  1148. #include <string> // string, to_string
  1149. #include <iterator> // input_iterator_tag
  1150. // #include <nlohmann/detail/value_t.hpp>
  1151. namespace nlohmann
  1152. {
  1153. namespace detail
  1154. {
  1155. /// proxy class for the items() function
  1156. template<typename IteratorType> class iteration_proxy
  1157. {
  1158. private:
  1159. /// helper class for iteration
  1160. class iteration_proxy_internal
  1161. {
  1162. public:
  1163. using difference_type = std::ptrdiff_t;
  1164. using value_type = iteration_proxy_internal;
  1165. using pointer = iteration_proxy_internal*;
  1166. using reference = iteration_proxy_internal&;
  1167. using iterator_category = std::input_iterator_tag;
  1168. private:
  1169. /// the iterator
  1170. IteratorType anchor;
  1171. /// an index for arrays (used to create key names)
  1172. std::size_t array_index = 0;
  1173. /// last stringified array index
  1174. mutable std::size_t array_index_last = 0;
  1175. /// a string representation of the array index
  1176. mutable std::string array_index_str = "0";
  1177. /// an empty string (to return a reference for primitive values)
  1178. const std::string empty_str = "";
  1179. public:
  1180. explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}
  1181. iteration_proxy_internal(const iteration_proxy_internal&) = default;
  1182. iteration_proxy_internal& operator=(const iteration_proxy_internal&) = default;
  1183. /// dereference operator (needed for range-based for)
  1184. iteration_proxy_internal& operator*()
  1185. {
  1186. return *this;
  1187. }
  1188. /// increment operator (needed for range-based for)
  1189. iteration_proxy_internal& operator++()
  1190. {
  1191. ++anchor;
  1192. ++array_index;
  1193. return *this;
  1194. }
  1195. /// equality operator (needed for InputIterator)
  1196. bool operator==(const iteration_proxy_internal& o) const noexcept
  1197. {
  1198. return anchor == o.anchor;
  1199. }
  1200. /// inequality operator (needed for range-based for)
  1201. bool operator!=(const iteration_proxy_internal& o) const noexcept
  1202. {
  1203. return anchor != o.anchor;
  1204. }
  1205. /// return key of the iterator
  1206. const std::string& key() const
  1207. {
  1208. assert(anchor.m_object != nullptr);
  1209. switch (anchor.m_object->type())
  1210. {
  1211. // use integer array index as key
  1212. case value_t::array:
  1213. {
  1214. if (array_index != array_index_last)
  1215. {
  1216. array_index_str = std::to_string(array_index);
  1217. array_index_last = array_index;
  1218. }
  1219. return array_index_str;
  1220. }
  1221. // use key from the object
  1222. case value_t::object:
  1223. return anchor.key();
  1224. // use an empty key for all primitive types
  1225. default:
  1226. return empty_str;
  1227. }
  1228. }
  1229. /// return value of the iterator
  1230. typename IteratorType::reference value() const
  1231. {
  1232. return anchor.value();
  1233. }
  1234. };
  1235. /// the container to iterate
  1236. typename IteratorType::reference container;
  1237. public:
  1238. /// construct iteration proxy from a container
  1239. explicit iteration_proxy(typename IteratorType::reference cont) noexcept
  1240. : container(cont) {}
  1241. /// return iterator begin (needed for range-based for)
  1242. iteration_proxy_internal begin() noexcept
  1243. {
  1244. return iteration_proxy_internal(container.begin());
  1245. }
  1246. /// return iterator end (needed for range-based for)
  1247. iteration_proxy_internal end() noexcept
  1248. {
  1249. return iteration_proxy_internal(container.end());
  1250. }
  1251. };
  1252. }
  1253. }
  1254. namespace nlohmann
  1255. {
  1256. namespace detail
  1257. {
  1258. //////////////////
  1259. // constructors //
  1260. //////////////////
  1261. template<value_t> struct external_constructor;
  1262. template<>
  1263. struct external_constructor<value_t::boolean>
  1264. {
  1265. template<typename BasicJsonType>
  1266. static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
  1267. {
  1268. j.m_type = value_t::boolean;
  1269. j.m_value = b;
  1270. j.assert_invariant();
  1271. }
  1272. };
  1273. template<>
  1274. struct external_constructor<value_t::string>
  1275. {
  1276. template<typename BasicJsonType>
  1277. static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
  1278. {
  1279. j.m_type = value_t::string;
  1280. j.m_value = s;
  1281. j.assert_invariant();
  1282. }
  1283. template<typename BasicJsonType>
  1284. static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1285. {
  1286. j.m_type = value_t::string;
  1287. j.m_value = std::move(s);
  1288. j.assert_invariant();
  1289. }
  1290. template<typename BasicJsonType, typename CompatibleStringType,
  1291. enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value,
  1292. int> = 0>
  1293. static void construct(BasicJsonType& j, const CompatibleStringType& str)
  1294. {
  1295. j.m_type = value_t::string;
  1296. j.m_value.string = j.template create<typename BasicJsonType::string_t>(str);
  1297. j.assert_invariant();
  1298. }
  1299. };
  1300. template<>
  1301. struct external_constructor<value_t::number_float>
  1302. {
  1303. template<typename BasicJsonType>
  1304. static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
  1305. {
  1306. j.m_type = value_t::number_float;
  1307. j.m_value = val;
  1308. j.assert_invariant();
  1309. }
  1310. };
  1311. template<>
  1312. struct external_constructor<value_t::number_unsigned>
  1313. {
  1314. template<typename BasicJsonType>
  1315. static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
  1316. {
  1317. j.m_type = value_t::number_unsigned;
  1318. j.m_value = val;
  1319. j.assert_invariant();
  1320. }
  1321. };
  1322. template<>
  1323. struct external_constructor<value_t::number_integer>
  1324. {
  1325. template<typename BasicJsonType>
  1326. static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
  1327. {
  1328. j.m_type = value_t::number_integer;
  1329. j.m_value = val;
  1330. j.assert_invariant();
  1331. }
  1332. };
  1333. template<>
  1334. struct external_constructor<value_t::array>
  1335. {
  1336. template<typename BasicJsonType>
  1337. static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
  1338. {
  1339. j.m_type = value_t::array;
  1340. j.m_value = arr;
  1341. j.assert_invariant();
  1342. }
  1343. template<typename BasicJsonType>
  1344. static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1345. {
  1346. j.m_type = value_t::array;
  1347. j.m_value = std::move(arr);
  1348. j.assert_invariant();
  1349. }
  1350. template<typename BasicJsonType, typename CompatibleArrayType,
  1351. enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,
  1352. int> = 0>
  1353. static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
  1354. {
  1355. using std::begin;
  1356. using std::end;
  1357. j.m_type = value_t::array;
  1358. j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
  1359. j.assert_invariant();
  1360. }
  1361. template<typename BasicJsonType>
  1362. static void construct(BasicJsonType& j, const std::vector<bool>& arr)
  1363. {
  1364. j.m_type = value_t::array;
  1365. j.m_value = value_t::array;
  1366. j.m_value.array->reserve(arr.size());
  1367. for (const bool x : arr)
  1368. {
  1369. j.m_value.array->push_back(x);
  1370. }
  1371. j.assert_invariant();
  1372. }
  1373. template<typename BasicJsonType, typename T,
  1374. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1375. static void construct(BasicJsonType& j, const std::valarray<T>& arr)
  1376. {
  1377. j.m_type = value_t::array;
  1378. j.m_value = value_t::array;
  1379. j.m_value.array->resize(arr.size());
  1380. std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());
  1381. j.assert_invariant();
  1382. }
  1383. };
  1384. template<>
  1385. struct external_constructor<value_t::object>
  1386. {
  1387. template<typename BasicJsonType>
  1388. static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
  1389. {
  1390. j.m_type = value_t::object;
  1391. j.m_value = obj;
  1392. j.assert_invariant();
  1393. }
  1394. template<typename BasicJsonType>
  1395. static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1396. {
  1397. j.m_type = value_t::object;
  1398. j.m_value = std::move(obj);
  1399. j.assert_invariant();
  1400. }
  1401. template<typename BasicJsonType, typename CompatibleObjectType,
  1402. enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>
  1403. static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
  1404. {
  1405. using std::begin;
  1406. using std::end;
  1407. j.m_type = value_t::object;
  1408. j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
  1409. j.assert_invariant();
  1410. }
  1411. };
  1412. /////////////
  1413. // to_json //
  1414. /////////////
  1415. template<typename BasicJsonType, typename T,
  1416. enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
  1417. void to_json(BasicJsonType& j, T b) noexcept
  1418. {
  1419. external_constructor<value_t::boolean>::construct(j, b);
  1420. }
  1421. template<typename BasicJsonType, typename CompatibleString,
  1422. enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>
  1423. void to_json(BasicJsonType& j, const CompatibleString& s)
  1424. {
  1425. external_constructor<value_t::string>::construct(j, s);
  1426. }
  1427. template<typename BasicJsonType>
  1428. void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)
  1429. {
  1430. external_constructor<value_t::string>::construct(j, std::move(s));
  1431. }
  1432. template<typename BasicJsonType, typename FloatType,
  1433. enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
  1434. void to_json(BasicJsonType& j, FloatType val) noexcept
  1435. {
  1436. external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
  1437. }
  1438. template<typename BasicJsonType, typename CompatibleNumberUnsignedType,
  1439. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>
  1440. void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
  1441. {
  1442. external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
  1443. }
  1444. template<typename BasicJsonType, typename CompatibleNumberIntegerType,
  1445. enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>
  1446. void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
  1447. {
  1448. external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
  1449. }
  1450. template<typename BasicJsonType, typename EnumType,
  1451. enable_if_t<std::is_enum<EnumType>::value, int> = 0>
  1452. void to_json(BasicJsonType& j, EnumType e) noexcept
  1453. {
  1454. using underlying_type = typename std::underlying_type<EnumType>::type;
  1455. external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));
  1456. }
  1457. template<typename BasicJsonType>
  1458. void to_json(BasicJsonType& j, const std::vector<bool>& e)
  1459. {
  1460. external_constructor<value_t::array>::construct(j, e);
  1461. }
  1462. template<typename BasicJsonType, typename CompatibleArrayType,
  1463. enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
  1464. std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
  1465. int> = 0>
  1466. void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
  1467. {
  1468. external_constructor<value_t::array>::construct(j, arr);
  1469. }
  1470. template<typename BasicJsonType, typename T,
  1471. enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>
  1472. void to_json(BasicJsonType& j, const std::valarray<T>& arr)
  1473. {
  1474. external_constructor<value_t::array>::construct(j, std::move(arr));
  1475. }
  1476. template<typename BasicJsonType>
  1477. void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)
  1478. {
  1479. external_constructor<value_t::array>::construct(j, std::move(arr));
  1480. }
  1481. template<typename BasicJsonType, typename CompatibleObjectType,
  1482. enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
  1483. void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
  1484. {
  1485. external_constructor<value_t::object>::construct(j, obj);
  1486. }
  1487. template<typename BasicJsonType>
  1488. void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
  1489. {
  1490. external_constructor<value_t::object>::construct(j, std::move(obj));
  1491. }
  1492. template<typename BasicJsonType, typename T, std::size_t N,
  1493. enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>
  1494. void to_json(BasicJsonType& j, T (&arr)[N])
  1495. {
  1496. external_constructor<value_t::array>::construct(j, arr);
  1497. }
  1498. template<typename BasicJsonType, typename... Args>
  1499. void to_json(BasicJsonType& j, const std::pair<Args...>& p)
  1500. {
  1501. j = {p.first, p.second};
  1502. }
  1503. // for https://github.com/nlohmann/json/pull/1134
  1504. template<typename BasicJsonType, typename T,
  1505. enable_if_t<std::is_same<T, typename iteration_proxy<typename BasicJsonType::iterator>::iteration_proxy_internal>::value, int> = 0>
  1506. void to_json(BasicJsonType& j, T b) noexcept
  1507. {
  1508. j = {{b.key(), b.value()}};
  1509. }
  1510. template<typename BasicJsonType, typename Tuple, std::size_t... Idx>
  1511. void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)
  1512. {
  1513. j = {std::get<Idx>(t)...};
  1514. }
  1515. template<typename BasicJsonType, typename... Args>
  1516. void to_json(BasicJsonType& j, const std::tuple<Args...>& t)
  1517. {
  1518. to_json_tuple_impl(j, t, index_sequence_for<Args...> {});
  1519. }
  1520. struct to_json_fn
  1521. {
  1522. private:
  1523. template<typename BasicJsonType, typename T>
  1524. auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
  1525. -> decltype(to_json(j, std::forward<T>(val)), void())
  1526. {
  1527. return to_json(j, std::forward<T>(val));
  1528. }
  1529. template<typename BasicJsonType, typename T>
  1530. void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept
  1531. {
  1532. static_assert(sizeof(BasicJsonType) == 0,
  1533. "could not find to_json() method in T's namespace");
  1534. #ifdef _MSC_VER
  1535. // MSVC does not show a stacktrace for the above assert
  1536. using decayed = uncvref_t<T>;
  1537. static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,
  1538. "forcing MSVC stacktrace to show which T we're talking about.");
  1539. #endif
  1540. }
  1541. public:
  1542. template<typename BasicJsonType, typename T>
  1543. void operator()(BasicJsonType& j, T&& val) const
  1544. noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
  1545. {
  1546. return call(j, std::forward<T>(val), priority_tag<1> {});
  1547. }
  1548. };
  1549. }
  1550. /// namespace to hold default `to_json` function
  1551. namespace
  1552. {
  1553. constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
  1554. }
  1555. }
  1556. // #include <nlohmann/detail/input/input_adapters.hpp>
  1557. #include <cassert> // assert
  1558. #include <cstddef> // size_t
  1559. #include <cstring> // strlen
  1560. #include <istream> // istream
  1561. #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next
  1562. #include <memory> // shared_ptr, make_shared, addressof
  1563. #include <numeric> // accumulate
  1564. #include <string> // string, char_traits
  1565. #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer
  1566. #include <utility> // pair, declval
  1567. // #include <nlohmann/detail/macro_scope.hpp>
  1568. namespace nlohmann
  1569. {
  1570. namespace detail
  1571. {
  1572. /// the supported input formats
  1573. enum class input_format_t { json, cbor, msgpack, ubjson };
  1574. ////////////////////
  1575. // input adapters //
  1576. ////////////////////
  1577. /*!
  1578. @brief abstract input adapter interface
  1579. Produces a stream of std::char_traits<char>::int_type characters from a
  1580. std::istream, a buffer, or some other input type. Accepts the return of
  1581. exactly one non-EOF character for future input. The int_type characters
  1582. returned consist of all valid char values as positive values (typically
  1583. unsigned char), plus an EOF value outside that range, specified by the value
  1584. of the function std::char_traits<char>::eof(). This value is typically -1, but
  1585. could be any arbitrary value which is not a valid char value.
  1586. */
  1587. struct input_adapter_protocol
  1588. {
  1589. /// get a character [0,255] or std::char_traits<char>::eof().
  1590. virtual std::char_traits<char>::int_type get_character() = 0;
  1591. virtual ~input_adapter_protocol() = default;
  1592. };
  1593. /// a type to simplify interfaces
  1594. using input_adapter_t = std::shared_ptr<input_adapter_protocol>;
  1595. /*!
  1596. Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at
  1597. beginning of input. Does not support changing the underlying std::streambuf
  1598. in mid-input. Maintains underlying std::istream and std::streambuf to support
  1599. subsequent use of standard std::istream operations to process any input
  1600. characters following those used in parsing the JSON input. Clears the
  1601. std::istream flags; any input errors (e.g., EOF) will be detected by the first
  1602. subsequent call for input from the std::istream.
  1603. */
  1604. class input_stream_adapter : public input_adapter_protocol
  1605. {
  1606. public:
  1607. ~input_stream_adapter() override
  1608. {
  1609. // clear stream flags; we use underlying streambuf I/O, do not
  1610. // maintain ifstream flags
  1611. is.clear();
  1612. }
  1613. explicit input_stream_adapter(std::istream& i)
  1614. : is(i), sb(*i.rdbuf())
  1615. {}
  1616. // delete because of pointer members
  1617. input_stream_adapter(const input_stream_adapter&) = delete;
  1618. input_stream_adapter& operator=(input_stream_adapter&) = delete;
  1619. // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to
  1620. // ensure that std::char_traits<char>::eof() and the character 0xFF do not
  1621. // end up as the same value, eg. 0xFFFFFFFF.
  1622. std::char_traits<char>::int_type get_character() override
  1623. {
  1624. return sb.sbumpc();
  1625. }
  1626. private:
  1627. /// the associated input stream
  1628. std::istream& is;
  1629. std::streambuf& sb;
  1630. };
  1631. /// input adapter for buffer input
  1632. class input_buffer_adapter : public input_adapter_protocol
  1633. {
  1634. public:
  1635. input_buffer_adapter(const char* b, const std::size_t l)
  1636. : cursor(b), limit(b + l)
  1637. {}
  1638. // delete because of pointer members
  1639. input_buffer_adapter(const input_buffer_adapter&) = delete;
  1640. input_buffer_adapter& operator=(input_buffer_adapter&) = delete;
  1641. std::char_traits<char>::int_type get_character() noexcept override
  1642. {
  1643. if (JSON_LIKELY(cursor < limit))
  1644. {
  1645. return std::char_traits<char>::to_int_type(*(cursor++));
  1646. }
  1647. return std::char_traits<char>::eof();
  1648. }
  1649. private:
  1650. /// pointer to the current character
  1651. const char* cursor;
  1652. /// pointer past the last character
  1653. const char* const limit;
  1654. };
  1655. template<typename WideStringType>
  1656. class wide_string_input_adapter : public input_adapter_protocol
  1657. {
  1658. public:
  1659. explicit wide_string_input_adapter(const WideStringType& w) : str(w) {}
  1660. std::char_traits<char>::int_type get_character() noexcept override
  1661. {
  1662. // check if buffer needs to be filled
  1663. if (utf8_bytes_index == utf8_bytes_filled)
  1664. {
  1665. if (sizeof(typename WideStringType::value_type) == 2)
  1666. {
  1667. fill_buffer_utf16();
  1668. }
  1669. else
  1670. {
  1671. fill_buffer_utf32();
  1672. }
  1673. assert(utf8_bytes_filled > 0);
  1674. assert(utf8_bytes_index == 0);
  1675. }
  1676. // use buffer
  1677. assert(utf8_bytes_filled > 0);
  1678. assert(utf8_bytes_index < utf8_bytes_filled);
  1679. return utf8_bytes[utf8_bytes_index++];
  1680. }
  1681. private:
  1682. void fill_buffer_utf16()
  1683. {
  1684. utf8_bytes_index = 0;
  1685. if (current_wchar == str.size())
  1686. {
  1687. utf8_bytes[0] = std::char_traits<char>::eof();
  1688. utf8_bytes_filled = 1;
  1689. }
  1690. else
  1691. {
  1692. // get the current character
  1693. const int wc = static_cast<int>(str[current_wchar++]);
  1694. // UTF-16 to UTF-8 encoding
  1695. if (wc < 0x80)
  1696. {
  1697. utf8_bytes[0] = wc;
  1698. utf8_bytes_filled = 1;
  1699. }
  1700. else if (wc <= 0x7FF)
  1701. {
  1702. utf8_bytes[0] = 0xC0 | ((wc >> 6));
  1703. utf8_bytes[1] = 0x80 | (wc & 0x3F);
  1704. utf8_bytes_filled = 2;
  1705. }
  1706. else if (0xD800 > wc or wc >= 0xE000)
  1707. {
  1708. utf8_bytes[0] = 0xE0 | ((wc >> 12));
  1709. utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
  1710. utf8_bytes[2] = 0x80 | (wc & 0x3F);
  1711. utf8_bytes_filled = 3;
  1712. }
  1713. else
  1714. {
  1715. if (current_wchar < str.size())
  1716. {
  1717. const int wc2 = static_cast<int>(str[current_wchar++]);
  1718. const int charcode = 0x10000 + (((wc & 0x3FF) << 10) | (wc2 & 0x3FF));
  1719. utf8_bytes[0] = 0xf0 | (charcode >> 18);
  1720. utf8_bytes[1] = 0x80 | ((charcode >> 12) & 0x3F);
  1721. utf8_bytes[2] = 0x80 | ((charcode >> 6) & 0x3F);
  1722. utf8_bytes[3] = 0x80 | (charcode & 0x3F);
  1723. utf8_bytes_filled = 4;
  1724. }
  1725. else
  1726. {
  1727. // unknown character
  1728. ++current_wchar;
  1729. utf8_bytes[0] = wc;
  1730. utf8_bytes_filled = 1;
  1731. }
  1732. }
  1733. }
  1734. }
  1735. void fill_buffer_utf32()
  1736. {
  1737. utf8_bytes_index = 0;
  1738. if (current_wchar == str.size())
  1739. {
  1740. utf8_bytes[0] = std::char_traits<char>::eof();
  1741. utf8_bytes_filled = 1;
  1742. }
  1743. else
  1744. {
  1745. // get the current character
  1746. const int wc = static_cast<int>(str[current_wchar++]);
  1747. // UTF-32 to UTF-8 encoding
  1748. if (wc < 0x80)
  1749. {
  1750. utf8_bytes[0] = wc;
  1751. utf8_bytes_filled = 1;
  1752. }
  1753. else if (wc <= 0x7FF)
  1754. {
  1755. utf8_bytes[0] = 0xC0 | ((wc >> 6) & 0x1F);
  1756. utf8_bytes[1] = 0x80 | (wc & 0x3F);
  1757. utf8_bytes_filled = 2;
  1758. }
  1759. else if (wc <= 0xFFFF)
  1760. {
  1761. utf8_bytes[0] = 0xE0 | ((wc >> 12) & 0x0F);
  1762. utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F);
  1763. utf8_bytes[2] = 0x80 | (wc & 0x3F);
  1764. utf8_bytes_filled = 3;
  1765. }
  1766. else if (wc <= 0x10FFFF)
  1767. {
  1768. utf8_bytes[0] = 0xF0 | ((wc >> 18 ) & 0x07);
  1769. utf8_bytes[1] = 0x80 | ((wc >> 12) & 0x3F);
  1770. utf8_bytes[2] = 0x80 | ((wc >> 6) & 0x3F);
  1771. utf8_bytes[3] = 0x80 | (wc & 0x3F);
  1772. utf8_bytes_filled = 4;
  1773. }
  1774. else
  1775. {
  1776. // unknown character
  1777. utf8_bytes[0] = wc;
  1778. utf8_bytes_filled = 1;
  1779. }
  1780. }
  1781. }
  1782. private:
  1783. /// the wstring to process
  1784. const WideStringType& str;
  1785. /// index of the current wchar in str
  1786. std::size_t current_wchar = 0;
  1787. /// a buffer for UTF-8 bytes
  1788. std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}};
  1789. /// index to the utf8_codes array for the next valid byte
  1790. std::size_t utf8_bytes_index = 0;
  1791. /// number of valid bytes in the utf8_codes array
  1792. std::size_t utf8_bytes_filled = 0;
  1793. };
  1794. class input_adapter
  1795. {
  1796. public:
  1797. // native support
  1798. /// input adapter for input stream
  1799. input_adapter(std::istream& i)
  1800. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1801. /// input adapter for input stream
  1802. input_adapter(std::istream&& i)
  1803. : ia(std::make_shared<input_stream_adapter>(i)) {}
  1804. input_adapter(const std::wstring& ws)
  1805. : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {}
  1806. input_adapter(const std::u16string& ws)
  1807. : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {}
  1808. input_adapter(const std::u32string& ws)
  1809. : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {}
  1810. /// input adapter for buffer
  1811. template<typename CharT,
  1812. typename std::enable_if<
  1813. std::is_pointer<CharT>::value and
  1814. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1815. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1816. int>::type = 0>
  1817. input_adapter(CharT b, std::size_t l)
  1818. : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}
  1819. // derived support
  1820. /// input adapter for string literal
  1821. template<typename CharT,
  1822. typename std::enable_if<
  1823. std::is_pointer<CharT>::value and
  1824. std::is_integral<typename std::remove_pointer<CharT>::type>::value and
  1825. sizeof(typename std::remove_pointer<CharT>::type) == 1,
  1826. int>::type = 0>
  1827. input_adapter(CharT b)
  1828. : input_adapter(reinterpret_cast<const char*>(b),
  1829. std::strlen(reinterpret_cast<const char*>(b))) {}
  1830. /// input adapter for iterator range with contiguous storage
  1831. template<class IteratorType,
  1832. typename std::enable_if<
  1833. std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,
  1834. int>::type = 0>
  1835. input_adapter(IteratorType first, IteratorType last)
  1836. {
  1837. // assertion to check that the iterator range is indeed contiguous,
  1838. // see http://stackoverflow.com/a/35008842/266378 for more discussion
  1839. assert(std::accumulate(
  1840. first, last, std::pair<bool, int>(true, 0),
  1841. [&first](std::pair<bool, int> res, decltype(*first) val)
  1842. {
  1843. res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
  1844. return res;
  1845. }).first);
  1846. // assertion to check that each element is 1 byte long
  1847. static_assert(
  1848. sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
  1849. "each element in the iterator range must have the size of 1 byte");
  1850. const auto len = static_cast<size_t>(std::distance(first, last));
  1851. if (JSON_LIKELY(len > 0))
  1852. {
  1853. // there is at least one element: use the address of first
  1854. ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);
  1855. }
  1856. else
  1857. {
  1858. // the address of first cannot be used: use nullptr
  1859. ia = std::make_shared<input_buffer_adapter>(nullptr, len);
  1860. }
  1861. }
  1862. /// input adapter for array
  1863. template<class T, std::size_t N>
  1864. input_adapter(T (&array)[N])
  1865. : input_adapter(std::begin(array), std::end(array)) {}
  1866. /// input adapter for contiguous container
  1867. template<class ContiguousContainer, typename
  1868. std::enable_if<not std::is_pointer<ContiguousContainer>::value and
  1869. std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,
  1870. int>::type = 0>
  1871. input_adapter(const ContiguousContainer& c)
  1872. : input_adapter(std::begin(c), std::end(c)) {}
  1873. operator input_adapter_t()
  1874. {
  1875. return ia;
  1876. }
  1877. private:
  1878. /// the actual adapter
  1879. input_adapter_t ia = nullptr;
  1880. };
  1881. }
  1882. }
  1883. // #include <nlohmann/detail/input/lexer.hpp>
  1884. #include <clocale> // localeconv
  1885. #include <cstddef> // size_t
  1886. #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull
  1887. #include <cstdio> // snprintf
  1888. #include <initializer_list> // initializer_list
  1889. #include <string> // char_traits, string
  1890. #include <vector> // vector
  1891. // #include <nlohmann/detail/macro_scope.hpp>
  1892. // #include <nlohmann/detail/input/input_adapters.hpp>
  1893. namespace nlohmann
  1894. {
  1895. namespace detail
  1896. {
  1897. ///////////
  1898. // lexer //
  1899. ///////////
  1900. /*!
  1901. @brief lexical analysis
  1902. This class organizes the lexical analysis during JSON deserialization.
  1903. */
  1904. template<typename BasicJsonType>
  1905. class lexer
  1906. {
  1907. using number_integer_t = typename BasicJsonType::number_integer_t;
  1908. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  1909. using number_float_t = typename BasicJsonType::number_float_t;
  1910. using string_t = typename BasicJsonType::string_t;
  1911. public:
  1912. /// token types for the parser
  1913. enum class token_type
  1914. {
  1915. uninitialized, ///< indicating the scanner is uninitialized
  1916. literal_true, ///< the `true` literal
  1917. literal_false, ///< the `false` literal
  1918. literal_null, ///< the `null` literal
  1919. value_string, ///< a string -- use get_string() for actual value
  1920. value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value
  1921. value_integer, ///< a signed integer -- use get_number_integer() for actual value
  1922. value_float, ///< an floating point number -- use get_number_float() for actual value
  1923. begin_array, ///< the character for array begin `[`
  1924. begin_object, ///< the character for object begin `{`
  1925. end_array, ///< the character for array end `]`
  1926. end_object, ///< the character for object end `}`
  1927. name_separator, ///< the name separator `:`
  1928. value_separator, ///< the value separator `,`
  1929. parse_error, ///< indicating a parse error
  1930. end_of_input, ///< indicating the end of the input buffer
  1931. literal_or_value ///< a literal or the begin of a value (only for diagnostics)
  1932. };
  1933. /// return name of values of type token_type (only used for errors)
  1934. static const char* token_type_name(const token_type t) noexcept
  1935. {
  1936. switch (t)
  1937. {
  1938. case token_type::uninitialized:
  1939. return "<uninitialized>";
  1940. case token_type::literal_true:
  1941. return "true literal";
  1942. case token_type::literal_false:
  1943. return "false literal";
  1944. case token_type::literal_null:
  1945. return "null literal";
  1946. case token_type::value_string:
  1947. return "string literal";
  1948. case lexer::token_type::value_unsigned:
  1949. case lexer::token_type::value_integer:
  1950. case lexer::token_type::value_float:
  1951. return "number literal";
  1952. case token_type::begin_array:
  1953. return "'['";
  1954. case token_type::begin_object:
  1955. return "'{'";
  1956. case token_type::end_array:
  1957. return "']'";
  1958. case token_type::end_object:
  1959. return "'}'";
  1960. case token_type::name_separator:
  1961. return "':'";
  1962. case token_type::value_separator:
  1963. return "','";
  1964. case token_type::parse_error:
  1965. return "<parse error>";
  1966. case token_type::end_of_input:
  1967. return "end of input";
  1968. case token_type::literal_or_value:
  1969. return "'[', '{', or a literal";
  1970. // LCOV_EXCL_START
  1971. default: // catch non-enum values
  1972. return "unknown token";
  1973. // LCOV_EXCL_STOP
  1974. }
  1975. }
  1976. explicit lexer(detail::input_adapter_t&& adapter)
  1977. : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}
  1978. // delete because of pointer members
  1979. lexer(const lexer&) = delete;
  1980. lexer& operator=(lexer&) = delete;
  1981. private:
  1982. /////////////////////
  1983. // locales
  1984. /////////////////////
  1985. /// return the locale-dependent decimal point
  1986. static char get_decimal_point() noexcept
  1987. {
  1988. const auto loc = localeconv();
  1989. assert(loc != nullptr);
  1990. return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);
  1991. }
  1992. /////////////////////
  1993. // scan functions
  1994. /////////////////////
  1995. /*!
  1996. @brief get codepoint from 4 hex characters following `\u`
  1997. For input "\u c1 c2 c3 c4" the codepoint is:
  1998. (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4
  1999. = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)
  2000. Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'
  2001. must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The
  2002. conversion is done by subtracting the offset (0x30, 0x37, and 0x57)
  2003. between the ASCII value of the character and the desired integer value.
  2004. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or
  2005. non-hex character)
  2006. */
  2007. int get_codepoint()
  2008. {
  2009. // this function only makes sense after reading `\u`
  2010. assert(current == 'u');
  2011. int codepoint = 0;
  2012. const auto factors = { 12, 8, 4, 0 };
  2013. for (const auto factor : factors)
  2014. {
  2015. get();
  2016. if (current >= '0' and current <= '9')
  2017. {
  2018. codepoint += ((current - 0x30) << factor);
  2019. }
  2020. else if (current >= 'A' and current <= 'F')
  2021. {
  2022. codepoint += ((current - 0x37) << factor);
  2023. }
  2024. else if (current >= 'a' and current <= 'f')
  2025. {
  2026. codepoint += ((current - 0x57) << factor);
  2027. }
  2028. else
  2029. {
  2030. return -1;
  2031. }
  2032. }
  2033. assert(0x0000 <= codepoint and codepoint <= 0xFFFF);
  2034. return codepoint;
  2035. }
  2036. /*!
  2037. @brief check if the next byte(s) are inside a given range
  2038. Adds the current byte and, for each passed range, reads a new byte and
  2039. checks if it is inside the range. If a violation was detected, set up an
  2040. error message and return false. Otherwise, return true.
  2041. @param[in] ranges list of integers; interpreted as list of pairs of
  2042. inclusive lower and upper bound, respectively
  2043. @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,
  2044. 1, 2, or 3 pairs. This precondition is enforced by an assertion.
  2045. @return true if and only if no range violation was detected
  2046. */
  2047. bool next_byte_in_range(std::initializer_list<int> ranges)
  2048. {
  2049. assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);
  2050. add(current);
  2051. for (auto range = ranges.begin(); range != ranges.end(); ++range)
  2052. {
  2053. get();
  2054. if (JSON_LIKELY(*range <= current and current <= *(++range)))
  2055. {
  2056. add(current);
  2057. }
  2058. else
  2059. {
  2060. error_message = "invalid string: ill-formed UTF-8 byte";
  2061. return false;
  2062. }
  2063. }
  2064. return true;
  2065. }
  2066. /*!
  2067. @brief scan a string literal
  2068. This function scans a string according to Sect. 7 of RFC 7159. While
  2069. scanning, bytes are escaped and copied into buffer token_buffer. Then the
  2070. function returns successfully, token_buffer is *not* null-terminated (as it
  2071. may contain \0 bytes), and token_buffer.size() is the number of bytes in the
  2072. string.
  2073. @return token_type::value_string if string could be successfully scanned,
  2074. token_type::parse_error otherwise
  2075. @note In case of errors, variable error_message contains a textual
  2076. description.
  2077. */
  2078. token_type scan_string()
  2079. {
  2080. // reset token_buffer (ignore opening quote)
  2081. reset();
  2082. // we entered the function by reading an open quote
  2083. assert(current == '\"');
  2084. while (true)
  2085. {
  2086. // get next character
  2087. switch (get())
  2088. {
  2089. // end of file while parsing string
  2090. case std::char_traits<char>::eof():
  2091. {
  2092. error_message = "invalid string: missing closing quote";
  2093. return token_type::parse_error;
  2094. }
  2095. // closing quote
  2096. case '\"':
  2097. {
  2098. return token_type::value_string;
  2099. }
  2100. // escapes
  2101. case '\\':
  2102. {
  2103. switch (get())
  2104. {
  2105. // quotation mark
  2106. case '\"':
  2107. add('\"');
  2108. break;
  2109. // reverse solidus
  2110. case '\\':
  2111. add('\\');
  2112. break;
  2113. // solidus
  2114. case '/':
  2115. add('/');
  2116. break;
  2117. // backspace
  2118. case 'b':
  2119. add('\b');
  2120. break;
  2121. // form feed
  2122. case 'f':
  2123. add('\f');
  2124. break;
  2125. // line feed
  2126. case 'n':
  2127. add('\n');
  2128. break;
  2129. // carriage return
  2130. case 'r':
  2131. add('\r');
  2132. break;
  2133. // tab
  2134. case 't':
  2135. add('\t');
  2136. break;
  2137. // unicode escapes
  2138. case 'u':
  2139. {
  2140. const int codepoint1 = get_codepoint();
  2141. int codepoint = codepoint1; // start with codepoint1
  2142. if (JSON_UNLIKELY(codepoint1 == -1))
  2143. {
  2144. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  2145. return token_type::parse_error;
  2146. }
  2147. // check if code point is a high surrogate
  2148. if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)
  2149. {
  2150. // expect next \uxxxx entry
  2151. if (JSON_LIKELY(get() == '\\' and get() == 'u'))
  2152. {
  2153. const int codepoint2 = get_codepoint();
  2154. if (JSON_UNLIKELY(codepoint2 == -1))
  2155. {
  2156. error_message = "invalid string: '\\u' must be followed by 4 hex digits";
  2157. return token_type::parse_error;
  2158. }
  2159. // check if codepoint2 is a low surrogate
  2160. if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))
  2161. {
  2162. // overwrite codepoint
  2163. codepoint =
  2164. // high surrogate occupies the most significant 22 bits
  2165. (codepoint1 << 10)
  2166. // low surrogate occupies the least significant 15 bits
  2167. + codepoint2
  2168. // there is still the 0xD800, 0xDC00 and 0x10000 noise
  2169. // in the result so we have to subtract with:
  2170. // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
  2171. - 0x35FDC00;
  2172. }
  2173. else
  2174. {
  2175. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  2176. return token_type::parse_error;
  2177. }
  2178. }
  2179. else
  2180. {
  2181. error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF";
  2182. return token_type::parse_error;
  2183. }
  2184. }
  2185. else
  2186. {
  2187. if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))
  2188. {
  2189. error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF";
  2190. return token_type::parse_error;
  2191. }
  2192. }
  2193. // result of the above calculation yields a proper codepoint
  2194. assert(0x00 <= codepoint and codepoint <= 0x10FFFF);
  2195. // translate codepoint into bytes
  2196. if (codepoint < 0x80)
  2197. {
  2198. // 1-byte characters: 0xxxxxxx (ASCII)
  2199. add(codepoint);
  2200. }
  2201. else if (codepoint <= 0x7FF)
  2202. {
  2203. // 2-byte characters: 110xxxxx 10xxxxxx
  2204. add(0xC0 | (codepoint >> 6));
  2205. add(0x80 | (codepoint & 0x3F));
  2206. }
  2207. else if (codepoint <= 0xFFFF)
  2208. {
  2209. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  2210. add(0xE0 | (codepoint >> 12));
  2211. add(0x80 | ((codepoint >> 6) & 0x3F));
  2212. add(0x80 | (codepoint & 0x3F));
  2213. }
  2214. else
  2215. {
  2216. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2217. add(0xF0 | (codepoint >> 18));
  2218. add(0x80 | ((codepoint >> 12) & 0x3F));
  2219. add(0x80 | ((codepoint >> 6) & 0x3F));
  2220. add(0x80 | (codepoint & 0x3F));
  2221. }
  2222. break;
  2223. }
  2224. // other characters after escape
  2225. default:
  2226. error_message = "invalid string: forbidden character after backslash";
  2227. return token_type::parse_error;
  2228. }
  2229. break;
  2230. }
  2231. // invalid control characters
  2232. case 0x00:
  2233. case 0x01:
  2234. case 0x02:
  2235. case 0x03:
  2236. case 0x04:
  2237. case 0x05:
  2238. case 0x06:
  2239. case 0x07:
  2240. case 0x08:
  2241. case 0x09:
  2242. case 0x0A:
  2243. case 0x0B:
  2244. case 0x0C:
  2245. case 0x0D:
  2246. case 0x0E:
  2247. case 0x0F:
  2248. case 0x10:
  2249. case 0x11:
  2250. case 0x12:
  2251. case 0x13:
  2252. case 0x14:
  2253. case 0x15:
  2254. case 0x16:
  2255. case 0x17:
  2256. case 0x18:
  2257. case 0x19:
  2258. case 0x1A:
  2259. case 0x1B:
  2260. case 0x1C:
  2261. case 0x1D:
  2262. case 0x1E:
  2263. case 0x1F:
  2264. {
  2265. error_message = "invalid string: control character must be escaped";
  2266. return token_type::parse_error;
  2267. }
  2268. // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))
  2269. case 0x20:
  2270. case 0x21:
  2271. case 0x23:
  2272. case 0x24:
  2273. case 0x25:
  2274. case 0x26:
  2275. case 0x27:
  2276. case 0x28:
  2277. case 0x29:
  2278. case 0x2A:
  2279. case 0x2B:
  2280. case 0x2C:
  2281. case 0x2D:
  2282. case 0x2E:
  2283. case 0x2F:
  2284. case 0x30:
  2285. case 0x31:
  2286. case 0x32:
  2287. case 0x33:
  2288. case 0x34:
  2289. case 0x35:
  2290. case 0x36:
  2291. case 0x37:
  2292. case 0x38:
  2293. case 0x39:
  2294. case 0x3A:
  2295. case 0x3B:
  2296. case 0x3C:
  2297. case 0x3D:
  2298. case 0x3E:
  2299. case 0x3F:
  2300. case 0x40:
  2301. case 0x41:
  2302. case 0x42:
  2303. case 0x43:
  2304. case 0x44:
  2305. case 0x45:
  2306. case 0x46:
  2307. case 0x47:
  2308. case 0x48:
  2309. case 0x49:
  2310. case 0x4A:
  2311. case 0x4B:
  2312. case 0x4C:
  2313. case 0x4D:
  2314. case 0x4E:
  2315. case 0x4F:
  2316. case 0x50:
  2317. case 0x51:
  2318. case 0x52:
  2319. case 0x53:
  2320. case 0x54:
  2321. case 0x55:
  2322. case 0x56:
  2323. case 0x57:
  2324. case 0x58:
  2325. case 0x59:
  2326. case 0x5A:
  2327. case 0x5B:
  2328. case 0x5D:
  2329. case 0x5E:
  2330. case 0x5F:
  2331. case 0x60:
  2332. case 0x61:
  2333. case 0x62:
  2334. case 0x63:
  2335. case 0x64:
  2336. case 0x65:
  2337. case 0x66:
  2338. case 0x67:
  2339. case 0x68:
  2340. case 0x69:
  2341. case 0x6A:
  2342. case 0x6B:
  2343. case 0x6C:
  2344. case 0x6D:
  2345. case 0x6E:
  2346. case 0x6F:
  2347. case 0x70:
  2348. case 0x71:
  2349. case 0x72:
  2350. case 0x73:
  2351. case 0x74:
  2352. case 0x75:
  2353. case 0x76:
  2354. case 0x77:
  2355. case 0x78:
  2356. case 0x79:
  2357. case 0x7A:
  2358. case 0x7B:
  2359. case 0x7C:
  2360. case 0x7D:
  2361. case 0x7E:
  2362. case 0x7F:
  2363. {
  2364. add(current);
  2365. break;
  2366. }
  2367. // U+0080..U+07FF: bytes C2..DF 80..BF
  2368. case 0xC2:
  2369. case 0xC3:
  2370. case 0xC4:
  2371. case 0xC5:
  2372. case 0xC6:
  2373. case 0xC7:
  2374. case 0xC8:
  2375. case 0xC9:
  2376. case 0xCA:
  2377. case 0xCB:
  2378. case 0xCC:
  2379. case 0xCD:
  2380. case 0xCE:
  2381. case 0xCF:
  2382. case 0xD0:
  2383. case 0xD1:
  2384. case 0xD2:
  2385. case 0xD3:
  2386. case 0xD4:
  2387. case 0xD5:
  2388. case 0xD6:
  2389. case 0xD7:
  2390. case 0xD8:
  2391. case 0xD9:
  2392. case 0xDA:
  2393. case 0xDB:
  2394. case 0xDC:
  2395. case 0xDD:
  2396. case 0xDE:
  2397. case 0xDF:
  2398. {
  2399. if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))
  2400. {
  2401. return token_type::parse_error;
  2402. }
  2403. break;
  2404. }
  2405. // U+0800..U+0FFF: bytes E0 A0..BF 80..BF
  2406. case 0xE0:
  2407. {
  2408. if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))
  2409. {
  2410. return token_type::parse_error;
  2411. }
  2412. break;
  2413. }
  2414. // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF
  2415. // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF
  2416. case 0xE1:
  2417. case 0xE2:
  2418. case 0xE3:
  2419. case 0xE4:
  2420. case 0xE5:
  2421. case 0xE6:
  2422. case 0xE7:
  2423. case 0xE8:
  2424. case 0xE9:
  2425. case 0xEA:
  2426. case 0xEB:
  2427. case 0xEC:
  2428. case 0xEE:
  2429. case 0xEF:
  2430. {
  2431. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))
  2432. {
  2433. return token_type::parse_error;
  2434. }
  2435. break;
  2436. }
  2437. // U+D000..U+D7FF: bytes ED 80..9F 80..BF
  2438. case 0xED:
  2439. {
  2440. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))
  2441. {
  2442. return token_type::parse_error;
  2443. }
  2444. break;
  2445. }
  2446. // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF
  2447. case 0xF0:
  2448. {
  2449. if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2450. {
  2451. return token_type::parse_error;
  2452. }
  2453. break;
  2454. }
  2455. // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF
  2456. case 0xF1:
  2457. case 0xF2:
  2458. case 0xF3:
  2459. {
  2460. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))
  2461. {
  2462. return token_type::parse_error;
  2463. }
  2464. break;
  2465. }
  2466. // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF
  2467. case 0xF4:
  2468. {
  2469. if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))
  2470. {
  2471. return token_type::parse_error;
  2472. }
  2473. break;
  2474. }
  2475. // remaining bytes (80..C1 and F5..FF) are ill-formed
  2476. default:
  2477. {
  2478. error_message = "invalid string: ill-formed UTF-8 byte";
  2479. return token_type::parse_error;
  2480. }
  2481. }
  2482. }
  2483. }
  2484. static void strtof(float& f, const char* str, char** endptr) noexcept
  2485. {
  2486. f = std::strtof(str, endptr);
  2487. }
  2488. static void strtof(double& f, const char* str, char** endptr) noexcept
  2489. {
  2490. f = std::strtod(str, endptr);
  2491. }
  2492. static void strtof(long double& f, const char* str, char** endptr) noexcept
  2493. {
  2494. f = std::strtold(str, endptr);
  2495. }
  2496. /*!
  2497. @brief scan a number literal
  2498. This function scans a string according to Sect. 6 of RFC 7159.
  2499. The function is realized with a deterministic finite state machine derived
  2500. from the grammar described in RFC 7159. Starting in state "init", the
  2501. input is read and used to determined the next state. Only state "done"
  2502. accepts the number. State "error" is a trap state to model errors. In the
  2503. table below, "anything" means any character but the ones listed before.
  2504. state | 0 | 1-9 | e E | + | - | . | anything
  2505. ---------|----------|----------|----------|---------|---------|----------|-----------
  2506. init | zero | any1 | [error] | [error] | minus | [error] | [error]
  2507. minus | zero | any1 | [error] | [error] | [error] | [error] | [error]
  2508. zero | done | done | exponent | done | done | decimal1 | done
  2509. any1 | any1 | any1 | exponent | done | done | decimal1 | done
  2510. decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error]
  2511. decimal2 | decimal2 | decimal2 | exponent | done | done | done | done
  2512. exponent | any2 | any2 | [error] | sign | sign | [error] | [error]
  2513. sign | any2 | any2 | [error] | [error] | [error] | [error] | [error]
  2514. any2 | any2 | any2 | done | done | done | done | done
  2515. The state machine is realized with one label per state (prefixed with
  2516. "scan_number_") and `goto` statements between them. The state machine
  2517. contains cycles, but any cycle can be left when EOF is read. Therefore,
  2518. the function is guaranteed to terminate.
  2519. During scanning, the read bytes are stored in token_buffer. This string is
  2520. then converted to a signed integer, an unsigned integer, or a
  2521. floating-point number.
  2522. @return token_type::value_unsigned, token_type::value_integer, or
  2523. token_type::value_float if number could be successfully scanned,
  2524. token_type::parse_error otherwise
  2525. @note The scanner is independent of the current locale. Internally, the
  2526. locale's decimal point is used instead of `.` to work with the
  2527. locale-dependent converters.
  2528. */
  2529. token_type scan_number()
  2530. {
  2531. // reset token_buffer to store the number's bytes
  2532. reset();
  2533. // the type of the parsed number; initially set to unsigned; will be
  2534. // changed if minus sign, decimal point or exponent is read
  2535. token_type number_type = token_type::value_unsigned;
  2536. // state (init): we just found out we need to scan a number
  2537. switch (current)
  2538. {
  2539. case '-':
  2540. {
  2541. add(current);
  2542. goto scan_number_minus;
  2543. }
  2544. case '0':
  2545. {
  2546. add(current);
  2547. goto scan_number_zero;
  2548. }
  2549. case '1':
  2550. case '2':
  2551. case '3':
  2552. case '4':
  2553. case '5':
  2554. case '6':
  2555. case '7':
  2556. case '8':
  2557. case '9':
  2558. {
  2559. add(current);
  2560. goto scan_number_any1;
  2561. }
  2562. // LCOV_EXCL_START
  2563. default:
  2564. {
  2565. // all other characters are rejected outside scan_number()
  2566. assert(false);
  2567. }
  2568. // LCOV_EXCL_STOP
  2569. }
  2570. scan_number_minus:
  2571. // state: we just parsed a leading minus sign
  2572. number_type = token_type::value_integer;
  2573. switch (get())
  2574. {
  2575. case '0':
  2576. {
  2577. add(current);
  2578. goto scan_number_zero;
  2579. }
  2580. case '1':
  2581. case '2':
  2582. case '3':
  2583. case '4':
  2584. case '5':
  2585. case '6':
  2586. case '7':
  2587. case '8':
  2588. case '9':
  2589. {
  2590. add(current);
  2591. goto scan_number_any1;
  2592. }
  2593. default:
  2594. {
  2595. error_message = "invalid number; expected digit after '-'";
  2596. return token_type::parse_error;
  2597. }
  2598. }
  2599. scan_number_zero:
  2600. // state: we just parse a zero (maybe with a leading minus sign)
  2601. switch (get())
  2602. {
  2603. case '.':
  2604. {
  2605. add(decimal_point_char);
  2606. goto scan_number_decimal1;
  2607. }
  2608. case 'e':
  2609. case 'E':
  2610. {
  2611. add(current);
  2612. goto scan_number_exponent;
  2613. }
  2614. default:
  2615. goto scan_number_done;
  2616. }
  2617. scan_number_any1:
  2618. // state: we just parsed a number 0-9 (maybe with a leading minus sign)
  2619. switch (get())
  2620. {
  2621. case '0':
  2622. case '1':
  2623. case '2':
  2624. case '3':
  2625. case '4':
  2626. case '5':
  2627. case '6':
  2628. case '7':
  2629. case '8':
  2630. case '9':
  2631. {
  2632. add(current);
  2633. goto scan_number_any1;
  2634. }
  2635. case '.':
  2636. {
  2637. add(decimal_point_char);
  2638. goto scan_number_decimal1;
  2639. }
  2640. case 'e':
  2641. case 'E':
  2642. {
  2643. add(current);
  2644. goto scan_number_exponent;
  2645. }
  2646. default:
  2647. goto scan_number_done;
  2648. }
  2649. scan_number_decimal1:
  2650. // state: we just parsed a decimal point
  2651. number_type = token_type::value_float;
  2652. switch (get())
  2653. {
  2654. case '0':
  2655. case '1':
  2656. case '2':
  2657. case '3':
  2658. case '4':
  2659. case '5':
  2660. case '6':
  2661. case '7':
  2662. case '8':
  2663. case '9':
  2664. {
  2665. add(current);
  2666. goto scan_number_decimal2;
  2667. }
  2668. default:
  2669. {
  2670. error_message = "invalid number; expected digit after '.'";
  2671. return token_type::parse_error;
  2672. }
  2673. }
  2674. scan_number_decimal2:
  2675. // we just parsed at least one number after a decimal point
  2676. switch (get())
  2677. {
  2678. case '0':
  2679. case '1':
  2680. case '2':
  2681. case '3':
  2682. case '4':
  2683. case '5':
  2684. case '6':
  2685. case '7':
  2686. case '8':
  2687. case '9':
  2688. {
  2689. add(current);
  2690. goto scan_number_decimal2;
  2691. }
  2692. case 'e':
  2693. case 'E':
  2694. {
  2695. add(current);
  2696. goto scan_number_exponent;
  2697. }
  2698. default:
  2699. goto scan_number_done;
  2700. }
  2701. scan_number_exponent:
  2702. // we just parsed an exponent
  2703. number_type = token_type::value_float;
  2704. switch (get())
  2705. {
  2706. case '+':
  2707. case '-':
  2708. {
  2709. add(current);
  2710. goto scan_number_sign;
  2711. }
  2712. case '0':
  2713. case '1':
  2714. case '2':
  2715. case '3':
  2716. case '4':
  2717. case '5':
  2718. case '6':
  2719. case '7':
  2720. case '8':
  2721. case '9':
  2722. {
  2723. add(current);
  2724. goto scan_number_any2;
  2725. }
  2726. default:
  2727. {
  2728. error_message =
  2729. "invalid number; expected '+', '-', or digit after exponent";
  2730. return token_type::parse_error;
  2731. }
  2732. }
  2733. scan_number_sign:
  2734. // we just parsed an exponent sign
  2735. switch (get())
  2736. {
  2737. case '0':
  2738. case '1':
  2739. case '2':
  2740. case '3':
  2741. case '4':
  2742. case '5':
  2743. case '6':
  2744. case '7':
  2745. case '8':
  2746. case '9':
  2747. {
  2748. add(current);
  2749. goto scan_number_any2;
  2750. }
  2751. default:
  2752. {
  2753. error_message = "invalid number; expected digit after exponent sign";
  2754. return token_type::parse_error;
  2755. }
  2756. }
  2757. scan_number_any2:
  2758. // we just parsed a number after the exponent or exponent sign
  2759. switch (get())
  2760. {
  2761. case '0':
  2762. case '1':
  2763. case '2':
  2764. case '3':
  2765. case '4':
  2766. case '5':
  2767. case '6':
  2768. case '7':
  2769. case '8':
  2770. case '9':
  2771. {
  2772. add(current);
  2773. goto scan_number_any2;
  2774. }
  2775. default:
  2776. goto scan_number_done;
  2777. }
  2778. scan_number_done:
  2779. // unget the character after the number (we only read it to know that
  2780. // we are done scanning a number)
  2781. unget();
  2782. char* endptr = nullptr;
  2783. errno = 0;
  2784. // try to parse integers first and fall back to floats
  2785. if (number_type == token_type::value_unsigned)
  2786. {
  2787. const auto x = std::strtoull(token_buffer.data(), &endptr, 10);
  2788. // we checked the number format before
  2789. assert(endptr == token_buffer.data() + token_buffer.size());
  2790. if (errno == 0)
  2791. {
  2792. value_unsigned = static_cast<number_unsigned_t>(x);
  2793. if (value_unsigned == x)
  2794. {
  2795. return token_type::value_unsigned;
  2796. }
  2797. }
  2798. }
  2799. else if (number_type == token_type::value_integer)
  2800. {
  2801. const auto x = std::strtoll(token_buffer.data(), &endptr, 10);
  2802. // we checked the number format before
  2803. assert(endptr == token_buffer.data() + token_buffer.size());
  2804. if (errno == 0)
  2805. {
  2806. value_integer = static_cast<number_integer_t>(x);
  2807. if (value_integer == x)
  2808. {
  2809. return token_type::value_integer;
  2810. }
  2811. }
  2812. }
  2813. // this code is reached if we parse a floating-point number or if an
  2814. // integer conversion above failed
  2815. strtof(value_float, token_buffer.data(), &endptr);
  2816. // we checked the number format before
  2817. assert(endptr == token_buffer.data() + token_buffer.size());
  2818. return token_type::value_float;
  2819. }
  2820. /*!
  2821. @param[in] literal_text the literal text to expect
  2822. @param[in] length the length of the passed literal text
  2823. @param[in] return_type the token type to return on success
  2824. */
  2825. token_type scan_literal(const char* literal_text, const std::size_t length,
  2826. token_type return_type)
  2827. {
  2828. assert(current == literal_text[0]);
  2829. for (std::size_t i = 1; i < length; ++i)
  2830. {
  2831. if (JSON_UNLIKELY(get() != literal_text[i]))
  2832. {
  2833. error_message = "invalid literal";
  2834. return token_type::parse_error;
  2835. }
  2836. }
  2837. return return_type;
  2838. }
  2839. /////////////////////
  2840. // input management
  2841. /////////////////////
  2842. /// reset token_buffer; current character is beginning of token
  2843. void reset() noexcept
  2844. {
  2845. token_buffer.clear();
  2846. token_string.clear();
  2847. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2848. }
  2849. /*
  2850. @brief get next character from the input
  2851. This function provides the interface to the used input adapter. It does
  2852. not throw in case the input reached EOF, but returns a
  2853. `std::char_traits<char>::eof()` in that case. Stores the scanned characters
  2854. for use in error messages.
  2855. @return character read from the input
  2856. */
  2857. std::char_traits<char>::int_type get()
  2858. {
  2859. ++chars_read;
  2860. if (next_unget)
  2861. {
  2862. // just reset the next_unget variable and work with current
  2863. next_unget = false;
  2864. }
  2865. else
  2866. {
  2867. current = ia->get_character();
  2868. }
  2869. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2870. {
  2871. token_string.push_back(std::char_traits<char>::to_char_type(current));
  2872. }
  2873. return current;
  2874. }
  2875. /*!
  2876. @brief unget current character (read it again on next get)
  2877. We implement unget by setting variable next_unget to true. The input is not
  2878. changed - we just simulate ungetting by modifying chars_read and
  2879. token_string. The next call to get() will behave as if the unget character
  2880. is read again.
  2881. */
  2882. void unget()
  2883. {
  2884. next_unget = true;
  2885. --chars_read;
  2886. if (JSON_LIKELY(current != std::char_traits<char>::eof()))
  2887. {
  2888. assert(token_string.size() != 0);
  2889. token_string.pop_back();
  2890. }
  2891. }
  2892. /// add a character to token_buffer
  2893. void add(int c)
  2894. {
  2895. token_buffer.push_back(std::char_traits<char>::to_char_type(c));
  2896. }
  2897. public:
  2898. /////////////////////
  2899. // value getters
  2900. /////////////////////
  2901. /// return integer value
  2902. constexpr number_integer_t get_number_integer() const noexcept
  2903. {
  2904. return value_integer;
  2905. }
  2906. /// return unsigned integer value
  2907. constexpr number_unsigned_t get_number_unsigned() const noexcept
  2908. {
  2909. return value_unsigned;
  2910. }
  2911. /// return floating-point value
  2912. constexpr number_float_t get_number_float() const noexcept
  2913. {
  2914. return value_float;
  2915. }
  2916. /// return current string value (implicitly resets the token; useful only once)
  2917. string_t& get_string()
  2918. {
  2919. return token_buffer;
  2920. }
  2921. /////////////////////
  2922. // diagnostics
  2923. /////////////////////
  2924. /// return position of last read token
  2925. constexpr std::size_t get_position() const noexcept
  2926. {
  2927. return chars_read;
  2928. }
  2929. /// return the last read token (for errors only). Will never contain EOF
  2930. /// (an arbitrary value that is not a valid char value, often -1), because
  2931. /// 255 may legitimately occur. May contain NUL, which should be escaped.
  2932. std::string get_token_string() const
  2933. {
  2934. // escape control characters
  2935. std::string result;
  2936. for (const auto c : token_string)
  2937. {
  2938. if ('\x00' <= c and c <= '\x1F')
  2939. {
  2940. // escape control characters
  2941. char cs[9];
  2942. snprintf(cs, 9, "<U+%.4X>", static_cast<unsigned char>(c));
  2943. result += cs;
  2944. }
  2945. else
  2946. {
  2947. // add character as is
  2948. result.push_back(c);
  2949. }
  2950. }
  2951. return result;
  2952. }
  2953. /// return syntax error message
  2954. constexpr const char* get_error_message() const noexcept
  2955. {
  2956. return error_message;
  2957. }
  2958. /////////////////////
  2959. // actual scanner
  2960. /////////////////////
  2961. /*!
  2962. @brief skip the UTF-8 byte order mark
  2963. @return true iff there is no BOM or the correct BOM has been skipped
  2964. */
  2965. bool skip_bom()
  2966. {
  2967. if (get() == 0xEF)
  2968. {
  2969. if (get() == 0xBB and get() == 0xBF)
  2970. {
  2971. // we completely parsed the BOM
  2972. return true;
  2973. }
  2974. else
  2975. {
  2976. // after reading 0xEF, an unexpected character followed
  2977. return false;
  2978. }
  2979. }
  2980. else
  2981. {
  2982. // the first character is not the beginning of the BOM; unget it to
  2983. // process is later
  2984. unget();
  2985. return true;
  2986. }
  2987. }
  2988. token_type scan()
  2989. {
  2990. // initially, skip the BOM
  2991. if (chars_read == 0 and not skip_bom())
  2992. {
  2993. error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given";
  2994. return token_type::parse_error;
  2995. }
  2996. // read next character and ignore whitespace
  2997. do
  2998. {
  2999. get();
  3000. }
  3001. while (current == ' ' or current == '\t' or current == '\n' or current == '\r');
  3002. switch (current)
  3003. {
  3004. // structural characters
  3005. case '[':
  3006. return token_type::begin_array;
  3007. case ']':
  3008. return token_type::end_array;
  3009. case '{':
  3010. return token_type::begin_object;
  3011. case '}':
  3012. return token_type::end_object;
  3013. case ':':
  3014. return token_type::name_separator;
  3015. case ',':
  3016. return token_type::value_separator;
  3017. // literals
  3018. case 't':
  3019. return scan_literal("true", 4, token_type::literal_true);
  3020. case 'f':
  3021. return scan_literal("false", 5, token_type::literal_false);
  3022. case 'n':
  3023. return scan_literal("null", 4, token_type::literal_null);
  3024. // string
  3025. case '\"':
  3026. return scan_string();
  3027. // number
  3028. case '-':
  3029. case '0':
  3030. case '1':
  3031. case '2':
  3032. case '3':
  3033. case '4':
  3034. case '5':
  3035. case '6':
  3036. case '7':
  3037. case '8':
  3038. case '9':
  3039. return scan_number();
  3040. // end of input (the null byte is needed when parsing from
  3041. // string literals)
  3042. case '\0':
  3043. case std::char_traits<char>::eof():
  3044. return token_type::end_of_input;
  3045. // error
  3046. default:
  3047. error_message = "invalid literal";
  3048. return token_type::parse_error;
  3049. }
  3050. }
  3051. private:
  3052. /// input adapter
  3053. detail::input_adapter_t ia = nullptr;
  3054. /// the current character
  3055. std::char_traits<char>::int_type current = std::char_traits<char>::eof();
  3056. /// whether the next get() call should just return current
  3057. bool next_unget = false;
  3058. /// the number of characters read
  3059. std::size_t chars_read = 0;
  3060. /// raw input token string (for error messages)
  3061. std::vector<char> token_string {};
  3062. /// buffer for variable-length tokens (numbers, strings)
  3063. string_t token_buffer {};
  3064. /// a description of occurred lexer errors
  3065. const char* error_message = "";
  3066. // number values
  3067. number_integer_t value_integer = 0;
  3068. number_unsigned_t value_unsigned = 0;
  3069. number_float_t value_float = 0;
  3070. /// the decimal point
  3071. const char decimal_point_char = '.';
  3072. };
  3073. }
  3074. }
  3075. // #include <nlohmann/detail/input/parser.hpp>
  3076. #include <cassert> // assert
  3077. #include <cmath> // isfinite
  3078. #include <cstdint> // uint8_t
  3079. #include <functional> // function
  3080. #include <string> // string
  3081. #include <utility> // move
  3082. // #include <nlohmann/detail/exceptions.hpp>
  3083. // #include <nlohmann/detail/macro_scope.hpp>
  3084. // #include <nlohmann/detail/meta/is_sax.hpp>
  3085. #include <cstdint> // size_t
  3086. #include <utility> // declval
  3087. // #include <nlohmann/detail/meta/detected.hpp>
  3088. #include <type_traits>
  3089. // #include <nlohmann/detail/meta/void_t.hpp>
  3090. namespace nlohmann
  3091. {
  3092. namespace detail
  3093. {
  3094. template <typename...>
  3095. using void_t = void;
  3096. }
  3097. }
  3098. // http://en.cppreference.com/w/cpp/experimental/is_detected
  3099. namespace nlohmann
  3100. {
  3101. namespace detail
  3102. {
  3103. struct nonesuch
  3104. {
  3105. nonesuch() = delete;
  3106. ~nonesuch() = delete;
  3107. nonesuch(nonesuch const&) = delete;
  3108. void operator=(nonesuch const&) = delete;
  3109. };
  3110. template <class Default,
  3111. class AlwaysVoid,
  3112. template <class...> class Op,
  3113. class... Args>
  3114. struct detector
  3115. {
  3116. using value_t = std::false_type;
  3117. using type = Default;
  3118. };
  3119. template <class Default, template <class...> class Op, class... Args>
  3120. struct detector<Default, void_t<Op<Args...>>, Op, Args...>
  3121. {
  3122. using value_t = std::true_type;
  3123. using type = Op<Args...>;
  3124. };
  3125. template <template <class...> class Op, class... Args>
  3126. using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t;
  3127. template <template <class...> class Op, class... Args>
  3128. using detected_t = typename detector<nonesuch, void, Op, Args...>::type;
  3129. template <class Default, template <class...> class Op, class... Args>
  3130. using detected_or = detector<Default, void, Op, Args...>;
  3131. template <class Default, template <class...> class Op, class... Args>
  3132. using detected_or_t = typename detected_or<Default, Op, Args...>::type;
  3133. template <class Expected, template <class...> class Op, class... Args>
  3134. using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>;
  3135. template <class To, template <class...> class Op, class... Args>
  3136. using is_detected_convertible =
  3137. std::is_convertible<detected_t<Op, Args...>, To>;
  3138. }
  3139. }
  3140. // #include <nlohmann/detail/meta/type_traits.hpp>
  3141. namespace nlohmann
  3142. {
  3143. namespace detail
  3144. {
  3145. template <typename T>
  3146. using null_function_t = decltype(std::declval<T&>().null());
  3147. template <typename T>
  3148. using boolean_function_t =
  3149. decltype(std::declval<T&>().boolean(std::declval<bool>()));
  3150. template <typename T, typename Integer>
  3151. using number_integer_function_t =
  3152. decltype(std::declval<T&>().number_integer(std::declval<Integer>()));
  3153. template <typename T, typename Unsigned>
  3154. using number_unsigned_function_t =
  3155. decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>()));
  3156. template <typename T, typename Float, typename String>
  3157. using number_float_function_t = decltype(std::declval<T&>().number_float(
  3158. std::declval<Float>(), std::declval<const String&>()));
  3159. template <typename T, typename String>
  3160. using string_function_t =
  3161. decltype(std::declval<T&>().string(std::declval<String&>()));
  3162. template <typename T>
  3163. using start_object_function_t =
  3164. decltype(std::declval<T&>().start_object(std::declval<std::size_t>()));
  3165. template <typename T, typename String>
  3166. using key_function_t =
  3167. decltype(std::declval<T&>().key(std::declval<String&>()));
  3168. template <typename T>
  3169. using end_object_function_t = decltype(std::declval<T&>().end_object());
  3170. template <typename T>
  3171. using start_array_function_t =
  3172. decltype(std::declval<T&>().start_array(std::declval<std::size_t>()));
  3173. template <typename T>
  3174. using end_array_function_t = decltype(std::declval<T&>().end_array());
  3175. template <typename T, typename Exception>
  3176. using parse_error_function_t = decltype(std::declval<T&>().parse_error(
  3177. std::declval<std::size_t>(), std::declval<const std::string&>(),
  3178. std::declval<const Exception&>()));
  3179. template <typename SAX, typename BasicJsonType>
  3180. struct is_sax
  3181. {
  3182. private:
  3183. static_assert(is_basic_json<BasicJsonType>::value,
  3184. "BasicJsonType must be of type basic_json<...>");
  3185. using number_integer_t = typename BasicJsonType::number_integer_t;
  3186. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3187. using number_float_t = typename BasicJsonType::number_float_t;
  3188. using string_t = typename BasicJsonType::string_t;
  3189. using exception_t = typename BasicJsonType::exception;
  3190. public:
  3191. static constexpr bool value =
  3192. is_detected_exact<bool, null_function_t, SAX>::value &&
  3193. is_detected_exact<bool, boolean_function_t, SAX>::value &&
  3194. is_detected_exact<bool, number_integer_function_t, SAX,
  3195. number_integer_t>::value &&
  3196. is_detected_exact<bool, number_unsigned_function_t, SAX,
  3197. number_unsigned_t>::value &&
  3198. is_detected_exact<bool, number_float_function_t, SAX, number_float_t,
  3199. string_t>::value &&
  3200. is_detected_exact<bool, string_function_t, SAX, string_t>::value &&
  3201. is_detected_exact<bool, start_object_function_t, SAX>::value &&
  3202. is_detected_exact<bool, key_function_t, SAX, string_t>::value &&
  3203. is_detected_exact<bool, end_object_function_t, SAX>::value &&
  3204. is_detected_exact<bool, start_array_function_t, SAX>::value &&
  3205. is_detected_exact<bool, end_array_function_t, SAX>::value &&
  3206. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value;
  3207. };
  3208. template <typename SAX, typename BasicJsonType>
  3209. struct is_sax_static_asserts
  3210. {
  3211. private:
  3212. static_assert(is_basic_json<BasicJsonType>::value,
  3213. "BasicJsonType must be of type basic_json<...>");
  3214. using number_integer_t = typename BasicJsonType::number_integer_t;
  3215. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3216. using number_float_t = typename BasicJsonType::number_float_t;
  3217. using string_t = typename BasicJsonType::string_t;
  3218. using exception_t = typename BasicJsonType::exception;
  3219. public:
  3220. static_assert(is_detected_exact<bool, null_function_t, SAX>::value,
  3221. "Missing/invalid function: bool null()");
  3222. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  3223. "Missing/invalid function: bool boolean(bool)");
  3224. static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value,
  3225. "Missing/invalid function: bool boolean(bool)");
  3226. static_assert(
  3227. is_detected_exact<bool, number_integer_function_t, SAX,
  3228. number_integer_t>::value,
  3229. "Missing/invalid function: bool number_integer(number_integer_t)");
  3230. static_assert(
  3231. is_detected_exact<bool, number_unsigned_function_t, SAX,
  3232. number_unsigned_t>::value,
  3233. "Missing/invalid function: bool number_unsigned(number_unsigned_t)");
  3234. static_assert(is_detected_exact<bool, number_float_function_t, SAX,
  3235. number_float_t, string_t>::value,
  3236. "Missing/invalid function: bool number_float(number_float_t, const string_t&)");
  3237. static_assert(
  3238. is_detected_exact<bool, string_function_t, SAX, string_t>::value,
  3239. "Missing/invalid function: bool string(string_t&)");
  3240. static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value,
  3241. "Missing/invalid function: bool start_object(std::size_t)");
  3242. static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value,
  3243. "Missing/invalid function: bool key(string_t&)");
  3244. static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value,
  3245. "Missing/invalid function: bool end_object()");
  3246. static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value,
  3247. "Missing/invalid function: bool start_array(std::size_t)");
  3248. static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value,
  3249. "Missing/invalid function: bool end_array()");
  3250. static_assert(
  3251. is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value,
  3252. "Missing/invalid function: bool parse_error(std::size_t, const "
  3253. "std::string&, const exception&)");
  3254. };
  3255. }
  3256. }
  3257. // #include <nlohmann/detail/input/input_adapters.hpp>
  3258. // #include <nlohmann/detail/input/json_sax.hpp>
  3259. #include <cstddef>
  3260. #include <string>
  3261. #include <vector>
  3262. // #include <nlohmann/detail/input/parser.hpp>
  3263. // #include <nlohmann/detail/exceptions.hpp>
  3264. namespace nlohmann
  3265. {
  3266. /*!
  3267. @brief SAX interface
  3268. This class describes the SAX interface used by @ref nlohmann::json::sax_parse.
  3269. Each function is called in different situations while the input is parsed. The
  3270. boolean return value informs the parser whether to continue processing the
  3271. input.
  3272. */
  3273. template<typename BasicJsonType>
  3274. struct json_sax
  3275. {
  3276. /// type for (signed) integers
  3277. using number_integer_t = typename BasicJsonType::number_integer_t;
  3278. /// type for unsigned integers
  3279. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3280. /// type for floating-point numbers
  3281. using number_float_t = typename BasicJsonType::number_float_t;
  3282. /// type for strings
  3283. using string_t = typename BasicJsonType::string_t;
  3284. /*!
  3285. @brief a null value was read
  3286. @return whether parsing should proceed
  3287. */
  3288. virtual bool null() = 0;
  3289. /*!
  3290. @brief a boolean value was read
  3291. @param[in] val boolean value
  3292. @return whether parsing should proceed
  3293. */
  3294. virtual bool boolean(bool val) = 0;
  3295. /*!
  3296. @brief an integer number was read
  3297. @param[in] val integer value
  3298. @return whether parsing should proceed
  3299. */
  3300. virtual bool number_integer(number_integer_t val) = 0;
  3301. /*!
  3302. @brief an unsigned integer number was read
  3303. @param[in] val unsigned integer value
  3304. @return whether parsing should proceed
  3305. */
  3306. virtual bool number_unsigned(number_unsigned_t val) = 0;
  3307. /*!
  3308. @brief an floating-point number was read
  3309. @param[in] val floating-point value
  3310. @param[in] s raw token value
  3311. @return whether parsing should proceed
  3312. */
  3313. virtual bool number_float(number_float_t val, const string_t& s) = 0;
  3314. /*!
  3315. @brief a string was read
  3316. @param[in] val string value
  3317. @return whether parsing should proceed
  3318. @note It is safe to move the passed string.
  3319. */
  3320. virtual bool string(string_t& val) = 0;
  3321. /*!
  3322. @brief the beginning of an object was read
  3323. @param[in] elements number of object elements or -1 if unknown
  3324. @return whether parsing should proceed
  3325. @note binary formats may report the number of elements
  3326. */
  3327. virtual bool start_object(std::size_t elements) = 0;
  3328. /*!
  3329. @brief an object key was read
  3330. @param[in] val object key
  3331. @return whether parsing should proceed
  3332. @note It is safe to move the passed string.
  3333. */
  3334. virtual bool key(string_t& val) = 0;
  3335. /*!
  3336. @brief the end of an object was read
  3337. @return whether parsing should proceed
  3338. */
  3339. virtual bool end_object() = 0;
  3340. /*!
  3341. @brief the beginning of an array was read
  3342. @param[in] elements number of array elements or -1 if unknown
  3343. @return whether parsing should proceed
  3344. @note binary formats may report the number of elements
  3345. */
  3346. virtual bool start_array(std::size_t elements) = 0;
  3347. /*!
  3348. @brief the end of an array was read
  3349. @return whether parsing should proceed
  3350. */
  3351. virtual bool end_array() = 0;
  3352. /*!
  3353. @brief a parse error occurred
  3354. @param[in] position the position in the input where the error occurs
  3355. @param[in] last_token the last read token
  3356. @param[in] error_msg a detailed error message
  3357. @return whether parsing should proceed (must return false)
  3358. */
  3359. virtual bool parse_error(std::size_t position,
  3360. const std::string& last_token,
  3361. const detail::exception& ex) = 0;
  3362. virtual ~json_sax() = default;
  3363. };
  3364. namespace detail
  3365. {
  3366. /*!
  3367. @brief SAX implementation to create a JSON value from SAX events
  3368. This class implements the @ref json_sax interface and processes the SAX events
  3369. to create a JSON value which makes it basically a DOM parser. The structure or
  3370. hierarchy of the JSON value is managed by the stack `ref_stack` which contains
  3371. a pointer to the respective array or object for each recursion depth.
  3372. After successful parsing, the value that is passed by reference to the
  3373. constructor contains the parsed value.
  3374. @tparam BasicJsonType the JSON type
  3375. */
  3376. template<typename BasicJsonType>
  3377. class json_sax_dom_parser
  3378. {
  3379. public:
  3380. using number_integer_t = typename BasicJsonType::number_integer_t;
  3381. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3382. using number_float_t = typename BasicJsonType::number_float_t;
  3383. using string_t = typename BasicJsonType::string_t;
  3384. /*!
  3385. @param[in, out] r reference to a JSON value that is manipulated while
  3386. parsing
  3387. @param[in] allow_exceptions_ whether parse errors yield exceptions
  3388. */
  3389. explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true)
  3390. : root(r), allow_exceptions(allow_exceptions_)
  3391. {}
  3392. bool null()
  3393. {
  3394. handle_value(nullptr);
  3395. return true;
  3396. }
  3397. bool boolean(bool val)
  3398. {
  3399. handle_value(val);
  3400. return true;
  3401. }
  3402. bool number_integer(number_integer_t val)
  3403. {
  3404. handle_value(val);
  3405. return true;
  3406. }
  3407. bool number_unsigned(number_unsigned_t val)
  3408. {
  3409. handle_value(val);
  3410. return true;
  3411. }
  3412. bool number_float(number_float_t val, const string_t&)
  3413. {
  3414. handle_value(val);
  3415. return true;
  3416. }
  3417. bool string(string_t& val)
  3418. {
  3419. handle_value(val);
  3420. return true;
  3421. }
  3422. bool start_object(std::size_t len)
  3423. {
  3424. ref_stack.push_back(handle_value(BasicJsonType::value_t::object));
  3425. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3426. {
  3427. JSON_THROW(out_of_range::create(408,
  3428. "excessive object size: " + std::to_string(len)));
  3429. }
  3430. return true;
  3431. }
  3432. bool key(string_t& val)
  3433. {
  3434. // add null at given key and store the reference for later
  3435. object_element = &(ref_stack.back()->m_value.object->operator[](val));
  3436. return true;
  3437. }
  3438. bool end_object()
  3439. {
  3440. ref_stack.pop_back();
  3441. return true;
  3442. }
  3443. bool start_array(std::size_t len)
  3444. {
  3445. ref_stack.push_back(handle_value(BasicJsonType::value_t::array));
  3446. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3447. {
  3448. JSON_THROW(out_of_range::create(408,
  3449. "excessive array size: " + std::to_string(len)));
  3450. }
  3451. return true;
  3452. }
  3453. bool end_array()
  3454. {
  3455. ref_stack.pop_back();
  3456. return true;
  3457. }
  3458. bool parse_error(std::size_t, const std::string&,
  3459. const detail::exception& ex)
  3460. {
  3461. errored = true;
  3462. if (allow_exceptions)
  3463. {
  3464. // determine the proper exception type from the id
  3465. switch ((ex.id / 100) % 100)
  3466. {
  3467. case 1:
  3468. JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
  3469. case 4:
  3470. JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
  3471. // LCOV_EXCL_START
  3472. case 2:
  3473. JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
  3474. case 3:
  3475. JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
  3476. case 5:
  3477. JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
  3478. default:
  3479. assert(false);
  3480. // LCOV_EXCL_STOP
  3481. }
  3482. }
  3483. return false;
  3484. }
  3485. constexpr bool is_errored() const
  3486. {
  3487. return errored;
  3488. }
  3489. private:
  3490. /*!
  3491. @invariant If the ref stack is empty, then the passed value will be the new
  3492. root.
  3493. @invariant If the ref stack contains a value, then it is an array or an
  3494. object to which we can add elements
  3495. */
  3496. template<typename Value>
  3497. BasicJsonType* handle_value(Value&& v)
  3498. {
  3499. if (ref_stack.empty())
  3500. {
  3501. root = BasicJsonType(std::forward<Value>(v));
  3502. return &root;
  3503. }
  3504. else
  3505. {
  3506. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  3507. if (ref_stack.back()->is_array())
  3508. {
  3509. ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v));
  3510. return &(ref_stack.back()->m_value.array->back());
  3511. }
  3512. else
  3513. {
  3514. assert(object_element);
  3515. *object_element = BasicJsonType(std::forward<Value>(v));
  3516. return object_element;
  3517. }
  3518. }
  3519. }
  3520. /// the parsed JSON value
  3521. BasicJsonType& root;
  3522. /// stack to model hierarchy of values
  3523. std::vector<BasicJsonType*> ref_stack;
  3524. /// helper to hold the reference for the next object element
  3525. BasicJsonType* object_element = nullptr;
  3526. /// whether a syntax error occurred
  3527. bool errored = false;
  3528. /// whether to throw exceptions in case of errors
  3529. const bool allow_exceptions = true;
  3530. };
  3531. template<typename BasicJsonType>
  3532. class json_sax_dom_callback_parser
  3533. {
  3534. public:
  3535. using number_integer_t = typename BasicJsonType::number_integer_t;
  3536. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3537. using number_float_t = typename BasicJsonType::number_float_t;
  3538. using string_t = typename BasicJsonType::string_t;
  3539. using parser_callback_t = typename BasicJsonType::parser_callback_t;
  3540. using parse_event_t = typename BasicJsonType::parse_event_t;
  3541. json_sax_dom_callback_parser(BasicJsonType& r,
  3542. const parser_callback_t cb,
  3543. const bool allow_exceptions_ = true)
  3544. : root(r), callback(cb), allow_exceptions(allow_exceptions_)
  3545. {
  3546. keep_stack.push_back(true);
  3547. }
  3548. bool null()
  3549. {
  3550. handle_value(nullptr);
  3551. return true;
  3552. }
  3553. bool boolean(bool val)
  3554. {
  3555. handle_value(val);
  3556. return true;
  3557. }
  3558. bool number_integer(number_integer_t val)
  3559. {
  3560. handle_value(val);
  3561. return true;
  3562. }
  3563. bool number_unsigned(number_unsigned_t val)
  3564. {
  3565. handle_value(val);
  3566. return true;
  3567. }
  3568. bool number_float(number_float_t val, const string_t&)
  3569. {
  3570. handle_value(val);
  3571. return true;
  3572. }
  3573. bool string(string_t& val)
  3574. {
  3575. handle_value(val);
  3576. return true;
  3577. }
  3578. bool start_object(std::size_t len)
  3579. {
  3580. // check callback for object start
  3581. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded);
  3582. keep_stack.push_back(keep);
  3583. auto val = handle_value(BasicJsonType::value_t::object, true);
  3584. ref_stack.push_back(val.second);
  3585. // check object limit
  3586. if (ref_stack.back())
  3587. {
  3588. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3589. {
  3590. JSON_THROW(out_of_range::create(408,
  3591. "excessive object size: " + std::to_string(len)));
  3592. }
  3593. }
  3594. return true;
  3595. }
  3596. bool key(string_t& val)
  3597. {
  3598. BasicJsonType k = BasicJsonType(val);
  3599. // check callback for key
  3600. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k);
  3601. key_keep_stack.push_back(keep);
  3602. // add discarded value at given key and store the reference for later
  3603. if (keep and ref_stack.back())
  3604. {
  3605. object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded);
  3606. }
  3607. return true;
  3608. }
  3609. bool end_object()
  3610. {
  3611. if (ref_stack.back())
  3612. {
  3613. if (not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back()))
  3614. {
  3615. // discard object
  3616. *ref_stack.back() = discarded;
  3617. }
  3618. }
  3619. assert(not ref_stack.empty());
  3620. assert(not keep_stack.empty());
  3621. ref_stack.pop_back();
  3622. keep_stack.pop_back();
  3623. if (not ref_stack.empty() and ref_stack.back())
  3624. {
  3625. // remove discarded value
  3626. if (ref_stack.back()->is_object())
  3627. {
  3628. for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it)
  3629. {
  3630. if (it->is_discarded())
  3631. {
  3632. ref_stack.back()->erase(it);
  3633. break;
  3634. }
  3635. }
  3636. }
  3637. }
  3638. return true;
  3639. }
  3640. bool start_array(std::size_t len)
  3641. {
  3642. const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded);
  3643. keep_stack.push_back(keep);
  3644. auto val = handle_value(BasicJsonType::value_t::array, true);
  3645. ref_stack.push_back(val.second);
  3646. // check array limit
  3647. if (ref_stack.back())
  3648. {
  3649. if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size()))
  3650. {
  3651. JSON_THROW(out_of_range::create(408,
  3652. "excessive array size: " + std::to_string(len)));
  3653. }
  3654. }
  3655. return true;
  3656. }
  3657. bool end_array()
  3658. {
  3659. bool keep = true;
  3660. if (ref_stack.back())
  3661. {
  3662. keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back());
  3663. if (not keep)
  3664. {
  3665. // discard array
  3666. *ref_stack.back() = discarded;
  3667. }
  3668. }
  3669. assert(not ref_stack.empty());
  3670. assert(not keep_stack.empty());
  3671. ref_stack.pop_back();
  3672. keep_stack.pop_back();
  3673. // remove discarded value
  3674. if (not keep and not ref_stack.empty())
  3675. {
  3676. if (ref_stack.back()->is_array())
  3677. {
  3678. ref_stack.back()->m_value.array->pop_back();
  3679. }
  3680. }
  3681. return true;
  3682. }
  3683. bool parse_error(std::size_t, const std::string&,
  3684. const detail::exception& ex)
  3685. {
  3686. errored = true;
  3687. if (allow_exceptions)
  3688. {
  3689. // determine the proper exception type from the id
  3690. switch ((ex.id / 100) % 100)
  3691. {
  3692. case 1:
  3693. JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex));
  3694. case 4:
  3695. JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex));
  3696. // LCOV_EXCL_START
  3697. case 2:
  3698. JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex));
  3699. case 3:
  3700. JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex));
  3701. case 5:
  3702. JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex));
  3703. default:
  3704. assert(false);
  3705. // LCOV_EXCL_STOP
  3706. }
  3707. }
  3708. return false;
  3709. }
  3710. constexpr bool is_errored() const
  3711. {
  3712. return errored;
  3713. }
  3714. private:
  3715. /*!
  3716. @param[in] v value to add to the JSON value we build during parsing
  3717. @param[in] skip_callback whether we should skip calling the callback
  3718. function; this is required after start_array() and
  3719. start_object() SAX events, because otherwise we would call the
  3720. callback function with an empty array or object, respectively.
  3721. @invariant If the ref stack is empty, then the passed value will be the new
  3722. root.
  3723. @invariant If the ref stack contains a value, then it is an array or an
  3724. object to which we can add elements
  3725. @return pair of boolean (whether value should be kept) and pointer (to the
  3726. passed value in the ref_stack hierarchy; nullptr if not kept)
  3727. */
  3728. template<typename Value>
  3729. std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false)
  3730. {
  3731. assert(not keep_stack.empty());
  3732. // do not handle this value if we know it would be added to a discarded
  3733. // container
  3734. if (not keep_stack.back())
  3735. {
  3736. return {false, nullptr};
  3737. }
  3738. // create value
  3739. auto value = BasicJsonType(std::forward<Value>(v));
  3740. // check callback
  3741. const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value);
  3742. // do not handle this value if we just learnt it shall be discarded
  3743. if (not keep)
  3744. {
  3745. return {false, nullptr};
  3746. }
  3747. if (ref_stack.empty())
  3748. {
  3749. root = std::move(value);
  3750. return {true, &root};
  3751. }
  3752. else
  3753. {
  3754. // skip this value if we already decided to skip the parent
  3755. // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360)
  3756. if (not ref_stack.back())
  3757. {
  3758. return {false, nullptr};
  3759. }
  3760. assert(ref_stack.back()->is_array() or ref_stack.back()->is_object());
  3761. if (ref_stack.back()->is_array())
  3762. {
  3763. ref_stack.back()->m_value.array->push_back(std::move(value));
  3764. return {true, &(ref_stack.back()->m_value.array->back())};
  3765. }
  3766. else
  3767. {
  3768. // check if we should store an element for the current key
  3769. assert(not key_keep_stack.empty());
  3770. const bool store_element = key_keep_stack.back();
  3771. key_keep_stack.pop_back();
  3772. if (not store_element)
  3773. {
  3774. return {false, nullptr};
  3775. }
  3776. assert(object_element);
  3777. *object_element = std::move(value);
  3778. return {true, object_element};
  3779. }
  3780. }
  3781. }
  3782. /// the parsed JSON value
  3783. BasicJsonType& root;
  3784. /// stack to model hierarchy of values
  3785. std::vector<BasicJsonType*> ref_stack;
  3786. /// stack to manage which values to keep
  3787. std::vector<bool> keep_stack;
  3788. /// stack to manage which object keys to keep
  3789. std::vector<bool> key_keep_stack;
  3790. /// helper to hold the reference for the next object element
  3791. BasicJsonType* object_element = nullptr;
  3792. /// whether a syntax error occurred
  3793. bool errored = false;
  3794. /// callback function
  3795. const parser_callback_t callback = nullptr;
  3796. /// whether to throw exceptions in case of errors
  3797. const bool allow_exceptions = true;
  3798. /// a discarded value for the callback
  3799. BasicJsonType discarded = BasicJsonType::value_t::discarded;
  3800. };
  3801. template<typename BasicJsonType>
  3802. class json_sax_acceptor
  3803. {
  3804. public:
  3805. using number_integer_t = typename BasicJsonType::number_integer_t;
  3806. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3807. using number_float_t = typename BasicJsonType::number_float_t;
  3808. using string_t = typename BasicJsonType::string_t;
  3809. bool null()
  3810. {
  3811. return true;
  3812. }
  3813. bool boolean(bool)
  3814. {
  3815. return true;
  3816. }
  3817. bool number_integer(number_integer_t)
  3818. {
  3819. return true;
  3820. }
  3821. bool number_unsigned(number_unsigned_t)
  3822. {
  3823. return true;
  3824. }
  3825. bool number_float(number_float_t, const string_t&)
  3826. {
  3827. return true;
  3828. }
  3829. bool string(string_t&)
  3830. {
  3831. return true;
  3832. }
  3833. bool start_object(std::size_t = std::size_t(-1))
  3834. {
  3835. return true;
  3836. }
  3837. bool key(string_t&)
  3838. {
  3839. return true;
  3840. }
  3841. bool end_object()
  3842. {
  3843. return true;
  3844. }
  3845. bool start_array(std::size_t = std::size_t(-1))
  3846. {
  3847. return true;
  3848. }
  3849. bool end_array()
  3850. {
  3851. return true;
  3852. }
  3853. bool parse_error(std::size_t, const std::string&, const detail::exception&)
  3854. {
  3855. return false;
  3856. }
  3857. };
  3858. }
  3859. }
  3860. // #include <nlohmann/detail/input/lexer.hpp>
  3861. // #include <nlohmann/detail/value_t.hpp>
  3862. namespace nlohmann
  3863. {
  3864. namespace detail
  3865. {
  3866. ////////////
  3867. // parser //
  3868. ////////////
  3869. /*!
  3870. @brief syntax analysis
  3871. This class implements a recursive decent parser.
  3872. */
  3873. template<typename BasicJsonType>
  3874. class parser
  3875. {
  3876. using number_integer_t = typename BasicJsonType::number_integer_t;
  3877. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  3878. using number_float_t = typename BasicJsonType::number_float_t;
  3879. using string_t = typename BasicJsonType::string_t;
  3880. using lexer_t = lexer<BasicJsonType>;
  3881. using token_type = typename lexer_t::token_type;
  3882. public:
  3883. enum class parse_event_t : uint8_t
  3884. {
  3885. /// the parser read `{` and started to process a JSON object
  3886. object_start,
  3887. /// the parser read `}` and finished processing a JSON object
  3888. object_end,
  3889. /// the parser read `[` and started to process a JSON array
  3890. array_start,
  3891. /// the parser read `]` and finished processing a JSON array
  3892. array_end,
  3893. /// the parser read a key of a value in an object
  3894. key,
  3895. /// the parser finished reading a JSON value
  3896. value
  3897. };
  3898. using parser_callback_t =
  3899. std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;
  3900. /// a parser reading from an input adapter
  3901. explicit parser(detail::input_adapter_t&& adapter,
  3902. const parser_callback_t cb = nullptr,
  3903. const bool allow_exceptions_ = true)
  3904. : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_)
  3905. {
  3906. // read first token
  3907. get_token();
  3908. }
  3909. /*!
  3910. @brief public parser interface
  3911. @param[in] strict whether to expect the last token to be EOF
  3912. @param[in,out] result parsed JSON value
  3913. @throw parse_error.101 in case of an unexpected token
  3914. @throw parse_error.102 if to_unicode fails or surrogate error
  3915. @throw parse_error.103 if to_unicode fails
  3916. */
  3917. void parse(const bool strict, BasicJsonType& result)
  3918. {
  3919. if (callback)
  3920. {
  3921. json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions);
  3922. sax_parse_internal(&sdp);
  3923. result.assert_invariant();
  3924. // in strict mode, input must be completely read
  3925. if (strict and (get_token() != token_type::end_of_input))
  3926. {
  3927. sdp.parse_error(m_lexer.get_position(),
  3928. m_lexer.get_token_string(),
  3929. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
  3930. }
  3931. // in case of an error, return discarded value
  3932. if (sdp.is_errored())
  3933. {
  3934. result = value_t::discarded;
  3935. return;
  3936. }
  3937. // set top-level value to null if it was discarded by the callback
  3938. // function
  3939. if (result.is_discarded())
  3940. {
  3941. result = nullptr;
  3942. }
  3943. }
  3944. else
  3945. {
  3946. json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions);
  3947. sax_parse_internal(&sdp);
  3948. result.assert_invariant();
  3949. // in strict mode, input must be completely read
  3950. if (strict and (get_token() != token_type::end_of_input))
  3951. {
  3952. sdp.parse_error(m_lexer.get_position(),
  3953. m_lexer.get_token_string(),
  3954. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
  3955. }
  3956. // in case of an error, return discarded value
  3957. if (sdp.is_errored())
  3958. {
  3959. result = value_t::discarded;
  3960. return;
  3961. }
  3962. }
  3963. }
  3964. /*!
  3965. @brief public accept interface
  3966. @param[in] strict whether to expect the last token to be EOF
  3967. @return whether the input is a proper JSON text
  3968. */
  3969. bool accept(const bool strict = true)
  3970. {
  3971. json_sax_acceptor<BasicJsonType> sax_acceptor;
  3972. return sax_parse(&sax_acceptor, strict);
  3973. }
  3974. template <typename SAX>
  3975. bool sax_parse(SAX* sax, const bool strict = true)
  3976. {
  3977. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  3978. const bool result = sax_parse_internal(sax);
  3979. // strict mode: next byte must be EOF
  3980. if (result and strict and (get_token() != token_type::end_of_input))
  3981. {
  3982. return sax->parse_error(m_lexer.get_position(),
  3983. m_lexer.get_token_string(),
  3984. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input)));
  3985. }
  3986. return result;
  3987. }
  3988. private:
  3989. template <typename SAX>
  3990. bool sax_parse_internal(SAX* sax)
  3991. {
  3992. // stack to remember the hieararchy of structured values we are parsing
  3993. // true = array; false = object
  3994. std::vector<bool> states;
  3995. // value to avoid a goto (see comment where set to true)
  3996. bool skip_to_state_evaluation = false;
  3997. while (true)
  3998. {
  3999. if (not skip_to_state_evaluation)
  4000. {
  4001. // invariant: get_token() was called before each iteration
  4002. switch (last_token)
  4003. {
  4004. case token_type::begin_object:
  4005. {
  4006. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  4007. {
  4008. return false;
  4009. }
  4010. // closing } -> we are done
  4011. if (get_token() == token_type::end_object)
  4012. {
  4013. if (JSON_UNLIKELY(not sax->end_object()))
  4014. {
  4015. return false;
  4016. }
  4017. break;
  4018. }
  4019. // parse key
  4020. if (JSON_UNLIKELY(last_token != token_type::value_string))
  4021. {
  4022. return sax->parse_error(m_lexer.get_position(),
  4023. m_lexer.get_token_string(),
  4024. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string)));
  4025. }
  4026. else
  4027. {
  4028. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  4029. {
  4030. return false;
  4031. }
  4032. }
  4033. // parse separator (:)
  4034. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  4035. {
  4036. return sax->parse_error(m_lexer.get_position(),
  4037. m_lexer.get_token_string(),
  4038. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator)));
  4039. }
  4040. // remember we are now inside an object
  4041. states.push_back(false);
  4042. // parse values
  4043. get_token();
  4044. continue;
  4045. }
  4046. case token_type::begin_array:
  4047. {
  4048. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  4049. {
  4050. return false;
  4051. }
  4052. // closing ] -> we are done
  4053. if (get_token() == token_type::end_array)
  4054. {
  4055. if (JSON_UNLIKELY(not sax->end_array()))
  4056. {
  4057. return false;
  4058. }
  4059. break;
  4060. }
  4061. // remember we are now inside an array
  4062. states.push_back(true);
  4063. // parse values (no need to call get_token)
  4064. continue;
  4065. }
  4066. case token_type::value_float:
  4067. {
  4068. const auto res = m_lexer.get_number_float();
  4069. if (JSON_UNLIKELY(not std::isfinite(res)))
  4070. {
  4071. return sax->parse_error(m_lexer.get_position(),
  4072. m_lexer.get_token_string(),
  4073. out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'"));
  4074. }
  4075. else
  4076. {
  4077. if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string())))
  4078. {
  4079. return false;
  4080. }
  4081. break;
  4082. }
  4083. }
  4084. case token_type::literal_false:
  4085. {
  4086. if (JSON_UNLIKELY(not sax->boolean(false)))
  4087. {
  4088. return false;
  4089. }
  4090. break;
  4091. }
  4092. case token_type::literal_null:
  4093. {
  4094. if (JSON_UNLIKELY(not sax->null()))
  4095. {
  4096. return false;
  4097. }
  4098. break;
  4099. }
  4100. case token_type::literal_true:
  4101. {
  4102. if (JSON_UNLIKELY(not sax->boolean(true)))
  4103. {
  4104. return false;
  4105. }
  4106. break;
  4107. }
  4108. case token_type::value_integer:
  4109. {
  4110. if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer())))
  4111. {
  4112. return false;
  4113. }
  4114. break;
  4115. }
  4116. case token_type::value_string:
  4117. {
  4118. if (JSON_UNLIKELY(not sax->string(m_lexer.get_string())))
  4119. {
  4120. return false;
  4121. }
  4122. break;
  4123. }
  4124. case token_type::value_unsigned:
  4125. {
  4126. if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned())))
  4127. {
  4128. return false;
  4129. }
  4130. break;
  4131. }
  4132. case token_type::parse_error:
  4133. {
  4134. // using "uninitialized" to avoid "expected" message
  4135. return sax->parse_error(m_lexer.get_position(),
  4136. m_lexer.get_token_string(),
  4137. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized)));
  4138. }
  4139. default: // the last token was unexpected
  4140. {
  4141. return sax->parse_error(m_lexer.get_position(),
  4142. m_lexer.get_token_string(),
  4143. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value)));
  4144. }
  4145. }
  4146. }
  4147. else
  4148. {
  4149. skip_to_state_evaluation = false;
  4150. }
  4151. // we reached this line after we successfully parsed a value
  4152. if (states.empty())
  4153. {
  4154. // empty stack: we reached the end of the hieararchy: done
  4155. return true;
  4156. }
  4157. else
  4158. {
  4159. if (states.back()) // array
  4160. {
  4161. // comma -> next value
  4162. if (get_token() == token_type::value_separator)
  4163. {
  4164. // parse a new value
  4165. get_token();
  4166. continue;
  4167. }
  4168. // closing ]
  4169. if (JSON_LIKELY(last_token == token_type::end_array))
  4170. {
  4171. if (JSON_UNLIKELY(not sax->end_array()))
  4172. {
  4173. return false;
  4174. }
  4175. // We are done with this array. Before we can parse a
  4176. // new value, we need to evaluate the new state first.
  4177. // By setting skip_to_state_evaluation to false, we
  4178. // are effectively jumping to the beginning of this if.
  4179. assert(not states.empty());
  4180. states.pop_back();
  4181. skip_to_state_evaluation = true;
  4182. continue;
  4183. }
  4184. else
  4185. {
  4186. return sax->parse_error(m_lexer.get_position(),
  4187. m_lexer.get_token_string(),
  4188. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array)));
  4189. }
  4190. }
  4191. else // object
  4192. {
  4193. // comma -> next value
  4194. if (get_token() == token_type::value_separator)
  4195. {
  4196. // parse key
  4197. if (JSON_UNLIKELY(get_token() != token_type::value_string))
  4198. {
  4199. return sax->parse_error(m_lexer.get_position(),
  4200. m_lexer.get_token_string(),
  4201. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string)));
  4202. }
  4203. else
  4204. {
  4205. if (JSON_UNLIKELY(not sax->key(m_lexer.get_string())))
  4206. {
  4207. return false;
  4208. }
  4209. }
  4210. // parse separator (:)
  4211. if (JSON_UNLIKELY(get_token() != token_type::name_separator))
  4212. {
  4213. return sax->parse_error(m_lexer.get_position(),
  4214. m_lexer.get_token_string(),
  4215. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator)));
  4216. }
  4217. // parse values
  4218. get_token();
  4219. continue;
  4220. }
  4221. // closing }
  4222. if (JSON_LIKELY(last_token == token_type::end_object))
  4223. {
  4224. if (JSON_UNLIKELY(not sax->end_object()))
  4225. {
  4226. return false;
  4227. }
  4228. // We are done with this object. Before we can parse a
  4229. // new value, we need to evaluate the new state first.
  4230. // By setting skip_to_state_evaluation to false, we
  4231. // are effectively jumping to the beginning of this if.
  4232. assert(not states.empty());
  4233. states.pop_back();
  4234. skip_to_state_evaluation = true;
  4235. continue;
  4236. }
  4237. else
  4238. {
  4239. return sax->parse_error(m_lexer.get_position(),
  4240. m_lexer.get_token_string(),
  4241. parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object)));
  4242. }
  4243. }
  4244. }
  4245. }
  4246. }
  4247. /// get next token from lexer
  4248. token_type get_token()
  4249. {
  4250. return (last_token = m_lexer.scan());
  4251. }
  4252. std::string exception_message(const token_type expected)
  4253. {
  4254. std::string error_msg = "syntax error - ";
  4255. if (last_token == token_type::parse_error)
  4256. {
  4257. error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" +
  4258. m_lexer.get_token_string() + "'";
  4259. }
  4260. else
  4261. {
  4262. error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token));
  4263. }
  4264. if (expected != token_type::uninitialized)
  4265. {
  4266. error_msg += "; expected " + std::string(lexer_t::token_type_name(expected));
  4267. }
  4268. return error_msg;
  4269. }
  4270. private:
  4271. /// callback function
  4272. const parser_callback_t callback = nullptr;
  4273. /// the type of the last read token
  4274. token_type last_token = token_type::uninitialized;
  4275. /// the lexer
  4276. lexer_t m_lexer;
  4277. /// whether to throw exceptions in case of errors
  4278. const bool allow_exceptions = true;
  4279. };
  4280. }
  4281. }
  4282. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4283. #include <cstddef> // ptrdiff_t
  4284. #include <limits> // numeric_limits
  4285. namespace nlohmann
  4286. {
  4287. namespace detail
  4288. {
  4289. /*
  4290. @brief an iterator for primitive JSON types
  4291. This class models an iterator for primitive JSON types (boolean, number,
  4292. string). It's only purpose is to allow the iterator/const_iterator classes
  4293. to "iterate" over primitive values. Internally, the iterator is modeled by
  4294. a `difference_type` variable. Value begin_value (`0`) models the begin,
  4295. end_value (`1`) models past the end.
  4296. */
  4297. class primitive_iterator_t
  4298. {
  4299. private:
  4300. using difference_type = std::ptrdiff_t;
  4301. static constexpr difference_type begin_value = 0;
  4302. static constexpr difference_type end_value = begin_value + 1;
  4303. /// iterator as signed integer type
  4304. difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();
  4305. public:
  4306. constexpr difference_type get_value() const noexcept
  4307. {
  4308. return m_it;
  4309. }
  4310. /// set iterator to a defined beginning
  4311. void set_begin() noexcept
  4312. {
  4313. m_it = begin_value;
  4314. }
  4315. /// set iterator to a defined past the end
  4316. void set_end() noexcept
  4317. {
  4318. m_it = end_value;
  4319. }
  4320. /// return whether the iterator can be dereferenced
  4321. constexpr bool is_begin() const noexcept
  4322. {
  4323. return m_it == begin_value;
  4324. }
  4325. /// return whether the iterator is at end
  4326. constexpr bool is_end() const noexcept
  4327. {
  4328. return m_it == end_value;
  4329. }
  4330. friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4331. {
  4332. return lhs.m_it == rhs.m_it;
  4333. }
  4334. friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4335. {
  4336. return lhs.m_it < rhs.m_it;
  4337. }
  4338. primitive_iterator_t operator+(difference_type n) noexcept
  4339. {
  4340. auto result = *this;
  4341. result += n;
  4342. return result;
  4343. }
  4344. friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
  4345. {
  4346. return lhs.m_it - rhs.m_it;
  4347. }
  4348. primitive_iterator_t& operator++() noexcept
  4349. {
  4350. ++m_it;
  4351. return *this;
  4352. }
  4353. primitive_iterator_t const operator++(int) noexcept
  4354. {
  4355. auto result = *this;
  4356. ++m_it;
  4357. return result;
  4358. }
  4359. primitive_iterator_t& operator--() noexcept
  4360. {
  4361. --m_it;
  4362. return *this;
  4363. }
  4364. primitive_iterator_t const operator--(int) noexcept
  4365. {
  4366. auto result = *this;
  4367. --m_it;
  4368. return result;
  4369. }
  4370. primitive_iterator_t& operator+=(difference_type n) noexcept
  4371. {
  4372. m_it += n;
  4373. return *this;
  4374. }
  4375. primitive_iterator_t& operator-=(difference_type n) noexcept
  4376. {
  4377. m_it -= n;
  4378. return *this;
  4379. }
  4380. };
  4381. }
  4382. }
  4383. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  4384. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4385. namespace nlohmann
  4386. {
  4387. namespace detail
  4388. {
  4389. /*!
  4390. @brief an iterator value
  4391. @note This structure could easily be a union, but MSVC currently does not allow
  4392. unions members with complex constructors, see https://github.com/nlohmann/json/pull/105.
  4393. */
  4394. template<typename BasicJsonType> struct internal_iterator
  4395. {
  4396. /// iterator for JSON objects
  4397. typename BasicJsonType::object_t::iterator object_iterator {};
  4398. /// iterator for JSON arrays
  4399. typename BasicJsonType::array_t::iterator array_iterator {};
  4400. /// generic iterator for all other types
  4401. primitive_iterator_t primitive_iterator {};
  4402. };
  4403. }
  4404. }
  4405. // #include <nlohmann/detail/iterators/iter_impl.hpp>
  4406. #include <ciso646> // not
  4407. #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next
  4408. #include <type_traits> // conditional, is_const, remove_const
  4409. // #include <nlohmann/detail/exceptions.hpp>
  4410. // #include <nlohmann/detail/iterators/internal_iterator.hpp>
  4411. // #include <nlohmann/detail/iterators/primitive_iterator.hpp>
  4412. // #include <nlohmann/detail/macro_scope.hpp>
  4413. // #include <nlohmann/detail/meta/cpp_future.hpp>
  4414. // #include <nlohmann/detail/value_t.hpp>
  4415. namespace nlohmann
  4416. {
  4417. namespace detail
  4418. {
  4419. // forward declare, to be able to friend it later on
  4420. template<typename IteratorType> class iteration_proxy;
  4421. /*!
  4422. @brief a template for a bidirectional iterator for the @ref basic_json class
  4423. This class implements a both iterators (iterator and const_iterator) for the
  4424. @ref basic_json class.
  4425. @note An iterator is called *initialized* when a pointer to a JSON value has
  4426. been set (e.g., by a constructor or a copy assignment). If the iterator is
  4427. default-constructed, it is *uninitialized* and most methods are undefined.
  4428. **The library uses assertions to detect calls on uninitialized iterators.**
  4429. @requirement The class satisfies the following concept requirements:
  4430. -
  4431. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  4432. The iterator that can be moved can be moved in both directions (i.e.
  4433. incremented and decremented).
  4434. @since version 1.0.0, simplified in version 2.0.9, change to bidirectional
  4435. iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)
  4436. */
  4437. template<typename BasicJsonType>
  4438. class iter_impl
  4439. {
  4440. /// allow basic_json to access private members
  4441. friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;
  4442. friend BasicJsonType;
  4443. friend iteration_proxy<iter_impl>;
  4444. using object_t = typename BasicJsonType::object_t;
  4445. using array_t = typename BasicJsonType::array_t;
  4446. // make sure BasicJsonType is basic_json or const basic_json
  4447. static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,
  4448. "iter_impl only accepts (const) basic_json");
  4449. public:
  4450. /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.
  4451. /// The C++ Standard has never required user-defined iterators to derive from std::iterator.
  4452. /// A user-defined iterator should provide publicly accessible typedefs named
  4453. /// iterator_category, value_type, difference_type, pointer, and reference.
  4454. /// Note that value_type is required to be non-const, even for constant iterators.
  4455. using iterator_category = std::bidirectional_iterator_tag;
  4456. /// the type of the values when the iterator is dereferenced
  4457. using value_type = typename BasicJsonType::value_type;
  4458. /// a type to represent differences between iterators
  4459. using difference_type = typename BasicJsonType::difference_type;
  4460. /// defines a pointer to the type iterated over (value_type)
  4461. using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,
  4462. typename BasicJsonType::const_pointer,
  4463. typename BasicJsonType::pointer>::type;
  4464. /// defines a reference to the type iterated over (value_type)
  4465. using reference =
  4466. typename std::conditional<std::is_const<BasicJsonType>::value,
  4467. typename BasicJsonType::const_reference,
  4468. typename BasicJsonType::reference>::type;
  4469. /// default constructor
  4470. iter_impl() = default;
  4471. /*!
  4472. @brief constructor for a given JSON instance
  4473. @param[in] object pointer to a JSON object for this iterator
  4474. @pre object != nullptr
  4475. @post The iterator is initialized; i.e. `m_object != nullptr`.
  4476. */
  4477. explicit iter_impl(pointer object) noexcept : m_object(object)
  4478. {
  4479. assert(m_object != nullptr);
  4480. switch (m_object->m_type)
  4481. {
  4482. case value_t::object:
  4483. {
  4484. m_it.object_iterator = typename object_t::iterator();
  4485. break;
  4486. }
  4487. case value_t::array:
  4488. {
  4489. m_it.array_iterator = typename array_t::iterator();
  4490. break;
  4491. }
  4492. default:
  4493. {
  4494. m_it.primitive_iterator = primitive_iterator_t();
  4495. break;
  4496. }
  4497. }
  4498. }
  4499. /*!
  4500. @note The conventional copy constructor and copy assignment are implicitly
  4501. defined. Combined with the following converting constructor and
  4502. assignment, they support: (1) copy from iterator to iterator, (2)
  4503. copy from const iterator to const iterator, and (3) conversion from
  4504. iterator to const iterator. However conversion from const iterator
  4505. to iterator is not defined.
  4506. */
  4507. /*!
  4508. @brief converting constructor
  4509. @param[in] other non-const iterator to copy from
  4510. @note It is not checked whether @a other is initialized.
  4511. */
  4512. iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  4513. : m_object(other.m_object), m_it(other.m_it) {}
  4514. /*!
  4515. @brief converting assignment
  4516. @param[in,out] other non-const iterator to copy from
  4517. @return const/non-const iterator
  4518. @note It is not checked whether @a other is initialized.
  4519. */
  4520. iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept
  4521. {
  4522. m_object = other.m_object;
  4523. m_it = other.m_it;
  4524. return *this;
  4525. }
  4526. private:
  4527. /*!
  4528. @brief set the iterator to the first value
  4529. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4530. */
  4531. void set_begin() noexcept
  4532. {
  4533. assert(m_object != nullptr);
  4534. switch (m_object->m_type)
  4535. {
  4536. case value_t::object:
  4537. {
  4538. m_it.object_iterator = m_object->m_value.object->begin();
  4539. break;
  4540. }
  4541. case value_t::array:
  4542. {
  4543. m_it.array_iterator = m_object->m_value.array->begin();
  4544. break;
  4545. }
  4546. case value_t::null:
  4547. {
  4548. // set to end so begin()==end() is true: null is empty
  4549. m_it.primitive_iterator.set_end();
  4550. break;
  4551. }
  4552. default:
  4553. {
  4554. m_it.primitive_iterator.set_begin();
  4555. break;
  4556. }
  4557. }
  4558. }
  4559. /*!
  4560. @brief set the iterator past the last value
  4561. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4562. */
  4563. void set_end() noexcept
  4564. {
  4565. assert(m_object != nullptr);
  4566. switch (m_object->m_type)
  4567. {
  4568. case value_t::object:
  4569. {
  4570. m_it.object_iterator = m_object->m_value.object->end();
  4571. break;
  4572. }
  4573. case value_t::array:
  4574. {
  4575. m_it.array_iterator = m_object->m_value.array->end();
  4576. break;
  4577. }
  4578. default:
  4579. {
  4580. m_it.primitive_iterator.set_end();
  4581. break;
  4582. }
  4583. }
  4584. }
  4585. public:
  4586. /*!
  4587. @brief return a reference to the value pointed to by the iterator
  4588. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4589. */
  4590. reference operator*() const
  4591. {
  4592. assert(m_object != nullptr);
  4593. switch (m_object->m_type)
  4594. {
  4595. case value_t::object:
  4596. {
  4597. assert(m_it.object_iterator != m_object->m_value.object->end());
  4598. return m_it.object_iterator->second;
  4599. }
  4600. case value_t::array:
  4601. {
  4602. assert(m_it.array_iterator != m_object->m_value.array->end());
  4603. return *m_it.array_iterator;
  4604. }
  4605. case value_t::null:
  4606. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4607. default:
  4608. {
  4609. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  4610. {
  4611. return *m_object;
  4612. }
  4613. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4614. }
  4615. }
  4616. }
  4617. /*!
  4618. @brief dereference the iterator
  4619. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4620. */
  4621. pointer operator->() const
  4622. {
  4623. assert(m_object != nullptr);
  4624. switch (m_object->m_type)
  4625. {
  4626. case value_t::object:
  4627. {
  4628. assert(m_it.object_iterator != m_object->m_value.object->end());
  4629. return &(m_it.object_iterator->second);
  4630. }
  4631. case value_t::array:
  4632. {
  4633. assert(m_it.array_iterator != m_object->m_value.array->end());
  4634. return &*m_it.array_iterator;
  4635. }
  4636. default:
  4637. {
  4638. if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))
  4639. {
  4640. return m_object;
  4641. }
  4642. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4643. }
  4644. }
  4645. }
  4646. /*!
  4647. @brief post-increment (it++)
  4648. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4649. */
  4650. iter_impl const operator++(int)
  4651. {
  4652. auto result = *this;
  4653. ++(*this);
  4654. return result;
  4655. }
  4656. /*!
  4657. @brief pre-increment (++it)
  4658. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4659. */
  4660. iter_impl& operator++()
  4661. {
  4662. assert(m_object != nullptr);
  4663. switch (m_object->m_type)
  4664. {
  4665. case value_t::object:
  4666. {
  4667. std::advance(m_it.object_iterator, 1);
  4668. break;
  4669. }
  4670. case value_t::array:
  4671. {
  4672. std::advance(m_it.array_iterator, 1);
  4673. break;
  4674. }
  4675. default:
  4676. {
  4677. ++m_it.primitive_iterator;
  4678. break;
  4679. }
  4680. }
  4681. return *this;
  4682. }
  4683. /*!
  4684. @brief post-decrement (it--)
  4685. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4686. */
  4687. iter_impl const operator--(int)
  4688. {
  4689. auto result = *this;
  4690. --(*this);
  4691. return result;
  4692. }
  4693. /*!
  4694. @brief pre-decrement (--it)
  4695. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4696. */
  4697. iter_impl& operator--()
  4698. {
  4699. assert(m_object != nullptr);
  4700. switch (m_object->m_type)
  4701. {
  4702. case value_t::object:
  4703. {
  4704. std::advance(m_it.object_iterator, -1);
  4705. break;
  4706. }
  4707. case value_t::array:
  4708. {
  4709. std::advance(m_it.array_iterator, -1);
  4710. break;
  4711. }
  4712. default:
  4713. {
  4714. --m_it.primitive_iterator;
  4715. break;
  4716. }
  4717. }
  4718. return *this;
  4719. }
  4720. /*!
  4721. @brief comparison: equal
  4722. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4723. */
  4724. bool operator==(const iter_impl& other) const
  4725. {
  4726. // if objects are not the same, the comparison is undefined
  4727. if (JSON_UNLIKELY(m_object != other.m_object))
  4728. {
  4729. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  4730. }
  4731. assert(m_object != nullptr);
  4732. switch (m_object->m_type)
  4733. {
  4734. case value_t::object:
  4735. return (m_it.object_iterator == other.m_it.object_iterator);
  4736. case value_t::array:
  4737. return (m_it.array_iterator == other.m_it.array_iterator);
  4738. default:
  4739. return (m_it.primitive_iterator == other.m_it.primitive_iterator);
  4740. }
  4741. }
  4742. /*!
  4743. @brief comparison: not equal
  4744. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4745. */
  4746. bool operator!=(const iter_impl& other) const
  4747. {
  4748. return not operator==(other);
  4749. }
  4750. /*!
  4751. @brief comparison: smaller
  4752. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4753. */
  4754. bool operator<(const iter_impl& other) const
  4755. {
  4756. // if objects are not the same, the comparison is undefined
  4757. if (JSON_UNLIKELY(m_object != other.m_object))
  4758. {
  4759. JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers"));
  4760. }
  4761. assert(m_object != nullptr);
  4762. switch (m_object->m_type)
  4763. {
  4764. case value_t::object:
  4765. JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators"));
  4766. case value_t::array:
  4767. return (m_it.array_iterator < other.m_it.array_iterator);
  4768. default:
  4769. return (m_it.primitive_iterator < other.m_it.primitive_iterator);
  4770. }
  4771. }
  4772. /*!
  4773. @brief comparison: less than or equal
  4774. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4775. */
  4776. bool operator<=(const iter_impl& other) const
  4777. {
  4778. return not other.operator < (*this);
  4779. }
  4780. /*!
  4781. @brief comparison: greater than
  4782. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4783. */
  4784. bool operator>(const iter_impl& other) const
  4785. {
  4786. return not operator<=(other);
  4787. }
  4788. /*!
  4789. @brief comparison: greater than or equal
  4790. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4791. */
  4792. bool operator>=(const iter_impl& other) const
  4793. {
  4794. return not operator<(other);
  4795. }
  4796. /*!
  4797. @brief add to iterator
  4798. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4799. */
  4800. iter_impl& operator+=(difference_type i)
  4801. {
  4802. assert(m_object != nullptr);
  4803. switch (m_object->m_type)
  4804. {
  4805. case value_t::object:
  4806. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  4807. case value_t::array:
  4808. {
  4809. std::advance(m_it.array_iterator, i);
  4810. break;
  4811. }
  4812. default:
  4813. {
  4814. m_it.primitive_iterator += i;
  4815. break;
  4816. }
  4817. }
  4818. return *this;
  4819. }
  4820. /*!
  4821. @brief subtract from iterator
  4822. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4823. */
  4824. iter_impl& operator-=(difference_type i)
  4825. {
  4826. return operator+=(-i);
  4827. }
  4828. /*!
  4829. @brief add to iterator
  4830. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4831. */
  4832. iter_impl operator+(difference_type i) const
  4833. {
  4834. auto result = *this;
  4835. result += i;
  4836. return result;
  4837. }
  4838. /*!
  4839. @brief addition of distance and iterator
  4840. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4841. */
  4842. friend iter_impl operator+(difference_type i, const iter_impl& it)
  4843. {
  4844. auto result = it;
  4845. result += i;
  4846. return result;
  4847. }
  4848. /*!
  4849. @brief subtract from iterator
  4850. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4851. */
  4852. iter_impl operator-(difference_type i) const
  4853. {
  4854. auto result = *this;
  4855. result -= i;
  4856. return result;
  4857. }
  4858. /*!
  4859. @brief return difference
  4860. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4861. */
  4862. difference_type operator-(const iter_impl& other) const
  4863. {
  4864. assert(m_object != nullptr);
  4865. switch (m_object->m_type)
  4866. {
  4867. case value_t::object:
  4868. JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators"));
  4869. case value_t::array:
  4870. return m_it.array_iterator - other.m_it.array_iterator;
  4871. default:
  4872. return m_it.primitive_iterator - other.m_it.primitive_iterator;
  4873. }
  4874. }
  4875. /*!
  4876. @brief access to successor
  4877. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4878. */
  4879. reference operator[](difference_type n) const
  4880. {
  4881. assert(m_object != nullptr);
  4882. switch (m_object->m_type)
  4883. {
  4884. case value_t::object:
  4885. JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators"));
  4886. case value_t::array:
  4887. return *std::next(m_it.array_iterator, n);
  4888. case value_t::null:
  4889. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4890. default:
  4891. {
  4892. if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))
  4893. {
  4894. return *m_object;
  4895. }
  4896. JSON_THROW(invalid_iterator::create(214, "cannot get value"));
  4897. }
  4898. }
  4899. }
  4900. /*!
  4901. @brief return the key of an object iterator
  4902. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4903. */
  4904. const typename object_t::key_type& key() const
  4905. {
  4906. assert(m_object != nullptr);
  4907. if (JSON_LIKELY(m_object->is_object()))
  4908. {
  4909. return m_it.object_iterator->first;
  4910. }
  4911. JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators"));
  4912. }
  4913. /*!
  4914. @brief return the value of an iterator
  4915. @pre The iterator is initialized; i.e. `m_object != nullptr`.
  4916. */
  4917. reference value() const
  4918. {
  4919. return operator*();
  4920. }
  4921. private:
  4922. /// associated JSON instance
  4923. pointer m_object = nullptr;
  4924. /// the actual iterator of the associated instance
  4925. internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it;
  4926. };
  4927. }
  4928. }
  4929. // #include <nlohmann/detail/iterators/iteration_proxy.hpp>
  4930. // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
  4931. #include <cstddef> // ptrdiff_t
  4932. #include <iterator> // reverse_iterator
  4933. #include <utility> // declval
  4934. namespace nlohmann
  4935. {
  4936. namespace detail
  4937. {
  4938. //////////////////////
  4939. // reverse_iterator //
  4940. //////////////////////
  4941. /*!
  4942. @brief a template for a reverse iterator class
  4943. @tparam Base the base iterator type to reverse. Valid types are @ref
  4944. iterator (to create @ref reverse_iterator) and @ref const_iterator (to
  4945. create @ref const_reverse_iterator).
  4946. @requirement The class satisfies the following concept requirements:
  4947. -
  4948. [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator):
  4949. The iterator that can be moved can be moved in both directions (i.e.
  4950. incremented and decremented).
  4951. - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator):
  4952. It is possible to write to the pointed-to element (only if @a Base is
  4953. @ref iterator).
  4954. @since version 1.0.0
  4955. */
  4956. template<typename Base>
  4957. class json_reverse_iterator : public std::reverse_iterator<Base>
  4958. {
  4959. public:
  4960. using difference_type = std::ptrdiff_t;
  4961. /// shortcut to the reverse iterator adapter
  4962. using base_iterator = std::reverse_iterator<Base>;
  4963. /// the reference type for the pointed-to element
  4964. using reference = typename Base::reference;
  4965. /// create reverse iterator from iterator
  4966. explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
  4967. : base_iterator(it) {}
  4968. /// create reverse iterator from base class
  4969. explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}
  4970. /// post-increment (it++)
  4971. json_reverse_iterator const operator++(int)
  4972. {
  4973. return static_cast<json_reverse_iterator>(base_iterator::operator++(1));
  4974. }
  4975. /// pre-increment (++it)
  4976. json_reverse_iterator& operator++()
  4977. {
  4978. return static_cast<json_reverse_iterator&>(base_iterator::operator++());
  4979. }
  4980. /// post-decrement (it--)
  4981. json_reverse_iterator const operator--(int)
  4982. {
  4983. return static_cast<json_reverse_iterator>(base_iterator::operator--(1));
  4984. }
  4985. /// pre-decrement (--it)
  4986. json_reverse_iterator& operator--()
  4987. {
  4988. return static_cast<json_reverse_iterator&>(base_iterator::operator--());
  4989. }
  4990. /// add to iterator
  4991. json_reverse_iterator& operator+=(difference_type i)
  4992. {
  4993. return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));
  4994. }
  4995. /// add to iterator
  4996. json_reverse_iterator operator+(difference_type i) const
  4997. {
  4998. return static_cast<json_reverse_iterator>(base_iterator::operator+(i));
  4999. }
  5000. /// subtract from iterator
  5001. json_reverse_iterator operator-(difference_type i) const
  5002. {
  5003. return static_cast<json_reverse_iterator>(base_iterator::operator-(i));
  5004. }
  5005. /// return difference
  5006. difference_type operator-(const json_reverse_iterator& other) const
  5007. {
  5008. return base_iterator(*this) - base_iterator(other);
  5009. }
  5010. /// access to successor
  5011. reference operator[](difference_type n) const
  5012. {
  5013. return *(this->operator+(n));
  5014. }
  5015. /// return the key of an object iterator
  5016. auto key() const -> decltype(std::declval<Base>().key())
  5017. {
  5018. auto it = --this->base();
  5019. return it.key();
  5020. }
  5021. /// return the value of an iterator
  5022. reference value() const
  5023. {
  5024. auto it = --this->base();
  5025. return it.operator * ();
  5026. }
  5027. };
  5028. }
  5029. }
  5030. // #include <nlohmann/detail/output/output_adapters.hpp>
  5031. #include <algorithm> // copy
  5032. #include <cstddef> // size_t
  5033. #include <ios> // streamsize
  5034. #include <iterator> // back_inserter
  5035. #include <memory> // shared_ptr, make_shared
  5036. #include <ostream> // basic_ostream
  5037. #include <string> // basic_string
  5038. #include <vector> // vector
  5039. namespace nlohmann
  5040. {
  5041. namespace detail
  5042. {
  5043. /// abstract output adapter interface
  5044. template<typename CharType> struct output_adapter_protocol
  5045. {
  5046. virtual void write_character(CharType c) = 0;
  5047. virtual void write_characters(const CharType* s, std::size_t length) = 0;
  5048. virtual ~output_adapter_protocol() = default;
  5049. };
  5050. /// a type to simplify interfaces
  5051. template<typename CharType>
  5052. using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;
  5053. /// output adapter for byte vectors
  5054. template<typename CharType>
  5055. class output_vector_adapter : public output_adapter_protocol<CharType>
  5056. {
  5057. public:
  5058. explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}
  5059. void write_character(CharType c) override
  5060. {
  5061. v.push_back(c);
  5062. }
  5063. void write_characters(const CharType* s, std::size_t length) override
  5064. {
  5065. std::copy(s, s + length, std::back_inserter(v));
  5066. }
  5067. private:
  5068. std::vector<CharType>& v;
  5069. };
  5070. /// output adapter for output streams
  5071. template<typename CharType>
  5072. class output_stream_adapter : public output_adapter_protocol<CharType>
  5073. {
  5074. public:
  5075. explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}
  5076. void write_character(CharType c) override
  5077. {
  5078. stream.put(c);
  5079. }
  5080. void write_characters(const CharType* s, std::size_t length) override
  5081. {
  5082. stream.write(s, static_cast<std::streamsize>(length));
  5083. }
  5084. private:
  5085. std::basic_ostream<CharType>& stream;
  5086. };
  5087. /// output adapter for basic_string
  5088. template<typename CharType, typename StringType = std::basic_string<CharType>>
  5089. class output_string_adapter : public output_adapter_protocol<CharType>
  5090. {
  5091. public:
  5092. explicit output_string_adapter(StringType& s) : str(s) {}
  5093. void write_character(CharType c) override
  5094. {
  5095. str.push_back(c);
  5096. }
  5097. void write_characters(const CharType* s, std::size_t length) override
  5098. {
  5099. str.append(s, length);
  5100. }
  5101. private:
  5102. StringType& str;
  5103. };
  5104. template<typename CharType, typename StringType = std::basic_string<CharType>>
  5105. class output_adapter
  5106. {
  5107. public:
  5108. output_adapter(std::vector<CharType>& vec)
  5109. : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}
  5110. output_adapter(std::basic_ostream<CharType>& s)
  5111. : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}
  5112. output_adapter(StringType& s)
  5113. : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {}
  5114. operator output_adapter_t<CharType>()
  5115. {
  5116. return oa;
  5117. }
  5118. private:
  5119. output_adapter_t<CharType> oa = nullptr;
  5120. };
  5121. }
  5122. }
  5123. // #include <nlohmann/detail/input/binary_reader.hpp>
  5124. #include <algorithm> // generate_n
  5125. #include <array> // array
  5126. #include <cassert> // assert
  5127. #include <cmath> // ldexp
  5128. #include <cstddef> // size_t
  5129. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  5130. #include <cstdio> // snprintf
  5131. #include <cstring> // memcpy
  5132. #include <iterator> // back_inserter
  5133. #include <limits> // numeric_limits
  5134. #include <string> // char_traits, string
  5135. #include <utility> // make_pair, move
  5136. // #include <nlohmann/detail/input/input_adapters.hpp>
  5137. // #include <nlohmann/detail/input/json_sax.hpp>
  5138. // #include <nlohmann/detail/exceptions.hpp>
  5139. // #include <nlohmann/detail/macro_scope.hpp>
  5140. // #include <nlohmann/detail/meta/is_sax.hpp>
  5141. // #include <nlohmann/detail/value_t.hpp>
  5142. namespace nlohmann
  5143. {
  5144. namespace detail
  5145. {
  5146. ///////////////////
  5147. // binary reader //
  5148. ///////////////////
  5149. /*!
  5150. @brief deserialization of CBOR, MessagePack, and UBJSON values
  5151. */
  5152. template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>>
  5153. class binary_reader
  5154. {
  5155. using number_integer_t = typename BasicJsonType::number_integer_t;
  5156. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  5157. using number_float_t = typename BasicJsonType::number_float_t;
  5158. using string_t = typename BasicJsonType::string_t;
  5159. using json_sax_t = SAX;
  5160. public:
  5161. /*!
  5162. @brief create a binary reader
  5163. @param[in] adapter input adapter to read from
  5164. */
  5165. explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))
  5166. {
  5167. (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {};
  5168. assert(ia);
  5169. }
  5170. /*!
  5171. @param[in] format the binary format to parse
  5172. @param[in] sax_ a SAX event processor
  5173. @param[in] strict whether to expect the input to be consumed completed
  5174. @return
  5175. */
  5176. bool sax_parse(const input_format_t format,
  5177. json_sax_t* sax_,
  5178. const bool strict = true)
  5179. {
  5180. sax = sax_;
  5181. bool result = false;
  5182. switch (format)
  5183. {
  5184. case input_format_t::cbor:
  5185. result = parse_cbor_internal();
  5186. break;
  5187. case input_format_t::msgpack:
  5188. result = parse_msgpack_internal();
  5189. break;
  5190. case input_format_t::ubjson:
  5191. result = parse_ubjson_internal();
  5192. break;
  5193. // LCOV_EXCL_START
  5194. default:
  5195. assert(false);
  5196. // LCOV_EXCL_STOP
  5197. }
  5198. // strict mode: next byte must be EOF
  5199. if (result and strict)
  5200. {
  5201. if (format == input_format_t::ubjson)
  5202. {
  5203. get_ignore_noop();
  5204. }
  5205. else
  5206. {
  5207. get();
  5208. }
  5209. if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))
  5210. {
  5211. return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, "expected end of input"));
  5212. }
  5213. }
  5214. return result;
  5215. }
  5216. /*!
  5217. @brief determine system byte order
  5218. @return true if and only if system's byte order is little endian
  5219. @note from http://stackoverflow.com/a/1001328/266378
  5220. */
  5221. static constexpr bool little_endianess(int num = 1) noexcept
  5222. {
  5223. return (*reinterpret_cast<char*>(&num) == 1);
  5224. }
  5225. private:
  5226. /*!
  5227. @param[in] get_char whether a new character should be retrieved from the
  5228. input (true, default) or whether the last read
  5229. character should be considered instead
  5230. @return whether a valid CBOR value was passed to the SAX parser
  5231. */
  5232. bool parse_cbor_internal(const bool get_char = true)
  5233. {
  5234. switch (get_char ? get() : current)
  5235. {
  5236. // EOF
  5237. case std::char_traits<char>::eof():
  5238. return unexpect_eof();
  5239. // Integer 0x00..0x17 (0..23)
  5240. case 0x00:
  5241. case 0x01:
  5242. case 0x02:
  5243. case 0x03:
  5244. case 0x04:
  5245. case 0x05:
  5246. case 0x06:
  5247. case 0x07:
  5248. case 0x08:
  5249. case 0x09:
  5250. case 0x0A:
  5251. case 0x0B:
  5252. case 0x0C:
  5253. case 0x0D:
  5254. case 0x0E:
  5255. case 0x0F:
  5256. case 0x10:
  5257. case 0x11:
  5258. case 0x12:
  5259. case 0x13:
  5260. case 0x14:
  5261. case 0x15:
  5262. case 0x16:
  5263. case 0x17:
  5264. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5265. case 0x18: // Unsigned integer (one-byte uint8_t follows)
  5266. {
  5267. uint8_t number;
  5268. return get_number(number) and sax->number_unsigned(number);
  5269. }
  5270. case 0x19: // Unsigned integer (two-byte uint16_t follows)
  5271. {
  5272. uint16_t number;
  5273. return get_number(number) and sax->number_unsigned(number);
  5274. }
  5275. case 0x1A: // Unsigned integer (four-byte uint32_t follows)
  5276. {
  5277. uint32_t number;
  5278. return get_number(number) and sax->number_unsigned(number);
  5279. }
  5280. case 0x1B: // Unsigned integer (eight-byte uint64_t follows)
  5281. {
  5282. uint64_t number;
  5283. return get_number(number) and sax->number_unsigned(number);
  5284. }
  5285. // Negative integer -1-0x00..-1-0x17 (-1..-24)
  5286. case 0x20:
  5287. case 0x21:
  5288. case 0x22:
  5289. case 0x23:
  5290. case 0x24:
  5291. case 0x25:
  5292. case 0x26:
  5293. case 0x27:
  5294. case 0x28:
  5295. case 0x29:
  5296. case 0x2A:
  5297. case 0x2B:
  5298. case 0x2C:
  5299. case 0x2D:
  5300. case 0x2E:
  5301. case 0x2F:
  5302. case 0x30:
  5303. case 0x31:
  5304. case 0x32:
  5305. case 0x33:
  5306. case 0x34:
  5307. case 0x35:
  5308. case 0x36:
  5309. case 0x37:
  5310. return sax->number_integer(static_cast<int8_t>(0x20 - 1 - current));
  5311. case 0x38: // Negative integer (one-byte uint8_t follows)
  5312. {
  5313. uint8_t number;
  5314. return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5315. }
  5316. case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
  5317. {
  5318. uint16_t number;
  5319. return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5320. }
  5321. case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)
  5322. {
  5323. uint32_t number;
  5324. return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1) - number);
  5325. }
  5326. case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)
  5327. {
  5328. uint64_t number;
  5329. return get_number(number) and sax->number_integer(static_cast<number_integer_t>(-1)
  5330. - static_cast<number_integer_t>(number));
  5331. }
  5332. // UTF-8 string (0x00..0x17 bytes follow)
  5333. case 0x60:
  5334. case 0x61:
  5335. case 0x62:
  5336. case 0x63:
  5337. case 0x64:
  5338. case 0x65:
  5339. case 0x66:
  5340. case 0x67:
  5341. case 0x68:
  5342. case 0x69:
  5343. case 0x6A:
  5344. case 0x6B:
  5345. case 0x6C:
  5346. case 0x6D:
  5347. case 0x6E:
  5348. case 0x6F:
  5349. case 0x70:
  5350. case 0x71:
  5351. case 0x72:
  5352. case 0x73:
  5353. case 0x74:
  5354. case 0x75:
  5355. case 0x76:
  5356. case 0x77:
  5357. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  5358. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  5359. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  5360. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  5361. case 0x7F: // UTF-8 string (indefinite length)
  5362. {
  5363. string_t s;
  5364. return get_cbor_string(s) and sax->string(s);
  5365. }
  5366. // array (0x00..0x17 data items follow)
  5367. case 0x80:
  5368. case 0x81:
  5369. case 0x82:
  5370. case 0x83:
  5371. case 0x84:
  5372. case 0x85:
  5373. case 0x86:
  5374. case 0x87:
  5375. case 0x88:
  5376. case 0x89:
  5377. case 0x8A:
  5378. case 0x8B:
  5379. case 0x8C:
  5380. case 0x8D:
  5381. case 0x8E:
  5382. case 0x8F:
  5383. case 0x90:
  5384. case 0x91:
  5385. case 0x92:
  5386. case 0x93:
  5387. case 0x94:
  5388. case 0x95:
  5389. case 0x96:
  5390. case 0x97:
  5391. return get_cbor_array(static_cast<std::size_t>(current & 0x1F));
  5392. case 0x98: // array (one-byte uint8_t for n follows)
  5393. {
  5394. uint8_t len;
  5395. return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
  5396. }
  5397. case 0x99: // array (two-byte uint16_t for n follow)
  5398. {
  5399. uint16_t len;
  5400. return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
  5401. }
  5402. case 0x9A: // array (four-byte uint32_t for n follow)
  5403. {
  5404. uint32_t len;
  5405. return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
  5406. }
  5407. case 0x9B: // array (eight-byte uint64_t for n follow)
  5408. {
  5409. uint64_t len;
  5410. return get_number(len) and get_cbor_array(static_cast<std::size_t>(len));
  5411. }
  5412. case 0x9F: // array (indefinite length)
  5413. return get_cbor_array(std::size_t(-1));
  5414. // map (0x00..0x17 pairs of data items follow)
  5415. case 0xA0:
  5416. case 0xA1:
  5417. case 0xA2:
  5418. case 0xA3:
  5419. case 0xA4:
  5420. case 0xA5:
  5421. case 0xA6:
  5422. case 0xA7:
  5423. case 0xA8:
  5424. case 0xA9:
  5425. case 0xAA:
  5426. case 0xAB:
  5427. case 0xAC:
  5428. case 0xAD:
  5429. case 0xAE:
  5430. case 0xAF:
  5431. case 0xB0:
  5432. case 0xB1:
  5433. case 0xB2:
  5434. case 0xB3:
  5435. case 0xB4:
  5436. case 0xB5:
  5437. case 0xB6:
  5438. case 0xB7:
  5439. return get_cbor_object(static_cast<std::size_t>(current & 0x1F));
  5440. case 0xB8: // map (one-byte uint8_t for n follows)
  5441. {
  5442. uint8_t len;
  5443. return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
  5444. }
  5445. case 0xB9: // map (two-byte uint16_t for n follow)
  5446. {
  5447. uint16_t len;
  5448. return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
  5449. }
  5450. case 0xBA: // map (four-byte uint32_t for n follow)
  5451. {
  5452. uint32_t len;
  5453. return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
  5454. }
  5455. case 0xBB: // map (eight-byte uint64_t for n follow)
  5456. {
  5457. uint64_t len;
  5458. return get_number(len) and get_cbor_object(static_cast<std::size_t>(len));
  5459. }
  5460. case 0xBF: // map (indefinite length)
  5461. return get_cbor_object(std::size_t(-1));
  5462. case 0xF4: // false
  5463. return sax->boolean(false);
  5464. case 0xF5: // true
  5465. return sax->boolean(true);
  5466. case 0xF6: // null
  5467. return sax->null();
  5468. case 0xF9: // Half-Precision Float (two-byte IEEE 754)
  5469. {
  5470. const int byte1 = get();
  5471. if (JSON_UNLIKELY(not unexpect_eof()))
  5472. {
  5473. return false;
  5474. }
  5475. const int byte2 = get();
  5476. if (JSON_UNLIKELY(not unexpect_eof()))
  5477. {
  5478. return false;
  5479. }
  5480. // code from RFC 7049, Appendix D, Figure 3:
  5481. // As half-precision floating-point numbers were only added
  5482. // to IEEE 754 in 2008, today's programming platforms often
  5483. // still only have limited support for them. It is very
  5484. // easy to include at least decoding support for them even
  5485. // without such support. An example of a small decoder for
  5486. // half-precision floating-point numbers in the C language
  5487. // is shown in Fig. 3.
  5488. const int half = (byte1 << 8) + byte2;
  5489. const double val = [&half]
  5490. {
  5491. const int exp = (half >> 10) & 0x1F;
  5492. const int mant = half & 0x3FF;
  5493. assert(0 <= exp and exp <= 32);
  5494. assert(0 <= mant and mant <= 1024);
  5495. switch (exp)
  5496. {
  5497. case 0:
  5498. return std::ldexp(mant, -24);
  5499. case 31:
  5500. return (mant == 0)
  5501. ? std::numeric_limits<double>::infinity()
  5502. : std::numeric_limits<double>::quiet_NaN();
  5503. default:
  5504. return std::ldexp(mant + 1024, exp - 25);
  5505. }
  5506. }();
  5507. return sax->number_float((half & 0x8000) != 0
  5508. ? static_cast<number_float_t>(-val)
  5509. : static_cast<number_float_t>(val), "");
  5510. }
  5511. case 0xFA: // Single-Precision Float (four-byte IEEE 754)
  5512. {
  5513. float number;
  5514. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  5515. }
  5516. case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
  5517. {
  5518. double number;
  5519. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  5520. }
  5521. default: // anything else (0xFF is handled inside the other types)
  5522. {
  5523. auto last_token = get_token_string();
  5524. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading CBOR; last byte: 0x" + last_token));
  5525. }
  5526. }
  5527. }
  5528. /*!
  5529. @return whether a valid MessagePack value was passed to the SAX parser
  5530. */
  5531. bool parse_msgpack_internal()
  5532. {
  5533. switch (get())
  5534. {
  5535. // EOF
  5536. case std::char_traits<char>::eof():
  5537. return unexpect_eof();
  5538. // positive fixint
  5539. case 0x00:
  5540. case 0x01:
  5541. case 0x02:
  5542. case 0x03:
  5543. case 0x04:
  5544. case 0x05:
  5545. case 0x06:
  5546. case 0x07:
  5547. case 0x08:
  5548. case 0x09:
  5549. case 0x0A:
  5550. case 0x0B:
  5551. case 0x0C:
  5552. case 0x0D:
  5553. case 0x0E:
  5554. case 0x0F:
  5555. case 0x10:
  5556. case 0x11:
  5557. case 0x12:
  5558. case 0x13:
  5559. case 0x14:
  5560. case 0x15:
  5561. case 0x16:
  5562. case 0x17:
  5563. case 0x18:
  5564. case 0x19:
  5565. case 0x1A:
  5566. case 0x1B:
  5567. case 0x1C:
  5568. case 0x1D:
  5569. case 0x1E:
  5570. case 0x1F:
  5571. case 0x20:
  5572. case 0x21:
  5573. case 0x22:
  5574. case 0x23:
  5575. case 0x24:
  5576. case 0x25:
  5577. case 0x26:
  5578. case 0x27:
  5579. case 0x28:
  5580. case 0x29:
  5581. case 0x2A:
  5582. case 0x2B:
  5583. case 0x2C:
  5584. case 0x2D:
  5585. case 0x2E:
  5586. case 0x2F:
  5587. case 0x30:
  5588. case 0x31:
  5589. case 0x32:
  5590. case 0x33:
  5591. case 0x34:
  5592. case 0x35:
  5593. case 0x36:
  5594. case 0x37:
  5595. case 0x38:
  5596. case 0x39:
  5597. case 0x3A:
  5598. case 0x3B:
  5599. case 0x3C:
  5600. case 0x3D:
  5601. case 0x3E:
  5602. case 0x3F:
  5603. case 0x40:
  5604. case 0x41:
  5605. case 0x42:
  5606. case 0x43:
  5607. case 0x44:
  5608. case 0x45:
  5609. case 0x46:
  5610. case 0x47:
  5611. case 0x48:
  5612. case 0x49:
  5613. case 0x4A:
  5614. case 0x4B:
  5615. case 0x4C:
  5616. case 0x4D:
  5617. case 0x4E:
  5618. case 0x4F:
  5619. case 0x50:
  5620. case 0x51:
  5621. case 0x52:
  5622. case 0x53:
  5623. case 0x54:
  5624. case 0x55:
  5625. case 0x56:
  5626. case 0x57:
  5627. case 0x58:
  5628. case 0x59:
  5629. case 0x5A:
  5630. case 0x5B:
  5631. case 0x5C:
  5632. case 0x5D:
  5633. case 0x5E:
  5634. case 0x5F:
  5635. case 0x60:
  5636. case 0x61:
  5637. case 0x62:
  5638. case 0x63:
  5639. case 0x64:
  5640. case 0x65:
  5641. case 0x66:
  5642. case 0x67:
  5643. case 0x68:
  5644. case 0x69:
  5645. case 0x6A:
  5646. case 0x6B:
  5647. case 0x6C:
  5648. case 0x6D:
  5649. case 0x6E:
  5650. case 0x6F:
  5651. case 0x70:
  5652. case 0x71:
  5653. case 0x72:
  5654. case 0x73:
  5655. case 0x74:
  5656. case 0x75:
  5657. case 0x76:
  5658. case 0x77:
  5659. case 0x78:
  5660. case 0x79:
  5661. case 0x7A:
  5662. case 0x7B:
  5663. case 0x7C:
  5664. case 0x7D:
  5665. case 0x7E:
  5666. case 0x7F:
  5667. return sax->number_unsigned(static_cast<number_unsigned_t>(current));
  5668. // fixmap
  5669. case 0x80:
  5670. case 0x81:
  5671. case 0x82:
  5672. case 0x83:
  5673. case 0x84:
  5674. case 0x85:
  5675. case 0x86:
  5676. case 0x87:
  5677. case 0x88:
  5678. case 0x89:
  5679. case 0x8A:
  5680. case 0x8B:
  5681. case 0x8C:
  5682. case 0x8D:
  5683. case 0x8E:
  5684. case 0x8F:
  5685. return get_msgpack_object(static_cast<std::size_t>(current & 0x0F));
  5686. // fixarray
  5687. case 0x90:
  5688. case 0x91:
  5689. case 0x92:
  5690. case 0x93:
  5691. case 0x94:
  5692. case 0x95:
  5693. case 0x96:
  5694. case 0x97:
  5695. case 0x98:
  5696. case 0x99:
  5697. case 0x9A:
  5698. case 0x9B:
  5699. case 0x9C:
  5700. case 0x9D:
  5701. case 0x9E:
  5702. case 0x9F:
  5703. return get_msgpack_array(static_cast<std::size_t>(current & 0x0F));
  5704. // fixstr
  5705. case 0xA0:
  5706. case 0xA1:
  5707. case 0xA2:
  5708. case 0xA3:
  5709. case 0xA4:
  5710. case 0xA5:
  5711. case 0xA6:
  5712. case 0xA7:
  5713. case 0xA8:
  5714. case 0xA9:
  5715. case 0xAA:
  5716. case 0xAB:
  5717. case 0xAC:
  5718. case 0xAD:
  5719. case 0xAE:
  5720. case 0xAF:
  5721. case 0xB0:
  5722. case 0xB1:
  5723. case 0xB2:
  5724. case 0xB3:
  5725. case 0xB4:
  5726. case 0xB5:
  5727. case 0xB6:
  5728. case 0xB7:
  5729. case 0xB8:
  5730. case 0xB9:
  5731. case 0xBA:
  5732. case 0xBB:
  5733. case 0xBC:
  5734. case 0xBD:
  5735. case 0xBE:
  5736. case 0xBF:
  5737. {
  5738. string_t s;
  5739. return get_msgpack_string(s) and sax->string(s);
  5740. }
  5741. case 0xC0: // nil
  5742. return sax->null();
  5743. case 0xC2: // false
  5744. return sax->boolean(false);
  5745. case 0xC3: // true
  5746. return sax->boolean(true);
  5747. case 0xCA: // float 32
  5748. {
  5749. float number;
  5750. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  5751. }
  5752. case 0xCB: // float 64
  5753. {
  5754. double number;
  5755. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  5756. }
  5757. case 0xCC: // uint 8
  5758. {
  5759. uint8_t number;
  5760. return get_number(number) and sax->number_unsigned(number);
  5761. }
  5762. case 0xCD: // uint 16
  5763. {
  5764. uint16_t number;
  5765. return get_number(number) and sax->number_unsigned(number);
  5766. }
  5767. case 0xCE: // uint 32
  5768. {
  5769. uint32_t number;
  5770. return get_number(number) and sax->number_unsigned(number);
  5771. }
  5772. case 0xCF: // uint 64
  5773. {
  5774. uint64_t number;
  5775. return get_number(number) and sax->number_unsigned(number);
  5776. }
  5777. case 0xD0: // int 8
  5778. {
  5779. int8_t number;
  5780. return get_number(number) and sax->number_integer(number);
  5781. }
  5782. case 0xD1: // int 16
  5783. {
  5784. int16_t number;
  5785. return get_number(number) and sax->number_integer(number);
  5786. }
  5787. case 0xD2: // int 32
  5788. {
  5789. int32_t number;
  5790. return get_number(number) and sax->number_integer(number);
  5791. }
  5792. case 0xD3: // int 64
  5793. {
  5794. int64_t number;
  5795. return get_number(number) and sax->number_integer(number);
  5796. }
  5797. case 0xD9: // str 8
  5798. case 0xDA: // str 16
  5799. case 0xDB: // str 32
  5800. {
  5801. string_t s;
  5802. return get_msgpack_string(s) and sax->string(s);
  5803. }
  5804. case 0xDC: // array 16
  5805. {
  5806. uint16_t len;
  5807. return get_number(len) and get_msgpack_array(static_cast<std::size_t>(len));
  5808. }
  5809. case 0xDD: // array 32
  5810. {
  5811. uint32_t len;
  5812. return get_number(len) and get_msgpack_array(static_cast<std::size_t>(len));
  5813. }
  5814. case 0xDE: // map 16
  5815. {
  5816. uint16_t len;
  5817. return get_number(len) and get_msgpack_object(static_cast<std::size_t>(len));
  5818. }
  5819. case 0xDF: // map 32
  5820. {
  5821. uint32_t len;
  5822. return get_number(len) and get_msgpack_object(static_cast<std::size_t>(len));
  5823. }
  5824. // negative fixint
  5825. case 0xE0:
  5826. case 0xE1:
  5827. case 0xE2:
  5828. case 0xE3:
  5829. case 0xE4:
  5830. case 0xE5:
  5831. case 0xE6:
  5832. case 0xE7:
  5833. case 0xE8:
  5834. case 0xE9:
  5835. case 0xEA:
  5836. case 0xEB:
  5837. case 0xEC:
  5838. case 0xED:
  5839. case 0xEE:
  5840. case 0xEF:
  5841. case 0xF0:
  5842. case 0xF1:
  5843. case 0xF2:
  5844. case 0xF3:
  5845. case 0xF4:
  5846. case 0xF5:
  5847. case 0xF6:
  5848. case 0xF7:
  5849. case 0xF8:
  5850. case 0xF9:
  5851. case 0xFA:
  5852. case 0xFB:
  5853. case 0xFC:
  5854. case 0xFD:
  5855. case 0xFE:
  5856. case 0xFF:
  5857. return sax->number_integer(static_cast<int8_t>(current));
  5858. default: // anything else
  5859. {
  5860. auto last_token = get_token_string();
  5861. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading MessagePack; last byte: 0x" + last_token));
  5862. }
  5863. }
  5864. }
  5865. /*!
  5866. @param[in] get_char whether a new character should be retrieved from the
  5867. input (true, default) or whether the last read
  5868. character should be considered instead
  5869. @return whether a valid UBJSON value was passed to the SAX parser
  5870. */
  5871. bool parse_ubjson_internal(const bool get_char = true)
  5872. {
  5873. return get_ubjson_value(get_char ? get_ignore_noop() : current);
  5874. }
  5875. /*!
  5876. @brief get next character from the input
  5877. This function provides the interface to the used input adapter. It does
  5878. not throw in case the input reached EOF, but returns a -'ve valued
  5879. `std::char_traits<char>::eof()` in that case.
  5880. @return character read from the input
  5881. */
  5882. int get()
  5883. {
  5884. ++chars_read;
  5885. return (current = ia->get_character());
  5886. }
  5887. /*!
  5888. @return character read from the input after ignoring all 'N' entries
  5889. */
  5890. int get_ignore_noop()
  5891. {
  5892. do
  5893. {
  5894. get();
  5895. }
  5896. while (current == 'N');
  5897. return current;
  5898. }
  5899. /*
  5900. @brief read a number from the input
  5901. @tparam NumberType the type of the number
  5902. @param[out] result number of type @a NumberType
  5903. @return whether conversion completed
  5904. @note This function needs to respect the system's endianess, because
  5905. bytes in CBOR, MessagePack, and UBJSON are stored in network order
  5906. (big endian) and therefore need reordering on little endian systems.
  5907. */
  5908. template<typename NumberType>
  5909. bool get_number(NumberType& result)
  5910. {
  5911. // step 1: read input into array with system's byte order
  5912. std::array<uint8_t, sizeof(NumberType)> vec;
  5913. for (std::size_t i = 0; i < sizeof(NumberType); ++i)
  5914. {
  5915. get();
  5916. if (JSON_UNLIKELY(not unexpect_eof()))
  5917. {
  5918. return false;
  5919. }
  5920. // reverse byte order prior to conversion if necessary
  5921. if (is_little_endian)
  5922. {
  5923. vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);
  5924. }
  5925. else
  5926. {
  5927. vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE
  5928. }
  5929. }
  5930. // step 2: convert array into number of type T and return
  5931. std::memcpy(&result, vec.data(), sizeof(NumberType));
  5932. return true;
  5933. }
  5934. /*!
  5935. @brief create a string by reading characters from the input
  5936. @tparam NumberType the type of the number
  5937. @param[in] len number of characters to read
  5938. @param[out] string created by reading @a len bytes
  5939. @return whether string creation completed
  5940. @note We can not reserve @a len bytes for the result, because @a len
  5941. may be too large. Usually, @ref unexpect_eof() detects the end of
  5942. the input before we run out of string memory.
  5943. */
  5944. template<typename NumberType>
  5945. bool get_string(const NumberType len, string_t& result)
  5946. {
  5947. bool success = true;
  5948. std::generate_n(std::back_inserter(result), len, [this, &success]()
  5949. {
  5950. get();
  5951. if (JSON_UNLIKELY(not unexpect_eof()))
  5952. {
  5953. success = false;
  5954. }
  5955. return static_cast<char>(current);
  5956. });
  5957. return success;
  5958. }
  5959. /*!
  5960. @brief reads a CBOR string
  5961. This function first reads starting bytes to determine the expected
  5962. string length and then copies this number of bytes into a string.
  5963. Additionally, CBOR's strings with indefinite lengths are supported.
  5964. @param[out] result created string
  5965. @return whether string creation completed
  5966. */
  5967. bool get_cbor_string(string_t& result)
  5968. {
  5969. if (JSON_UNLIKELY(not unexpect_eof()))
  5970. {
  5971. return false;
  5972. }
  5973. switch (current)
  5974. {
  5975. // UTF-8 string (0x00..0x17 bytes follow)
  5976. case 0x60:
  5977. case 0x61:
  5978. case 0x62:
  5979. case 0x63:
  5980. case 0x64:
  5981. case 0x65:
  5982. case 0x66:
  5983. case 0x67:
  5984. case 0x68:
  5985. case 0x69:
  5986. case 0x6A:
  5987. case 0x6B:
  5988. case 0x6C:
  5989. case 0x6D:
  5990. case 0x6E:
  5991. case 0x6F:
  5992. case 0x70:
  5993. case 0x71:
  5994. case 0x72:
  5995. case 0x73:
  5996. case 0x74:
  5997. case 0x75:
  5998. case 0x76:
  5999. case 0x77:
  6000. {
  6001. return get_string(current & 0x1F, result);
  6002. }
  6003. case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
  6004. {
  6005. uint8_t len;
  6006. return get_number(len) and get_string(len, result);
  6007. }
  6008. case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
  6009. {
  6010. uint16_t len;
  6011. return get_number(len) and get_string(len, result);
  6012. }
  6013. case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)
  6014. {
  6015. uint32_t len;
  6016. return get_number(len) and get_string(len, result);
  6017. }
  6018. case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)
  6019. {
  6020. uint64_t len;
  6021. return get_number(len) and get_string(len, result);
  6022. }
  6023. case 0x7F: // UTF-8 string (indefinite length)
  6024. {
  6025. while (get() != 0xFF)
  6026. {
  6027. string_t chunk;
  6028. if (not get_cbor_string(chunk))
  6029. {
  6030. return false;
  6031. }
  6032. result.append(chunk);
  6033. }
  6034. return true;
  6035. }
  6036. default:
  6037. {
  6038. auto last_token = get_token_string();
  6039. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a CBOR string; last byte: 0x" + last_token));
  6040. }
  6041. }
  6042. }
  6043. /*!
  6044. @param[in] len the length of the array or std::size_t(-1) for an
  6045. array of indefinite size
  6046. @return whether array creation completed
  6047. */
  6048. bool get_cbor_array(const std::size_t len)
  6049. {
  6050. if (JSON_UNLIKELY(not sax->start_array(len)))
  6051. {
  6052. return false;
  6053. }
  6054. if (len != std::size_t(-1))
  6055. for (std::size_t i = 0; i < len; ++i)
  6056. {
  6057. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6058. {
  6059. return false;
  6060. }
  6061. }
  6062. else
  6063. {
  6064. while (get() != 0xFF)
  6065. {
  6066. if (JSON_UNLIKELY(not parse_cbor_internal(false)))
  6067. {
  6068. return false;
  6069. }
  6070. }
  6071. }
  6072. return sax->end_array();
  6073. }
  6074. /*!
  6075. @param[in] len the length of the object or std::size_t(-1) for an
  6076. object of indefinite size
  6077. @return whether object creation completed
  6078. */
  6079. bool get_cbor_object(const std::size_t len)
  6080. {
  6081. if (not JSON_UNLIKELY(sax->start_object(len)))
  6082. {
  6083. return false;
  6084. }
  6085. string_t key;
  6086. if (len != std::size_t(-1))
  6087. {
  6088. for (std::size_t i = 0; i < len; ++i)
  6089. {
  6090. get();
  6091. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  6092. {
  6093. return false;
  6094. }
  6095. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6096. {
  6097. return false;
  6098. }
  6099. key.clear();
  6100. }
  6101. }
  6102. else
  6103. {
  6104. while (get() != 0xFF)
  6105. {
  6106. if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key)))
  6107. {
  6108. return false;
  6109. }
  6110. if (JSON_UNLIKELY(not parse_cbor_internal()))
  6111. {
  6112. return false;
  6113. }
  6114. key.clear();
  6115. }
  6116. }
  6117. return sax->end_object();
  6118. }
  6119. /*!
  6120. @brief reads a MessagePack string
  6121. This function first reads starting bytes to determine the expected
  6122. string length and then copies this number of bytes into a string.
  6123. @param[out] result created string
  6124. @return whether string creation completed
  6125. */
  6126. bool get_msgpack_string(string_t& result)
  6127. {
  6128. if (JSON_UNLIKELY(not unexpect_eof()))
  6129. {
  6130. return false;
  6131. }
  6132. switch (current)
  6133. {
  6134. // fixstr
  6135. case 0xA0:
  6136. case 0xA1:
  6137. case 0xA2:
  6138. case 0xA3:
  6139. case 0xA4:
  6140. case 0xA5:
  6141. case 0xA6:
  6142. case 0xA7:
  6143. case 0xA8:
  6144. case 0xA9:
  6145. case 0xAA:
  6146. case 0xAB:
  6147. case 0xAC:
  6148. case 0xAD:
  6149. case 0xAE:
  6150. case 0xAF:
  6151. case 0xB0:
  6152. case 0xB1:
  6153. case 0xB2:
  6154. case 0xB3:
  6155. case 0xB4:
  6156. case 0xB5:
  6157. case 0xB6:
  6158. case 0xB7:
  6159. case 0xB8:
  6160. case 0xB9:
  6161. case 0xBA:
  6162. case 0xBB:
  6163. case 0xBC:
  6164. case 0xBD:
  6165. case 0xBE:
  6166. case 0xBF:
  6167. {
  6168. return get_string(current & 0x1F, result);
  6169. }
  6170. case 0xD9: // str 8
  6171. {
  6172. uint8_t len;
  6173. return get_number(len) and get_string(len, result);
  6174. }
  6175. case 0xDA: // str 16
  6176. {
  6177. uint16_t len;
  6178. return get_number(len) and get_string(len, result);
  6179. }
  6180. case 0xDB: // str 32
  6181. {
  6182. uint32_t len;
  6183. return get_number(len) and get_string(len, result);
  6184. }
  6185. default:
  6186. {
  6187. auto last_token = get_token_string();
  6188. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a MessagePack string; last byte: 0x" + last_token));
  6189. }
  6190. }
  6191. }
  6192. /*!
  6193. @param[in] len the length of the array
  6194. @return whether array creation completed
  6195. */
  6196. bool get_msgpack_array(const std::size_t len)
  6197. {
  6198. if (JSON_UNLIKELY(not sax->start_array(len)))
  6199. {
  6200. return false;
  6201. }
  6202. for (std::size_t i = 0; i < len; ++i)
  6203. {
  6204. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  6205. {
  6206. return false;
  6207. }
  6208. }
  6209. return sax->end_array();
  6210. }
  6211. /*!
  6212. @param[in] len the length of the object
  6213. @return whether object creation completed
  6214. */
  6215. bool get_msgpack_object(const std::size_t len)
  6216. {
  6217. if (JSON_UNLIKELY(not sax->start_object(len)))
  6218. {
  6219. return false;
  6220. }
  6221. string_t key;
  6222. for (std::size_t i = 0; i < len; ++i)
  6223. {
  6224. get();
  6225. if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key)))
  6226. {
  6227. return false;
  6228. }
  6229. if (JSON_UNLIKELY(not parse_msgpack_internal()))
  6230. {
  6231. return false;
  6232. }
  6233. key.clear();
  6234. }
  6235. return sax->end_object();
  6236. }
  6237. /*!
  6238. @brief reads a UBJSON string
  6239. This function is either called after reading the 'S' byte explicitly
  6240. indicating a string, or in case of an object key where the 'S' byte can be
  6241. left out.
  6242. @param[out] result created string
  6243. @param[in] get_char whether a new character should be retrieved from the
  6244. input (true, default) or whether the last read
  6245. character should be considered instead
  6246. @return whether string creation completed
  6247. */
  6248. bool get_ubjson_string(string_t& result, const bool get_char = true)
  6249. {
  6250. if (get_char)
  6251. {
  6252. get(); // TODO: may we ignore N here?
  6253. }
  6254. if (JSON_UNLIKELY(not unexpect_eof()))
  6255. {
  6256. return false;
  6257. }
  6258. switch (current)
  6259. {
  6260. case 'U':
  6261. {
  6262. uint8_t len;
  6263. return get_number(len) and get_string(len, result);
  6264. }
  6265. case 'i':
  6266. {
  6267. int8_t len;
  6268. return get_number(len) and get_string(len, result);
  6269. }
  6270. case 'I':
  6271. {
  6272. int16_t len;
  6273. return get_number(len) and get_string(len, result);
  6274. }
  6275. case 'l':
  6276. {
  6277. int32_t len;
  6278. return get_number(len) and get_string(len, result);
  6279. }
  6280. case 'L':
  6281. {
  6282. int64_t len;
  6283. return get_number(len) and get_string(len, result);
  6284. }
  6285. default:
  6286. auto last_token = get_token_string();
  6287. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "expected a UBJSON string; last byte: 0x" + last_token));
  6288. }
  6289. }
  6290. /*!
  6291. @param[out] result determined size
  6292. @return whether size determination completed
  6293. */
  6294. bool get_ubjson_size_value(std::size_t& result)
  6295. {
  6296. switch (get_ignore_noop())
  6297. {
  6298. case 'U':
  6299. {
  6300. uint8_t number;
  6301. if (JSON_UNLIKELY(not get_number(number)))
  6302. {
  6303. return false;
  6304. }
  6305. result = static_cast<std::size_t>(number);
  6306. return true;
  6307. }
  6308. case 'i':
  6309. {
  6310. int8_t number;
  6311. if (JSON_UNLIKELY(not get_number(number)))
  6312. {
  6313. return false;
  6314. }
  6315. result = static_cast<std::size_t>(number);
  6316. return true;
  6317. }
  6318. case 'I':
  6319. {
  6320. int16_t number;
  6321. if (JSON_UNLIKELY(not get_number(number)))
  6322. {
  6323. return false;
  6324. }
  6325. result = static_cast<std::size_t>(number);
  6326. return true;
  6327. }
  6328. case 'l':
  6329. {
  6330. int32_t number;
  6331. if (JSON_UNLIKELY(not get_number(number)))
  6332. {
  6333. return false;
  6334. }
  6335. result = static_cast<std::size_t>(number);
  6336. return true;
  6337. }
  6338. case 'L':
  6339. {
  6340. int64_t number;
  6341. if (JSON_UNLIKELY(not get_number(number)))
  6342. {
  6343. return false;
  6344. }
  6345. result = static_cast<std::size_t>(number);
  6346. return true;
  6347. }
  6348. default:
  6349. {
  6350. auto last_token = get_token_string();
  6351. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after '#' must denote a number type; last byte: 0x" + last_token));
  6352. }
  6353. }
  6354. }
  6355. /*!
  6356. @brief determine the type and size for a container
  6357. In the optimized UBJSON format, a type and a size can be provided to allow
  6358. for a more compact representation.
  6359. @param[out] result pair of the size and the type
  6360. @return whether pair creation completed
  6361. */
  6362. bool get_ubjson_size_type(std::pair<std::size_t, int>& result)
  6363. {
  6364. result.first = string_t::npos; // size
  6365. result.second = 0; // type
  6366. get_ignore_noop();
  6367. if (current == '$')
  6368. {
  6369. result.second = get(); // must not ignore 'N', because 'N' maybe the type
  6370. if (JSON_UNLIKELY(not unexpect_eof()))
  6371. {
  6372. return false;
  6373. }
  6374. get_ignore_noop();
  6375. if (JSON_UNLIKELY(current != '#'))
  6376. {
  6377. if (JSON_UNLIKELY(not unexpect_eof()))
  6378. {
  6379. return false;
  6380. }
  6381. auto last_token = get_token_string();
  6382. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "expected '#' after UBJSON type information; last byte: 0x" + last_token));
  6383. }
  6384. return get_ubjson_size_value(result.first);
  6385. }
  6386. else if (current == '#')
  6387. {
  6388. return get_ubjson_size_value(result.first);
  6389. }
  6390. return true;
  6391. }
  6392. /*!
  6393. @param prefix the previously read or set type prefix
  6394. @return whether value creation completed
  6395. */
  6396. bool get_ubjson_value(const int prefix)
  6397. {
  6398. switch (prefix)
  6399. {
  6400. case std::char_traits<char>::eof(): // EOF
  6401. return unexpect_eof();
  6402. case 'T': // true
  6403. return sax->boolean(true);
  6404. case 'F': // false
  6405. return sax->boolean(false);
  6406. case 'Z': // null
  6407. return sax->null();
  6408. case 'U':
  6409. {
  6410. uint8_t number;
  6411. return get_number(number) and sax->number_unsigned(number);
  6412. }
  6413. case 'i':
  6414. {
  6415. int8_t number;
  6416. return get_number(number) and sax->number_integer(number);
  6417. }
  6418. case 'I':
  6419. {
  6420. int16_t number;
  6421. return get_number(number) and sax->number_integer(number);
  6422. }
  6423. case 'l':
  6424. {
  6425. int32_t number;
  6426. return get_number(number) and sax->number_integer(number);
  6427. }
  6428. case 'L':
  6429. {
  6430. int64_t number;
  6431. return get_number(number) and sax->number_integer(number);
  6432. }
  6433. case 'd':
  6434. {
  6435. float number;
  6436. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  6437. }
  6438. case 'D':
  6439. {
  6440. double number;
  6441. return get_number(number) and sax->number_float(static_cast<number_float_t>(number), "");
  6442. }
  6443. case 'C': // char
  6444. {
  6445. get();
  6446. if (JSON_UNLIKELY(not unexpect_eof()))
  6447. {
  6448. return false;
  6449. }
  6450. if (JSON_UNLIKELY(current > 127))
  6451. {
  6452. auto last_token = get_token_string();
  6453. return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token));
  6454. }
  6455. string_t s(1, static_cast<char>(current));
  6456. return sax->string(s);
  6457. }
  6458. case 'S': // string
  6459. {
  6460. string_t s;
  6461. return get_ubjson_string(s) and sax->string(s);
  6462. }
  6463. case '[': // array
  6464. return get_ubjson_array();
  6465. case '{': // object
  6466. return get_ubjson_object();
  6467. default: // anything else
  6468. {
  6469. auto last_token = get_token_string();
  6470. return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, "error reading UBJSON; last byte: 0x" + last_token));
  6471. }
  6472. }
  6473. }
  6474. /*!
  6475. @return whether array creation completed
  6476. */
  6477. bool get_ubjson_array()
  6478. {
  6479. std::pair<std::size_t, int> size_and_type;
  6480. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6481. {
  6482. return false;
  6483. }
  6484. if (size_and_type.first != string_t::npos)
  6485. {
  6486. if (JSON_UNLIKELY(not sax->start_array(size_and_type.first)))
  6487. {
  6488. return false;
  6489. }
  6490. if (size_and_type.second != 0)
  6491. {
  6492. if (size_and_type.second != 'N')
  6493. {
  6494. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6495. {
  6496. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6497. {
  6498. return false;
  6499. }
  6500. }
  6501. }
  6502. }
  6503. else
  6504. {
  6505. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6506. {
  6507. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  6508. {
  6509. return false;
  6510. }
  6511. }
  6512. }
  6513. }
  6514. else
  6515. {
  6516. if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1))))
  6517. {
  6518. return false;
  6519. }
  6520. while (current != ']')
  6521. {
  6522. if (JSON_UNLIKELY(not parse_ubjson_internal(false)))
  6523. {
  6524. return false;
  6525. }
  6526. get_ignore_noop();
  6527. }
  6528. }
  6529. return sax->end_array();
  6530. }
  6531. /*!
  6532. @return whether object creation completed
  6533. */
  6534. bool get_ubjson_object()
  6535. {
  6536. std::pair<std::size_t, int> size_and_type;
  6537. if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type)))
  6538. {
  6539. return false;
  6540. }
  6541. string_t key;
  6542. if (size_and_type.first != string_t::npos)
  6543. {
  6544. if (JSON_UNLIKELY(not sax->start_object(size_and_type.first)))
  6545. {
  6546. return false;
  6547. }
  6548. if (size_and_type.second != 0)
  6549. {
  6550. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6551. {
  6552. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6553. {
  6554. return false;
  6555. }
  6556. if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second)))
  6557. {
  6558. return false;
  6559. }
  6560. key.clear();
  6561. }
  6562. }
  6563. else
  6564. {
  6565. for (std::size_t i = 0; i < size_and_type.first; ++i)
  6566. {
  6567. if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key)))
  6568. {
  6569. return false;
  6570. }
  6571. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  6572. {
  6573. return false;
  6574. }
  6575. key.clear();
  6576. }
  6577. }
  6578. }
  6579. else
  6580. {
  6581. if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1))))
  6582. {
  6583. return false;
  6584. }
  6585. while (current != '}')
  6586. {
  6587. if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key)))
  6588. {
  6589. return false;
  6590. }
  6591. if (JSON_UNLIKELY(not parse_ubjson_internal()))
  6592. {
  6593. return false;
  6594. }
  6595. get_ignore_noop();
  6596. key.clear();
  6597. }
  6598. }
  6599. return sax->end_object();
  6600. }
  6601. /*!
  6602. @return whether the last read character is not EOF
  6603. */
  6604. bool unexpect_eof() const
  6605. {
  6606. if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))
  6607. {
  6608. return sax->parse_error(chars_read, "<end of file>", parse_error::create(110, chars_read, "unexpected end of input"));
  6609. }
  6610. return true;
  6611. }
  6612. /*!
  6613. @return a string representation of the last read byte
  6614. */
  6615. std::string get_token_string() const
  6616. {
  6617. char cr[3];
  6618. snprintf(cr, 3, "%.2hhX", static_cast<unsigned char>(current));
  6619. return std::string{cr};
  6620. }
  6621. private:
  6622. /// input adapter
  6623. input_adapter_t ia = nullptr;
  6624. /// the current character
  6625. int current = std::char_traits<char>::eof();
  6626. /// the number of characters read
  6627. std::size_t chars_read = 0;
  6628. /// whether we can assume little endianess
  6629. const bool is_little_endian = little_endianess();
  6630. /// the SAX parser
  6631. json_sax_t* sax = nullptr;
  6632. };
  6633. }
  6634. }
  6635. // #include <nlohmann/detail/output/binary_writer.hpp>
  6636. #include <algorithm> // reverse
  6637. #include <array> // array
  6638. #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t
  6639. #include <cstring> // memcpy
  6640. #include <limits> // numeric_limits
  6641. // #include <nlohmann/detail/input/binary_reader.hpp>
  6642. // #include <nlohmann/detail/output/output_adapters.hpp>
  6643. namespace nlohmann
  6644. {
  6645. namespace detail
  6646. {
  6647. ///////////////////
  6648. // binary writer //
  6649. ///////////////////
  6650. /*!
  6651. @brief serialization to CBOR and MessagePack values
  6652. */
  6653. template<typename BasicJsonType, typename CharType>
  6654. class binary_writer
  6655. {
  6656. public:
  6657. /*!
  6658. @brief create a binary writer
  6659. @param[in] adapter output adapter to write to
  6660. */
  6661. explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)
  6662. {
  6663. assert(oa);
  6664. }
  6665. /*!
  6666. @brief[in] j JSON value to serialize
  6667. */
  6668. void write_cbor(const BasicJsonType& j)
  6669. {
  6670. switch (j.type())
  6671. {
  6672. case value_t::null:
  6673. {
  6674. oa->write_character(static_cast<CharType>(0xF6));
  6675. break;
  6676. }
  6677. case value_t::boolean:
  6678. {
  6679. oa->write_character(j.m_value.boolean
  6680. ? static_cast<CharType>(0xF5)
  6681. : static_cast<CharType>(0xF4));
  6682. break;
  6683. }
  6684. case value_t::number_integer:
  6685. {
  6686. if (j.m_value.number_integer >= 0)
  6687. {
  6688. // CBOR does not differentiate between positive signed
  6689. // integers and unsigned integers. Therefore, we used the
  6690. // code from the value_t::number_unsigned case here.
  6691. if (j.m_value.number_integer <= 0x17)
  6692. {
  6693. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  6694. }
  6695. else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  6696. {
  6697. oa->write_character(static_cast<CharType>(0x18));
  6698. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  6699. }
  6700. else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())
  6701. {
  6702. oa->write_character(static_cast<CharType>(0x19));
  6703. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  6704. }
  6705. else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())
  6706. {
  6707. oa->write_character(static_cast<CharType>(0x1A));
  6708. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  6709. }
  6710. else
  6711. {
  6712. oa->write_character(static_cast<CharType>(0x1B));
  6713. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  6714. }
  6715. }
  6716. else
  6717. {
  6718. // The conversions below encode the sign in the first
  6719. // byte, and the value is converted to a positive number.
  6720. const auto positive_number = -1 - j.m_value.number_integer;
  6721. if (j.m_value.number_integer >= -24)
  6722. {
  6723. write_number(static_cast<uint8_t>(0x20 + positive_number));
  6724. }
  6725. else if (positive_number <= (std::numeric_limits<uint8_t>::max)())
  6726. {
  6727. oa->write_character(static_cast<CharType>(0x38));
  6728. write_number(static_cast<uint8_t>(positive_number));
  6729. }
  6730. else if (positive_number <= (std::numeric_limits<uint16_t>::max)())
  6731. {
  6732. oa->write_character(static_cast<CharType>(0x39));
  6733. write_number(static_cast<uint16_t>(positive_number));
  6734. }
  6735. else if (positive_number <= (std::numeric_limits<uint32_t>::max)())
  6736. {
  6737. oa->write_character(static_cast<CharType>(0x3A));
  6738. write_number(static_cast<uint32_t>(positive_number));
  6739. }
  6740. else
  6741. {
  6742. oa->write_character(static_cast<CharType>(0x3B));
  6743. write_number(static_cast<uint64_t>(positive_number));
  6744. }
  6745. }
  6746. break;
  6747. }
  6748. case value_t::number_unsigned:
  6749. {
  6750. if (j.m_value.number_unsigned <= 0x17)
  6751. {
  6752. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  6753. }
  6754. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6755. {
  6756. oa->write_character(static_cast<CharType>(0x18));
  6757. write_number(static_cast<uint8_t>(j.m_value.number_unsigned));
  6758. }
  6759. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  6760. {
  6761. oa->write_character(static_cast<CharType>(0x19));
  6762. write_number(static_cast<uint16_t>(j.m_value.number_unsigned));
  6763. }
  6764. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  6765. {
  6766. oa->write_character(static_cast<CharType>(0x1A));
  6767. write_number(static_cast<uint32_t>(j.m_value.number_unsigned));
  6768. }
  6769. else
  6770. {
  6771. oa->write_character(static_cast<CharType>(0x1B));
  6772. write_number(static_cast<uint64_t>(j.m_value.number_unsigned));
  6773. }
  6774. break;
  6775. }
  6776. case value_t::number_float:
  6777. {
  6778. oa->write_character(get_cbor_float_prefix(j.m_value.number_float));
  6779. write_number(j.m_value.number_float);
  6780. break;
  6781. }
  6782. case value_t::string:
  6783. {
  6784. // step 1: write control byte and the string length
  6785. const auto N = j.m_value.string->size();
  6786. if (N <= 0x17)
  6787. {
  6788. write_number(static_cast<uint8_t>(0x60 + N));
  6789. }
  6790. else if (N <= (std::numeric_limits<uint8_t>::max)())
  6791. {
  6792. oa->write_character(static_cast<CharType>(0x78));
  6793. write_number(static_cast<uint8_t>(N));
  6794. }
  6795. else if (N <= (std::numeric_limits<uint16_t>::max)())
  6796. {
  6797. oa->write_character(static_cast<CharType>(0x79));
  6798. write_number(static_cast<uint16_t>(N));
  6799. }
  6800. else if (N <= (std::numeric_limits<uint32_t>::max)())
  6801. {
  6802. oa->write_character(static_cast<CharType>(0x7A));
  6803. write_number(static_cast<uint32_t>(N));
  6804. }
  6805. // LCOV_EXCL_START
  6806. else if (N <= (std::numeric_limits<uint64_t>::max)())
  6807. {
  6808. oa->write_character(static_cast<CharType>(0x7B));
  6809. write_number(static_cast<uint64_t>(N));
  6810. }
  6811. // LCOV_EXCL_STOP
  6812. // step 2: write the string
  6813. oa->write_characters(
  6814. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  6815. j.m_value.string->size());
  6816. break;
  6817. }
  6818. case value_t::array:
  6819. {
  6820. // step 1: write control byte and the array size
  6821. const auto N = j.m_value.array->size();
  6822. if (N <= 0x17)
  6823. {
  6824. write_number(static_cast<uint8_t>(0x80 + N));
  6825. }
  6826. else if (N <= (std::numeric_limits<uint8_t>::max)())
  6827. {
  6828. oa->write_character(static_cast<CharType>(0x98));
  6829. write_number(static_cast<uint8_t>(N));
  6830. }
  6831. else if (N <= (std::numeric_limits<uint16_t>::max)())
  6832. {
  6833. oa->write_character(static_cast<CharType>(0x99));
  6834. write_number(static_cast<uint16_t>(N));
  6835. }
  6836. else if (N <= (std::numeric_limits<uint32_t>::max)())
  6837. {
  6838. oa->write_character(static_cast<CharType>(0x9A));
  6839. write_number(static_cast<uint32_t>(N));
  6840. }
  6841. // LCOV_EXCL_START
  6842. else if (N <= (std::numeric_limits<uint64_t>::max)())
  6843. {
  6844. oa->write_character(static_cast<CharType>(0x9B));
  6845. write_number(static_cast<uint64_t>(N));
  6846. }
  6847. // LCOV_EXCL_STOP
  6848. // step 2: write each element
  6849. for (const auto& el : *j.m_value.array)
  6850. {
  6851. write_cbor(el);
  6852. }
  6853. break;
  6854. }
  6855. case value_t::object:
  6856. {
  6857. // step 1: write control byte and the object size
  6858. const auto N = j.m_value.object->size();
  6859. if (N <= 0x17)
  6860. {
  6861. write_number(static_cast<uint8_t>(0xA0 + N));
  6862. }
  6863. else if (N <= (std::numeric_limits<uint8_t>::max)())
  6864. {
  6865. oa->write_character(static_cast<CharType>(0xB8));
  6866. write_number(static_cast<uint8_t>(N));
  6867. }
  6868. else if (N <= (std::numeric_limits<uint16_t>::max)())
  6869. {
  6870. oa->write_character(static_cast<CharType>(0xB9));
  6871. write_number(static_cast<uint16_t>(N));
  6872. }
  6873. else if (N <= (std::numeric_limits<uint32_t>::max)())
  6874. {
  6875. oa->write_character(static_cast<CharType>(0xBA));
  6876. write_number(static_cast<uint32_t>(N));
  6877. }
  6878. // LCOV_EXCL_START
  6879. else if (N <= (std::numeric_limits<uint64_t>::max)())
  6880. {
  6881. oa->write_character(static_cast<CharType>(0xBB));
  6882. write_number(static_cast<uint64_t>(N));
  6883. }
  6884. // LCOV_EXCL_STOP
  6885. // step 2: write each element
  6886. for (const auto& el : *j.m_value.object)
  6887. {
  6888. write_cbor(el.first);
  6889. write_cbor(el.second);
  6890. }
  6891. break;
  6892. }
  6893. default:
  6894. break;
  6895. }
  6896. }
  6897. /*!
  6898. @brief[in] j JSON value to serialize
  6899. */
  6900. void write_msgpack(const BasicJsonType& j)
  6901. {
  6902. switch (j.type())
  6903. {
  6904. case value_t::null: // nil
  6905. {
  6906. oa->write_character(static_cast<CharType>(0xC0));
  6907. break;
  6908. }
  6909. case value_t::boolean: // true and false
  6910. {
  6911. oa->write_character(j.m_value.boolean
  6912. ? static_cast<CharType>(0xC3)
  6913. : static_cast<CharType>(0xC2));
  6914. break;
  6915. }
  6916. case value_t::number_integer:
  6917. {
  6918. if (j.m_value.number_integer >= 0)
  6919. {
  6920. // MessagePack does not differentiate between positive
  6921. // signed integers and unsigned integers. Therefore, we used
  6922. // the code from the value_t::number_unsigned case here.
  6923. if (j.m_value.number_unsigned < 128)
  6924. {
  6925. // positive fixnum
  6926. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  6927. }
  6928. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6929. {
  6930. // uint 8
  6931. oa->write_character(static_cast<CharType>(0xCC));
  6932. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  6933. }
  6934. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  6935. {
  6936. // uint 16
  6937. oa->write_character(static_cast<CharType>(0xCD));
  6938. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  6939. }
  6940. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  6941. {
  6942. // uint 32
  6943. oa->write_character(static_cast<CharType>(0xCE));
  6944. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  6945. }
  6946. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  6947. {
  6948. // uint 64
  6949. oa->write_character(static_cast<CharType>(0xCF));
  6950. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  6951. }
  6952. }
  6953. else
  6954. {
  6955. if (j.m_value.number_integer >= -32)
  6956. {
  6957. // negative fixnum
  6958. write_number(static_cast<int8_t>(j.m_value.number_integer));
  6959. }
  6960. else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and
  6961. j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  6962. {
  6963. // int 8
  6964. oa->write_character(static_cast<CharType>(0xD0));
  6965. write_number(static_cast<int8_t>(j.m_value.number_integer));
  6966. }
  6967. else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and
  6968. j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  6969. {
  6970. // int 16
  6971. oa->write_character(static_cast<CharType>(0xD1));
  6972. write_number(static_cast<int16_t>(j.m_value.number_integer));
  6973. }
  6974. else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and
  6975. j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  6976. {
  6977. // int 32
  6978. oa->write_character(static_cast<CharType>(0xD2));
  6979. write_number(static_cast<int32_t>(j.m_value.number_integer));
  6980. }
  6981. else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and
  6982. j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())
  6983. {
  6984. // int 64
  6985. oa->write_character(static_cast<CharType>(0xD3));
  6986. write_number(static_cast<int64_t>(j.m_value.number_integer));
  6987. }
  6988. }
  6989. break;
  6990. }
  6991. case value_t::number_unsigned:
  6992. {
  6993. if (j.m_value.number_unsigned < 128)
  6994. {
  6995. // positive fixnum
  6996. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  6997. }
  6998. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  6999. {
  7000. // uint 8
  7001. oa->write_character(static_cast<CharType>(0xCC));
  7002. write_number(static_cast<uint8_t>(j.m_value.number_integer));
  7003. }
  7004. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())
  7005. {
  7006. // uint 16
  7007. oa->write_character(static_cast<CharType>(0xCD));
  7008. write_number(static_cast<uint16_t>(j.m_value.number_integer));
  7009. }
  7010. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())
  7011. {
  7012. // uint 32
  7013. oa->write_character(static_cast<CharType>(0xCE));
  7014. write_number(static_cast<uint32_t>(j.m_value.number_integer));
  7015. }
  7016. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())
  7017. {
  7018. // uint 64
  7019. oa->write_character(static_cast<CharType>(0xCF));
  7020. write_number(static_cast<uint64_t>(j.m_value.number_integer));
  7021. }
  7022. break;
  7023. }
  7024. case value_t::number_float:
  7025. {
  7026. oa->write_character(get_msgpack_float_prefix(j.m_value.number_float));
  7027. write_number(j.m_value.number_float);
  7028. break;
  7029. }
  7030. case value_t::string:
  7031. {
  7032. // step 1: write control byte and the string length
  7033. const auto N = j.m_value.string->size();
  7034. if (N <= 31)
  7035. {
  7036. // fixstr
  7037. write_number(static_cast<uint8_t>(0xA0 | N));
  7038. }
  7039. else if (N <= (std::numeric_limits<uint8_t>::max)())
  7040. {
  7041. // str 8
  7042. oa->write_character(static_cast<CharType>(0xD9));
  7043. write_number(static_cast<uint8_t>(N));
  7044. }
  7045. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7046. {
  7047. // str 16
  7048. oa->write_character(static_cast<CharType>(0xDA));
  7049. write_number(static_cast<uint16_t>(N));
  7050. }
  7051. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7052. {
  7053. // str 32
  7054. oa->write_character(static_cast<CharType>(0xDB));
  7055. write_number(static_cast<uint32_t>(N));
  7056. }
  7057. // step 2: write the string
  7058. oa->write_characters(
  7059. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  7060. j.m_value.string->size());
  7061. break;
  7062. }
  7063. case value_t::array:
  7064. {
  7065. // step 1: write control byte and the array size
  7066. const auto N = j.m_value.array->size();
  7067. if (N <= 15)
  7068. {
  7069. // fixarray
  7070. write_number(static_cast<uint8_t>(0x90 | N));
  7071. }
  7072. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7073. {
  7074. // array 16
  7075. oa->write_character(static_cast<CharType>(0xDC));
  7076. write_number(static_cast<uint16_t>(N));
  7077. }
  7078. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7079. {
  7080. // array 32
  7081. oa->write_character(static_cast<CharType>(0xDD));
  7082. write_number(static_cast<uint32_t>(N));
  7083. }
  7084. // step 2: write each element
  7085. for (const auto& el : *j.m_value.array)
  7086. {
  7087. write_msgpack(el);
  7088. }
  7089. break;
  7090. }
  7091. case value_t::object:
  7092. {
  7093. // step 1: write control byte and the object size
  7094. const auto N = j.m_value.object->size();
  7095. if (N <= 15)
  7096. {
  7097. // fixmap
  7098. write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));
  7099. }
  7100. else if (N <= (std::numeric_limits<uint16_t>::max)())
  7101. {
  7102. // map 16
  7103. oa->write_character(static_cast<CharType>(0xDE));
  7104. write_number(static_cast<uint16_t>(N));
  7105. }
  7106. else if (N <= (std::numeric_limits<uint32_t>::max)())
  7107. {
  7108. // map 32
  7109. oa->write_character(static_cast<CharType>(0xDF));
  7110. write_number(static_cast<uint32_t>(N));
  7111. }
  7112. // step 2: write each element
  7113. for (const auto& el : *j.m_value.object)
  7114. {
  7115. write_msgpack(el.first);
  7116. write_msgpack(el.second);
  7117. }
  7118. break;
  7119. }
  7120. default:
  7121. break;
  7122. }
  7123. }
  7124. /*!
  7125. @param[in] j JSON value to serialize
  7126. @param[in] use_count whether to use '#' prefixes (optimized format)
  7127. @param[in] use_type whether to use '$' prefixes (optimized format)
  7128. @param[in] add_prefix whether prefixes need to be used for this value
  7129. */
  7130. void write_ubjson(const BasicJsonType& j, const bool use_count,
  7131. const bool use_type, const bool add_prefix = true)
  7132. {
  7133. switch (j.type())
  7134. {
  7135. case value_t::null:
  7136. {
  7137. if (add_prefix)
  7138. {
  7139. oa->write_character(static_cast<CharType>('Z'));
  7140. }
  7141. break;
  7142. }
  7143. case value_t::boolean:
  7144. {
  7145. if (add_prefix)
  7146. oa->write_character(j.m_value.boolean
  7147. ? static_cast<CharType>('T')
  7148. : static_cast<CharType>('F'));
  7149. break;
  7150. }
  7151. case value_t::number_integer:
  7152. {
  7153. write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix);
  7154. break;
  7155. }
  7156. case value_t::number_unsigned:
  7157. {
  7158. write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix);
  7159. break;
  7160. }
  7161. case value_t::number_float:
  7162. {
  7163. write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix);
  7164. break;
  7165. }
  7166. case value_t::string:
  7167. {
  7168. if (add_prefix)
  7169. {
  7170. oa->write_character(static_cast<CharType>('S'));
  7171. }
  7172. write_number_with_ubjson_prefix(j.m_value.string->size(), true);
  7173. oa->write_characters(
  7174. reinterpret_cast<const CharType*>(j.m_value.string->c_str()),
  7175. j.m_value.string->size());
  7176. break;
  7177. }
  7178. case value_t::array:
  7179. {
  7180. if (add_prefix)
  7181. {
  7182. oa->write_character(static_cast<CharType>('['));
  7183. }
  7184. bool prefix_required = true;
  7185. if (use_type and not j.m_value.array->empty())
  7186. {
  7187. assert(use_count);
  7188. const CharType first_prefix = ubjson_prefix(j.front());
  7189. const bool same_prefix = std::all_of(j.begin() + 1, j.end(),
  7190. [this, first_prefix](const BasicJsonType & v)
  7191. {
  7192. return ubjson_prefix(v) == first_prefix;
  7193. });
  7194. if (same_prefix)
  7195. {
  7196. prefix_required = false;
  7197. oa->write_character(static_cast<CharType>('$'));
  7198. oa->write_character(first_prefix);
  7199. }
  7200. }
  7201. if (use_count)
  7202. {
  7203. oa->write_character(static_cast<CharType>('#'));
  7204. write_number_with_ubjson_prefix(j.m_value.array->size(), true);
  7205. }
  7206. for (const auto& el : *j.m_value.array)
  7207. {
  7208. write_ubjson(el, use_count, use_type, prefix_required);
  7209. }
  7210. if (not use_count)
  7211. {
  7212. oa->write_character(static_cast<CharType>(']'));
  7213. }
  7214. break;
  7215. }
  7216. case value_t::object:
  7217. {
  7218. if (add_prefix)
  7219. {
  7220. oa->write_character(static_cast<CharType>('{'));
  7221. }
  7222. bool prefix_required = true;
  7223. if (use_type and not j.m_value.object->empty())
  7224. {
  7225. assert(use_count);
  7226. const CharType first_prefix = ubjson_prefix(j.front());
  7227. const bool same_prefix = std::all_of(j.begin(), j.end(),
  7228. [this, first_prefix](const BasicJsonType & v)
  7229. {
  7230. return ubjson_prefix(v) == first_prefix;
  7231. });
  7232. if (same_prefix)
  7233. {
  7234. prefix_required = false;
  7235. oa->write_character(static_cast<CharType>('$'));
  7236. oa->write_character(first_prefix);
  7237. }
  7238. }
  7239. if (use_count)
  7240. {
  7241. oa->write_character(static_cast<CharType>('#'));
  7242. write_number_with_ubjson_prefix(j.m_value.object->size(), true);
  7243. }
  7244. for (const auto& el : *j.m_value.object)
  7245. {
  7246. write_number_with_ubjson_prefix(el.first.size(), true);
  7247. oa->write_characters(
  7248. reinterpret_cast<const CharType*>(el.first.c_str()),
  7249. el.first.size());
  7250. write_ubjson(el.second, use_count, use_type, prefix_required);
  7251. }
  7252. if (not use_count)
  7253. {
  7254. oa->write_character(static_cast<CharType>('}'));
  7255. }
  7256. break;
  7257. }
  7258. default:
  7259. break;
  7260. }
  7261. }
  7262. private:
  7263. /*
  7264. @brief write a number to output input
  7265. @param[in] n number of type @a NumberType
  7266. @tparam NumberType the type of the number
  7267. @note This function needs to respect the system's endianess, because bytes
  7268. in CBOR, MessagePack, and UBJSON are stored in network order (big
  7269. endian) and therefore need reordering on little endian systems.
  7270. */
  7271. template<typename NumberType>
  7272. void write_number(const NumberType n)
  7273. {
  7274. // step 1: write number to array of length NumberType
  7275. std::array<CharType, sizeof(NumberType)> vec;
  7276. std::memcpy(vec.data(), &n, sizeof(NumberType));
  7277. // step 2: write array to output (with possible reordering)
  7278. if (is_little_endian)
  7279. {
  7280. // reverse byte order prior to conversion if necessary
  7281. std::reverse(vec.begin(), vec.end());
  7282. }
  7283. oa->write_characters(vec.data(), sizeof(NumberType));
  7284. }
  7285. // UBJSON: write number (floating point)
  7286. template<typename NumberType, typename std::enable_if<
  7287. std::is_floating_point<NumberType>::value, int>::type = 0>
  7288. void write_number_with_ubjson_prefix(const NumberType n,
  7289. const bool add_prefix)
  7290. {
  7291. if (add_prefix)
  7292. {
  7293. oa->write_character(get_ubjson_float_prefix(n));
  7294. }
  7295. write_number(n);
  7296. }
  7297. // UBJSON: write number (unsigned integer)
  7298. template<typename NumberType, typename std::enable_if<
  7299. std::is_unsigned<NumberType>::value, int>::type = 0>
  7300. void write_number_with_ubjson_prefix(const NumberType n,
  7301. const bool add_prefix)
  7302. {
  7303. if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)()))
  7304. {
  7305. if (add_prefix)
  7306. {
  7307. oa->write_character(static_cast<CharType>('i')); // int8
  7308. }
  7309. write_number(static_cast<uint8_t>(n));
  7310. }
  7311. else if (n <= (std::numeric_limits<uint8_t>::max)())
  7312. {
  7313. if (add_prefix)
  7314. {
  7315. oa->write_character(static_cast<CharType>('U')); // uint8
  7316. }
  7317. write_number(static_cast<uint8_t>(n));
  7318. }
  7319. else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)()))
  7320. {
  7321. if (add_prefix)
  7322. {
  7323. oa->write_character(static_cast<CharType>('I')); // int16
  7324. }
  7325. write_number(static_cast<int16_t>(n));
  7326. }
  7327. else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)()))
  7328. {
  7329. if (add_prefix)
  7330. {
  7331. oa->write_character(static_cast<CharType>('l')); // int32
  7332. }
  7333. write_number(static_cast<int32_t>(n));
  7334. }
  7335. else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)()))
  7336. {
  7337. if (add_prefix)
  7338. {
  7339. oa->write_character(static_cast<CharType>('L')); // int64
  7340. }
  7341. write_number(static_cast<int64_t>(n));
  7342. }
  7343. else
  7344. {
  7345. JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
  7346. }
  7347. }
  7348. // UBJSON: write number (signed integer)
  7349. template<typename NumberType, typename std::enable_if<
  7350. std::is_signed<NumberType>::value and
  7351. not std::is_floating_point<NumberType>::value, int>::type = 0>
  7352. void write_number_with_ubjson_prefix(const NumberType n,
  7353. const bool add_prefix)
  7354. {
  7355. if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)())
  7356. {
  7357. if (add_prefix)
  7358. {
  7359. oa->write_character(static_cast<CharType>('i')); // int8
  7360. }
  7361. write_number(static_cast<int8_t>(n));
  7362. }
  7363. else if (static_cast<int64_t>((std::numeric_limits<uint8_t>::min)()) <= n and n <= static_cast<int64_t>((std::numeric_limits<uint8_t>::max)()))
  7364. {
  7365. if (add_prefix)
  7366. {
  7367. oa->write_character(static_cast<CharType>('U')); // uint8
  7368. }
  7369. write_number(static_cast<uint8_t>(n));
  7370. }
  7371. else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)())
  7372. {
  7373. if (add_prefix)
  7374. {
  7375. oa->write_character(static_cast<CharType>('I')); // int16
  7376. }
  7377. write_number(static_cast<int16_t>(n));
  7378. }
  7379. else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)())
  7380. {
  7381. if (add_prefix)
  7382. {
  7383. oa->write_character(static_cast<CharType>('l')); // int32
  7384. }
  7385. write_number(static_cast<int32_t>(n));
  7386. }
  7387. else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)())
  7388. {
  7389. if (add_prefix)
  7390. {
  7391. oa->write_character(static_cast<CharType>('L')); // int64
  7392. }
  7393. write_number(static_cast<int64_t>(n));
  7394. }
  7395. // LCOV_EXCL_START
  7396. else
  7397. {
  7398. JSON_THROW(out_of_range::create(407, "number overflow serializing " + std::to_string(n)));
  7399. }
  7400. // LCOV_EXCL_STOP
  7401. }
  7402. /*!
  7403. @brief determine the type prefix of container values
  7404. @note This function does not need to be 100% accurate when it comes to
  7405. integer limits. In case a number exceeds the limits of int64_t,
  7406. this will be detected by a later call to function
  7407. write_number_with_ubjson_prefix. Therefore, we return 'L' for any
  7408. value that does not fit the previous limits.
  7409. */
  7410. CharType ubjson_prefix(const BasicJsonType& j) const noexcept
  7411. {
  7412. switch (j.type())
  7413. {
  7414. case value_t::null:
  7415. return 'Z';
  7416. case value_t::boolean:
  7417. return j.m_value.boolean ? 'T' : 'F';
  7418. case value_t::number_integer:
  7419. {
  7420. if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())
  7421. {
  7422. return 'i';
  7423. }
  7424. else if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())
  7425. {
  7426. return 'U';
  7427. }
  7428. else if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())
  7429. {
  7430. return 'I';
  7431. }
  7432. else if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())
  7433. {
  7434. return 'l';
  7435. }
  7436. else // no check and assume int64_t (see note above)
  7437. {
  7438. return 'L';
  7439. }
  7440. }
  7441. case value_t::number_unsigned:
  7442. {
  7443. if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)())
  7444. {
  7445. return 'i';
  7446. }
  7447. else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())
  7448. {
  7449. return 'U';
  7450. }
  7451. else if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)())
  7452. {
  7453. return 'I';
  7454. }
  7455. else if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)())
  7456. {
  7457. return 'l';
  7458. }
  7459. else // no check and assume int64_t (see note above)
  7460. {
  7461. return 'L';
  7462. }
  7463. }
  7464. case value_t::number_float:
  7465. return get_ubjson_float_prefix(j.m_value.number_float);
  7466. case value_t::string:
  7467. return 'S';
  7468. case value_t::array:
  7469. return '[';
  7470. case value_t::object:
  7471. return '{';
  7472. default: // discarded values
  7473. return 'N';
  7474. }
  7475. }
  7476. static constexpr CharType get_cbor_float_prefix(float)
  7477. {
  7478. return static_cast<CharType>(0xFA); // Single-Precision Float
  7479. }
  7480. static constexpr CharType get_cbor_float_prefix(double)
  7481. {
  7482. return static_cast<CharType>(0xFB); // Double-Precision Float
  7483. }
  7484. static constexpr CharType get_msgpack_float_prefix(float)
  7485. {
  7486. return static_cast<CharType>(0xCA); // float 32
  7487. }
  7488. static constexpr CharType get_msgpack_float_prefix(double)
  7489. {
  7490. return static_cast<CharType>(0xCB); // float 64
  7491. }
  7492. static constexpr CharType get_ubjson_float_prefix(float)
  7493. {
  7494. return 'd'; // float 32
  7495. }
  7496. static constexpr CharType get_ubjson_float_prefix(double)
  7497. {
  7498. return 'D'; // float 64
  7499. }
  7500. private:
  7501. /// whether we can assume little endianess
  7502. const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();
  7503. /// the output
  7504. output_adapter_t<CharType> oa = nullptr;
  7505. };
  7506. }
  7507. }
  7508. // #include <nlohmann/detail/output/serializer.hpp>
  7509. #include <algorithm> // reverse, remove, fill, find, none_of
  7510. #include <array> // array
  7511. #include <cassert> // assert
  7512. #include <ciso646> // and, or
  7513. #include <clocale> // localeconv, lconv
  7514. #include <cmath> // labs, isfinite, isnan, signbit
  7515. #include <cstddef> // size_t, ptrdiff_t
  7516. #include <cstdint> // uint8_t
  7517. #include <cstdio> // snprintf
  7518. #include <limits> // numeric_limits
  7519. #include <string> // string
  7520. #include <type_traits> // is_same
  7521. // #include <nlohmann/detail/exceptions.hpp>
  7522. // #include <nlohmann/detail/conversions/to_chars.hpp>
  7523. #include <cassert> // assert
  7524. #include <ciso646> // or, and, not
  7525. #include <cmath> // signbit, isfinite
  7526. #include <cstdint> // intN_t, uintN_t
  7527. #include <cstring> // memcpy, memmove
  7528. namespace nlohmann
  7529. {
  7530. namespace detail
  7531. {
  7532. /*!
  7533. @brief implements the Grisu2 algorithm for binary to decimal floating-point
  7534. conversion.
  7535. This implementation is a slightly modified version of the reference
  7536. implementation which may be obtained from
  7537. http://florian.loitsch.com/publications (bench.tar.gz).
  7538. The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch.
  7539. For a detailed description of the algorithm see:
  7540. [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with
  7541. Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming
  7542. Language Design and Implementation, PLDI 2010
  7543. [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately",
  7544. Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language
  7545. Design and Implementation, PLDI 1996
  7546. */
  7547. namespace dtoa_impl
  7548. {
  7549. template <typename Target, typename Source>
  7550. Target reinterpret_bits(const Source source)
  7551. {
  7552. static_assert(sizeof(Target) == sizeof(Source), "size mismatch");
  7553. Target target;
  7554. std::memcpy(&target, &source, sizeof(Source));
  7555. return target;
  7556. }
  7557. struct diyfp // f * 2^e
  7558. {
  7559. static constexpr int kPrecision = 64; // = q
  7560. uint64_t f;
  7561. int e;
  7562. constexpr diyfp() noexcept : f(0), e(0) {}
  7563. constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {}
  7564. /*!
  7565. @brief returns x - y
  7566. @pre x.e == y.e and x.f >= y.f
  7567. */
  7568. static diyfp sub(const diyfp& x, const diyfp& y) noexcept
  7569. {
  7570. assert(x.e == y.e);
  7571. assert(x.f >= y.f);
  7572. return diyfp(x.f - y.f, x.e);
  7573. }
  7574. /*!
  7575. @brief returns x * y
  7576. @note The result is rounded. (Only the upper q bits are returned.)
  7577. */
  7578. static diyfp mul(const diyfp& x, const diyfp& y) noexcept
  7579. {
  7580. static_assert(kPrecision == 64, "internal error");
  7581. // Computes:
  7582. // f = round((x.f * y.f) / 2^q)
  7583. // e = x.e + y.e + q
  7584. // Emulate the 64-bit * 64-bit multiplication:
  7585. //
  7586. // p = u * v
  7587. // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi)
  7588. // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi )
  7589. // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 )
  7590. // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 )
  7591. // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3)
  7592. // = (p0_lo ) + 2^32 (Q ) + 2^64 (H )
  7593. // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H )
  7594. //
  7595. // (Since Q might be larger than 2^32 - 1)
  7596. //
  7597. // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H)
  7598. //
  7599. // (Q_hi + H does not overflow a 64-bit int)
  7600. //
  7601. // = p_lo + 2^64 p_hi
  7602. const uint64_t u_lo = x.f & 0xFFFFFFFF;
  7603. const uint64_t u_hi = x.f >> 32;
  7604. const uint64_t v_lo = y.f & 0xFFFFFFFF;
  7605. const uint64_t v_hi = y.f >> 32;
  7606. const uint64_t p0 = u_lo * v_lo;
  7607. const uint64_t p1 = u_lo * v_hi;
  7608. const uint64_t p2 = u_hi * v_lo;
  7609. const uint64_t p3 = u_hi * v_hi;
  7610. const uint64_t p0_hi = p0 >> 32;
  7611. const uint64_t p1_lo = p1 & 0xFFFFFFFF;
  7612. const uint64_t p1_hi = p1 >> 32;
  7613. const uint64_t p2_lo = p2 & 0xFFFFFFFF;
  7614. const uint64_t p2_hi = p2 >> 32;
  7615. uint64_t Q = p0_hi + p1_lo + p2_lo;
  7616. // The full product might now be computed as
  7617. //
  7618. // p_hi = p3 + p2_hi + p1_hi + (Q >> 32)
  7619. // p_lo = p0_lo + (Q << 32)
  7620. //
  7621. // But in this particular case here, the full p_lo is not required.
  7622. // Effectively we only need to add the highest bit in p_lo to p_hi (and
  7623. // Q_hi + 1 does not overflow).
  7624. Q += uint64_t{1} << (64 - 32 - 1); // round, ties up
  7625. const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32);
  7626. return diyfp(h, x.e + y.e + 64);
  7627. }
  7628. /*!
  7629. @brief normalize x such that the significand is >= 2^(q-1)
  7630. @pre x.f != 0
  7631. */
  7632. static diyfp normalize(diyfp x) noexcept
  7633. {
  7634. assert(x.f != 0);
  7635. while ((x.f >> 63) == 0)
  7636. {
  7637. x.f <<= 1;
  7638. x.e--;
  7639. }
  7640. return x;
  7641. }
  7642. /*!
  7643. @brief normalize x such that the result has the exponent E
  7644. @pre e >= x.e and the upper e - x.e bits of x.f must be zero.
  7645. */
  7646. static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept
  7647. {
  7648. const int delta = x.e - target_exponent;
  7649. assert(delta >= 0);
  7650. assert(((x.f << delta) >> delta) == x.f);
  7651. return diyfp(x.f << delta, target_exponent);
  7652. }
  7653. };
  7654. struct boundaries
  7655. {
  7656. diyfp w;
  7657. diyfp minus;
  7658. diyfp plus;
  7659. };
  7660. /*!
  7661. Compute the (normalized) diyfp representing the input number 'value' and its
  7662. boundaries.
  7663. @pre value must be finite and positive
  7664. */
  7665. template <typename FloatType>
  7666. boundaries compute_boundaries(FloatType value)
  7667. {
  7668. assert(std::isfinite(value));
  7669. assert(value > 0);
  7670. // Convert the IEEE representation into a diyfp.
  7671. //
  7672. // If v is denormal:
  7673. // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1))
  7674. // If v is normalized:
  7675. // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1))
  7676. static_assert(std::numeric_limits<FloatType>::is_iec559,
  7677. "internal error: dtoa_short requires an IEEE-754 floating-point implementation");
  7678. constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit)
  7679. constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1);
  7680. constexpr int kMinExp = 1 - kBias;
  7681. constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1)
  7682. using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type;
  7683. const uint64_t bits = reinterpret_bits<bits_type>(value);
  7684. const uint64_t E = bits >> (kPrecision - 1);
  7685. const uint64_t F = bits & (kHiddenBit - 1);
  7686. const bool is_denormal = (E == 0);
  7687. const diyfp v = is_denormal
  7688. ? diyfp(F, kMinExp)
  7689. : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias);
  7690. // Compute the boundaries m- and m+ of the floating-point value
  7691. // v = f * 2^e.
  7692. //
  7693. // Determine v- and v+, the floating-point predecessor and successor if v,
  7694. // respectively.
  7695. //
  7696. // v- = v - 2^e if f != 2^(p-1) or e == e_min (A)
  7697. // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B)
  7698. //
  7699. // v+ = v + 2^e
  7700. //
  7701. // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_
  7702. // between m- and m+ round to v, regardless of how the input rounding
  7703. // algorithm breaks ties.
  7704. //
  7705. // ---+-------------+-------------+-------------+-------------+--- (A)
  7706. // v- m- v m+ v+
  7707. //
  7708. // -----------------+------+------+-------------+-------------+--- (B)
  7709. // v- m- v m+ v+
  7710. const bool lower_boundary_is_closer = (F == 0 and E > 1);
  7711. const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1);
  7712. const diyfp m_minus = lower_boundary_is_closer
  7713. ? diyfp(4 * v.f - 1, v.e - 2) // (B)
  7714. : diyfp(2 * v.f - 1, v.e - 1); // (A)
  7715. // Determine the normalized w+ = m+.
  7716. const diyfp w_plus = diyfp::normalize(m_plus);
  7717. // Determine w- = m- such that e_(w-) = e_(w+).
  7718. const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e);
  7719. return {diyfp::normalize(v), w_minus, w_plus};
  7720. }
  7721. // Given normalized diyfp w, Grisu needs to find a (normalized) cached
  7722. // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies
  7723. // within a certain range [alpha, gamma] (Definition 3.2 from [1])
  7724. //
  7725. // alpha <= e = e_c + e_w + q <= gamma
  7726. //
  7727. // or
  7728. //
  7729. // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q
  7730. // <= f_c * f_w * 2^gamma
  7731. //
  7732. // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies
  7733. //
  7734. // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma
  7735. //
  7736. // or
  7737. //
  7738. // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma)
  7739. //
  7740. // The choice of (alpha,gamma) determines the size of the table and the form of
  7741. // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well
  7742. // in practice:
  7743. //
  7744. // The idea is to cut the number c * w = f * 2^e into two parts, which can be
  7745. // processed independently: An integral part p1, and a fractional part p2:
  7746. //
  7747. // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e
  7748. // = (f div 2^-e) + (f mod 2^-e) * 2^e
  7749. // = p1 + p2 * 2^e
  7750. //
  7751. // The conversion of p1 into decimal form requires a series of divisions and
  7752. // modulos by (a power of) 10. These operations are faster for 32-bit than for
  7753. // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be
  7754. // achieved by choosing
  7755. //
  7756. // -e >= 32 or e <= -32 := gamma
  7757. //
  7758. // In order to convert the fractional part
  7759. //
  7760. // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ...
  7761. //
  7762. // into decimal form, the fraction is repeatedly multiplied by 10 and the digits
  7763. // d[-i] are extracted in order:
  7764. //
  7765. // (10 * p2) div 2^-e = d[-1]
  7766. // (10 * p2) mod 2^-e = d[-2] / 10^1 + ...
  7767. //
  7768. // The multiplication by 10 must not overflow. It is sufficient to choose
  7769. //
  7770. // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64.
  7771. //
  7772. // Since p2 = f mod 2^-e < 2^-e,
  7773. //
  7774. // -e <= 60 or e >= -60 := alpha
  7775. constexpr int kAlpha = -60;
  7776. constexpr int kGamma = -32;
  7777. struct cached_power // c = f * 2^e ~= 10^k
  7778. {
  7779. uint64_t f;
  7780. int e;
  7781. int k;
  7782. };
  7783. /*!
  7784. For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached
  7785. power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c
  7786. satisfies (Definition 3.2 from [1])
  7787. alpha <= e_c + e + q <= gamma.
  7788. */
  7789. inline cached_power get_cached_power_for_binary_exponent(int e)
  7790. {
  7791. // Now
  7792. //
  7793. // alpha <= e_c + e + q <= gamma (1)
  7794. // ==> f_c * 2^alpha <= c * 2^e * 2^q
  7795. //
  7796. // and since the c's are normalized, 2^(q-1) <= f_c,
  7797. //
  7798. // ==> 2^(q - 1 + alpha) <= c * 2^(e + q)
  7799. // ==> 2^(alpha - e - 1) <= c
  7800. //
  7801. // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as
  7802. //
  7803. // k = ceil( log_10( 2^(alpha - e - 1) ) )
  7804. // = ceil( (alpha - e - 1) * log_10(2) )
  7805. //
  7806. // From the paper:
  7807. // "In theory the result of the procedure could be wrong since c is rounded,
  7808. // and the computation itself is approximated [...]. In practice, however,
  7809. // this simple function is sufficient."
  7810. //
  7811. // For IEEE double precision floating-point numbers converted into
  7812. // normalized diyfp's w = f * 2^e, with q = 64,
  7813. //
  7814. // e >= -1022 (min IEEE exponent)
  7815. // -52 (p - 1)
  7816. // -52 (p - 1, possibly normalize denormal IEEE numbers)
  7817. // -11 (normalize the diyfp)
  7818. // = -1137
  7819. //
  7820. // and
  7821. //
  7822. // e <= +1023 (max IEEE exponent)
  7823. // -52 (p - 1)
  7824. // -11 (normalize the diyfp)
  7825. // = 960
  7826. //
  7827. // This binary exponent range [-1137,960] results in a decimal exponent
  7828. // range [-307,324]. One does not need to store a cached power for each
  7829. // k in this range. For each such k it suffices to find a cached power
  7830. // such that the exponent of the product lies in [alpha,gamma].
  7831. // This implies that the difference of the decimal exponents of adjacent
  7832. // table entries must be less than or equal to
  7833. //
  7834. // floor( (gamma - alpha) * log_10(2) ) = 8.
  7835. //
  7836. // (A smaller distance gamma-alpha would require a larger table.)
  7837. // NB:
  7838. // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34.
  7839. constexpr int kCachedPowersSize = 79;
  7840. constexpr int kCachedPowersMinDecExp = -300;
  7841. constexpr int kCachedPowersDecStep = 8;
  7842. static constexpr cached_power kCachedPowers[] =
  7843. {
  7844. { 0xAB70FE17C79AC6CA, -1060, -300 },
  7845. { 0xFF77B1FCBEBCDC4F, -1034, -292 },
  7846. { 0xBE5691EF416BD60C, -1007, -284 },
  7847. { 0x8DD01FAD907FFC3C, -980, -276 },
  7848. { 0xD3515C2831559A83, -954, -268 },
  7849. { 0x9D71AC8FADA6C9B5, -927, -260 },
  7850. { 0xEA9C227723EE8BCB, -901, -252 },
  7851. { 0xAECC49914078536D, -874, -244 },
  7852. { 0x823C12795DB6CE57, -847, -236 },
  7853. { 0xC21094364DFB5637, -821, -228 },
  7854. { 0x9096EA6F3848984F, -794, -220 },
  7855. { 0xD77485CB25823AC7, -768, -212 },
  7856. { 0xA086CFCD97BF97F4, -741, -204 },
  7857. { 0xEF340A98172AACE5, -715, -196 },
  7858. { 0xB23867FB2A35B28E, -688, -188 },
  7859. { 0x84C8D4DFD2C63F3B, -661, -180 },
  7860. { 0xC5DD44271AD3CDBA, -635, -172 },
  7861. { 0x936B9FCEBB25C996, -608, -164 },
  7862. { 0xDBAC6C247D62A584, -582, -156 },
  7863. { 0xA3AB66580D5FDAF6, -555, -148 },
  7864. { 0xF3E2F893DEC3F126, -529, -140 },
  7865. { 0xB5B5ADA8AAFF80B8, -502, -132 },
  7866. { 0x87625F056C7C4A8B, -475, -124 },
  7867. { 0xC9BCFF6034C13053, -449, -116 },
  7868. { 0x964E858C91BA2655, -422, -108 },
  7869. { 0xDFF9772470297EBD, -396, -100 },
  7870. { 0xA6DFBD9FB8E5B88F, -369, -92 },
  7871. { 0xF8A95FCF88747D94, -343, -84 },
  7872. { 0xB94470938FA89BCF, -316, -76 },
  7873. { 0x8A08F0F8BF0F156B, -289, -68 },
  7874. { 0xCDB02555653131B6, -263, -60 },
  7875. { 0x993FE2C6D07B7FAC, -236, -52 },
  7876. { 0xE45C10C42A2B3B06, -210, -44 },
  7877. { 0xAA242499697392D3, -183, -36 },
  7878. { 0xFD87B5F28300CA0E, -157, -28 },
  7879. { 0xBCE5086492111AEB, -130, -20 },
  7880. { 0x8CBCCC096F5088CC, -103, -12 },
  7881. { 0xD1B71758E219652C, -77, -4 },
  7882. { 0x9C40000000000000, -50, 4 },
  7883. { 0xE8D4A51000000000, -24, 12 },
  7884. { 0xAD78EBC5AC620000, 3, 20 },
  7885. { 0x813F3978F8940984, 30, 28 },
  7886. { 0xC097CE7BC90715B3, 56, 36 },
  7887. { 0x8F7E32CE7BEA5C70, 83, 44 },
  7888. { 0xD5D238A4ABE98068, 109, 52 },
  7889. { 0x9F4F2726179A2245, 136, 60 },
  7890. { 0xED63A231D4C4FB27, 162, 68 },
  7891. { 0xB0DE65388CC8ADA8, 189, 76 },
  7892. { 0x83C7088E1AAB65DB, 216, 84 },
  7893. { 0xC45D1DF942711D9A, 242, 92 },
  7894. { 0x924D692CA61BE758, 269, 100 },
  7895. { 0xDA01EE641A708DEA, 295, 108 },
  7896. { 0xA26DA3999AEF774A, 322, 116 },
  7897. { 0xF209787BB47D6B85, 348, 124 },
  7898. { 0xB454E4A179DD1877, 375, 132 },
  7899. { 0x865B86925B9BC5C2, 402, 140 },
  7900. { 0xC83553C5C8965D3D, 428, 148 },
  7901. { 0x952AB45CFA97A0B3, 455, 156 },
  7902. { 0xDE469FBD99A05FE3, 481, 164 },
  7903. { 0xA59BC234DB398C25, 508, 172 },
  7904. { 0xF6C69A72A3989F5C, 534, 180 },
  7905. { 0xB7DCBF5354E9BECE, 561, 188 },
  7906. { 0x88FCF317F22241E2, 588, 196 },
  7907. { 0xCC20CE9BD35C78A5, 614, 204 },
  7908. { 0x98165AF37B2153DF, 641, 212 },
  7909. { 0xE2A0B5DC971F303A, 667, 220 },
  7910. { 0xA8D9D1535CE3B396, 694, 228 },
  7911. { 0xFB9B7CD9A4A7443C, 720, 236 },
  7912. { 0xBB764C4CA7A44410, 747, 244 },
  7913. { 0x8BAB8EEFB6409C1A, 774, 252 },
  7914. { 0xD01FEF10A657842C, 800, 260 },
  7915. { 0x9B10A4E5E9913129, 827, 268 },
  7916. { 0xE7109BFBA19C0C9D, 853, 276 },
  7917. { 0xAC2820D9623BF429, 880, 284 },
  7918. { 0x80444B5E7AA7CF85, 907, 292 },
  7919. { 0xBF21E44003ACDD2D, 933, 300 },
  7920. { 0x8E679C2F5E44FF8F, 960, 308 },
  7921. { 0xD433179D9C8CB841, 986, 316 },
  7922. { 0x9E19DB92B4E31BA9, 1013, 324 },
  7923. };
  7924. // This computation gives exactly the same results for k as
  7925. // k = ceil((kAlpha - e - 1) * 0.30102999566398114)
  7926. // for |e| <= 1500, but doesn't require floating-point operations.
  7927. // NB: log_10(2) ~= 78913 / 2^18
  7928. assert(e >= -1500);
  7929. assert(e <= 1500);
  7930. const int f = kAlpha - e - 1;
  7931. const int k = (f * 78913) / (1 << 18) + (f > 0);
  7932. const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep;
  7933. assert(index >= 0);
  7934. assert(index < kCachedPowersSize);
  7935. static_cast<void>(kCachedPowersSize); // Fix warning.
  7936. const cached_power cached = kCachedPowers[index];
  7937. assert(kAlpha <= cached.e + e + 64);
  7938. assert(kGamma >= cached.e + e + 64);
  7939. return cached;
  7940. }
  7941. /*!
  7942. For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k.
  7943. For n == 0, returns 1 and sets pow10 := 1.
  7944. */
  7945. inline int find_largest_pow10(const uint32_t n, uint32_t& pow10)
  7946. {
  7947. // LCOV_EXCL_START
  7948. if (n >= 1000000000)
  7949. {
  7950. pow10 = 1000000000;
  7951. return 10;
  7952. }
  7953. // LCOV_EXCL_STOP
  7954. else if (n >= 100000000)
  7955. {
  7956. pow10 = 100000000;
  7957. return 9;
  7958. }
  7959. else if (n >= 10000000)
  7960. {
  7961. pow10 = 10000000;
  7962. return 8;
  7963. }
  7964. else if (n >= 1000000)
  7965. {
  7966. pow10 = 1000000;
  7967. return 7;
  7968. }
  7969. else if (n >= 100000)
  7970. {
  7971. pow10 = 100000;
  7972. return 6;
  7973. }
  7974. else if (n >= 10000)
  7975. {
  7976. pow10 = 10000;
  7977. return 5;
  7978. }
  7979. else if (n >= 1000)
  7980. {
  7981. pow10 = 1000;
  7982. return 4;
  7983. }
  7984. else if (n >= 100)
  7985. {
  7986. pow10 = 100;
  7987. return 3;
  7988. }
  7989. else if (n >= 10)
  7990. {
  7991. pow10 = 10;
  7992. return 2;
  7993. }
  7994. else
  7995. {
  7996. pow10 = 1;
  7997. return 1;
  7998. }
  7999. }
  8000. inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta,
  8001. uint64_t rest, uint64_t ten_k)
  8002. {
  8003. assert(len >= 1);
  8004. assert(dist <= delta);
  8005. assert(rest <= delta);
  8006. assert(ten_k > 0);
  8007. // <--------------------------- delta ---->
  8008. // <---- dist --------->
  8009. // --------------[------------------+-------------------]--------------
  8010. // M- w M+
  8011. //
  8012. // ten_k
  8013. // <------>
  8014. // <---- rest ---->
  8015. // --------------[------------------+----+--------------]--------------
  8016. // w V
  8017. // = buf * 10^k
  8018. //
  8019. // ten_k represents a unit-in-the-last-place in the decimal representation
  8020. // stored in buf.
  8021. // Decrement buf by ten_k while this takes buf closer to w.
  8022. // The tests are written in this order to avoid overflow in unsigned
  8023. // integer arithmetic.
  8024. while (rest < dist
  8025. and delta - rest >= ten_k
  8026. and (rest + ten_k < dist or dist - rest > rest + ten_k - dist))
  8027. {
  8028. assert(buf[len - 1] != '0');
  8029. buf[len - 1]--;
  8030. rest += ten_k;
  8031. }
  8032. }
  8033. /*!
  8034. Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+.
  8035. M- and M+ must be normalized and share the same exponent -60 <= e <= -32.
  8036. */
  8037. inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent,
  8038. diyfp M_minus, diyfp w, diyfp M_plus)
  8039. {
  8040. static_assert(kAlpha >= -60, "internal error");
  8041. static_assert(kGamma <= -32, "internal error");
  8042. // Generates the digits (and the exponent) of a decimal floating-point
  8043. // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's
  8044. // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma.
  8045. //
  8046. // <--------------------------- delta ---->
  8047. // <---- dist --------->
  8048. // --------------[------------------+-------------------]--------------
  8049. // M- w M+
  8050. //
  8051. // Grisu2 generates the digits of M+ from left to right and stops as soon as
  8052. // V is in [M-,M+].
  8053. assert(M_plus.e >= kAlpha);
  8054. assert(M_plus.e <= kGamma);
  8055. uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e)
  8056. uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e)
  8057. // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0):
  8058. //
  8059. // M+ = f * 2^e
  8060. // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e
  8061. // = ((p1 ) * 2^-e + (p2 )) * 2^e
  8062. // = p1 + p2 * 2^e
  8063. const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e);
  8064. uint32_t p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.)
  8065. uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e
  8066. // 1)
  8067. //
  8068. // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0]
  8069. assert(p1 > 0);
  8070. uint32_t pow10;
  8071. const int k = find_largest_pow10(p1, pow10);
  8072. // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1)
  8073. //
  8074. // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1))
  8075. // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1))
  8076. //
  8077. // M+ = p1 + p2 * 2^e
  8078. // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e
  8079. // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e
  8080. // = d[k-1] * 10^(k-1) + ( rest) * 2^e
  8081. //
  8082. // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0)
  8083. //
  8084. // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0]
  8085. //
  8086. // but stop as soon as
  8087. //
  8088. // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e
  8089. int n = k;
  8090. while (n > 0)
  8091. {
  8092. // Invariants:
  8093. // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k)
  8094. // pow10 = 10^(n-1) <= p1 < 10^n
  8095. //
  8096. const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1)
  8097. const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1)
  8098. //
  8099. // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e
  8100. // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e)
  8101. //
  8102. assert(d <= 9);
  8103. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  8104. //
  8105. // M+ = buffer * 10^(n-1) + (r + p2 * 2^e)
  8106. //
  8107. p1 = r;
  8108. n--;
  8109. //
  8110. // M+ = buffer * 10^n + (p1 + p2 * 2^e)
  8111. // pow10 = 10^n
  8112. //
  8113. // Now check if enough digits have been generated.
  8114. // Compute
  8115. //
  8116. // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e
  8117. //
  8118. // Note:
  8119. // Since rest and delta share the same exponent e, it suffices to
  8120. // compare the significands.
  8121. const uint64_t rest = (uint64_t{p1} << -one.e) + p2;
  8122. if (rest <= delta)
  8123. {
  8124. // V = buffer * 10^n, with M- <= V <= M+.
  8125. decimal_exponent += n;
  8126. // We may now just stop. But instead look if the buffer could be
  8127. // decremented to bring V closer to w.
  8128. //
  8129. // pow10 = 10^n is now 1 ulp in the decimal representation V.
  8130. // The rounding procedure works with diyfp's with an implicit
  8131. // exponent of e.
  8132. //
  8133. // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e
  8134. //
  8135. const uint64_t ten_n = uint64_t{pow10} << -one.e;
  8136. grisu2_round(buffer, length, dist, delta, rest, ten_n);
  8137. return;
  8138. }
  8139. pow10 /= 10;
  8140. //
  8141. // pow10 = 10^(n-1) <= p1 < 10^n
  8142. // Invariants restored.
  8143. }
  8144. // 2)
  8145. //
  8146. // The digits of the integral part have been generated:
  8147. //
  8148. // M+ = d[k-1]...d[1]d[0] + p2 * 2^e
  8149. // = buffer + p2 * 2^e
  8150. //
  8151. // Now generate the digits of the fractional part p2 * 2^e.
  8152. //
  8153. // Note:
  8154. // No decimal point is generated: the exponent is adjusted instead.
  8155. //
  8156. // p2 actually represents the fraction
  8157. //
  8158. // p2 * 2^e
  8159. // = p2 / 2^-e
  8160. // = d[-1] / 10^1 + d[-2] / 10^2 + ...
  8161. //
  8162. // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...)
  8163. //
  8164. // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m
  8165. // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...)
  8166. //
  8167. // using
  8168. //
  8169. // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e)
  8170. // = ( d) * 2^-e + ( r)
  8171. //
  8172. // or
  8173. // 10^m * p2 * 2^e = d + r * 2^e
  8174. //
  8175. // i.e.
  8176. //
  8177. // M+ = buffer + p2 * 2^e
  8178. // = buffer + 10^-m * (d + r * 2^e)
  8179. // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e
  8180. //
  8181. // and stop as soon as 10^-m * r * 2^e <= delta * 2^e
  8182. assert(p2 > delta);
  8183. int m = 0;
  8184. for (;;)
  8185. {
  8186. // Invariant:
  8187. // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e
  8188. // = buffer * 10^-m + 10^-m * (p2 ) * 2^e
  8189. // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e
  8190. // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e
  8191. //
  8192. assert(p2 <= UINT64_MAX / 10);
  8193. p2 *= 10;
  8194. const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e
  8195. const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e
  8196. //
  8197. // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e
  8198. // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e))
  8199. // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e
  8200. //
  8201. assert(d <= 9);
  8202. buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d
  8203. //
  8204. // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e
  8205. //
  8206. p2 = r;
  8207. m++;
  8208. //
  8209. // M+ = buffer * 10^-m + 10^-m * p2 * 2^e
  8210. // Invariant restored.
  8211. // Check if enough digits have been generated.
  8212. //
  8213. // 10^-m * p2 * 2^e <= delta * 2^e
  8214. // p2 * 2^e <= 10^m * delta * 2^e
  8215. // p2 <= 10^m * delta
  8216. delta *= 10;
  8217. dist *= 10;
  8218. if (p2 <= delta)
  8219. {
  8220. break;
  8221. }
  8222. }
  8223. // V = buffer * 10^-m, with M- <= V <= M+.
  8224. decimal_exponent -= m;
  8225. // 1 ulp in the decimal representation is now 10^-m.
  8226. // Since delta and dist are now scaled by 10^m, we need to do the
  8227. // same with ulp in order to keep the units in sync.
  8228. //
  8229. // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e
  8230. //
  8231. const uint64_t ten_m = one.f;
  8232. grisu2_round(buffer, length, dist, delta, p2, ten_m);
  8233. // By construction this algorithm generates the shortest possible decimal
  8234. // number (Loitsch, Theorem 6.2) which rounds back to w.
  8235. // For an input number of precision p, at least
  8236. //
  8237. // N = 1 + ceil(p * log_10(2))
  8238. //
  8239. // decimal digits are sufficient to identify all binary floating-point
  8240. // numbers (Matula, "In-and-Out conversions").
  8241. // This implies that the algorithm does not produce more than N decimal
  8242. // digits.
  8243. //
  8244. // N = 17 for p = 53 (IEEE double precision)
  8245. // N = 9 for p = 24 (IEEE single precision)
  8246. }
  8247. /*!
  8248. v = buf * 10^decimal_exponent
  8249. len is the length of the buffer (number of decimal digits)
  8250. The buffer must be large enough, i.e. >= max_digits10.
  8251. */
  8252. inline void grisu2(char* buf, int& len, int& decimal_exponent,
  8253. diyfp m_minus, diyfp v, diyfp m_plus)
  8254. {
  8255. assert(m_plus.e == m_minus.e);
  8256. assert(m_plus.e == v.e);
  8257. // --------(-----------------------+-----------------------)-------- (A)
  8258. // m- v m+
  8259. //
  8260. // --------------------(-----------+-----------------------)-------- (B)
  8261. // m- v m+
  8262. //
  8263. // First scale v (and m- and m+) such that the exponent is in the range
  8264. // [alpha, gamma].
  8265. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e);
  8266. const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k
  8267. // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma]
  8268. const diyfp w = diyfp::mul(v, c_minus_k);
  8269. const diyfp w_minus = diyfp::mul(m_minus, c_minus_k);
  8270. const diyfp w_plus = diyfp::mul(m_plus, c_minus_k);
  8271. // ----(---+---)---------------(---+---)---------------(---+---)----
  8272. // w- w w+
  8273. // = c*m- = c*v = c*m+
  8274. //
  8275. // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and
  8276. // w+ are now off by a small amount.
  8277. // In fact:
  8278. //
  8279. // w - v * 10^k < 1 ulp
  8280. //
  8281. // To account for this inaccuracy, add resp. subtract 1 ulp.
  8282. //
  8283. // --------+---[---------------(---+---)---------------]---+--------
  8284. // w- M- w M+ w+
  8285. //
  8286. // Now any number in [M-, M+] (bounds included) will round to w when input,
  8287. // regardless of how the input rounding algorithm breaks ties.
  8288. //
  8289. // And digit_gen generates the shortest possible such number in [M-, M+].
  8290. // Note that this does not mean that Grisu2 always generates the shortest
  8291. // possible number in the interval (m-, m+).
  8292. const diyfp M_minus(w_minus.f + 1, w_minus.e);
  8293. const diyfp M_plus (w_plus.f - 1, w_plus.e );
  8294. decimal_exponent = -cached.k; // = -(-k) = k
  8295. grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus);
  8296. }
  8297. /*!
  8298. v = buf * 10^decimal_exponent
  8299. len is the length of the buffer (number of decimal digits)
  8300. The buffer must be large enough, i.e. >= max_digits10.
  8301. */
  8302. template <typename FloatType>
  8303. void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value)
  8304. {
  8305. static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3,
  8306. "internal error: not enough precision");
  8307. assert(std::isfinite(value));
  8308. assert(value > 0);
  8309. // If the neighbors (and boundaries) of 'value' are always computed for double-precision
  8310. // numbers, all float's can be recovered using strtod (and strtof). However, the resulting
  8311. // decimal representations are not exactly "short".
  8312. //
  8313. // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars)
  8314. // says "value is converted to a string as if by std::sprintf in the default ("C") locale"
  8315. // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars'
  8316. // does.
  8317. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the
  8318. // representation using the corresponding std::from_chars function recovers value exactly". That
  8319. // indicates that single precision floating-point numbers should be recovered using
  8320. // 'std::strtof'.
  8321. //
  8322. // NB: If the neighbors are computed for single-precision numbers, there is a single float
  8323. // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision
  8324. // value is off by 1 ulp.
  8325. #if 0
  8326. const boundaries w = compute_boundaries(static_cast<double>(value));
  8327. #else
  8328. const boundaries w = compute_boundaries(value);
  8329. #endif
  8330. grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus);
  8331. }
  8332. /*!
  8333. @brief appends a decimal representation of e to buf
  8334. @return a pointer to the element following the exponent.
  8335. @pre -1000 < e < 1000
  8336. */
  8337. inline char* append_exponent(char* buf, int e)
  8338. {
  8339. assert(e > -1000);
  8340. assert(e < 1000);
  8341. if (e < 0)
  8342. {
  8343. e = -e;
  8344. *buf++ = '-';
  8345. }
  8346. else
  8347. {
  8348. *buf++ = '+';
  8349. }
  8350. uint32_t k = static_cast<uint32_t>(e);
  8351. if (k < 10)
  8352. {
  8353. // Always print at least two digits in the exponent.
  8354. // This is for compatibility with printf("%g").
  8355. *buf++ = '0';
  8356. *buf++ = static_cast<char>('0' + k);
  8357. }
  8358. else if (k < 100)
  8359. {
  8360. *buf++ = static_cast<char>('0' + k / 10);
  8361. k %= 10;
  8362. *buf++ = static_cast<char>('0' + k);
  8363. }
  8364. else
  8365. {
  8366. *buf++ = static_cast<char>('0' + k / 100);
  8367. k %= 100;
  8368. *buf++ = static_cast<char>('0' + k / 10);
  8369. k %= 10;
  8370. *buf++ = static_cast<char>('0' + k);
  8371. }
  8372. return buf;
  8373. }
  8374. /*!
  8375. @brief prettify v = buf * 10^decimal_exponent
  8376. If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point
  8377. notation. Otherwise it will be printed in exponential notation.
  8378. @pre min_exp < 0
  8379. @pre max_exp > 0
  8380. */
  8381. inline char* format_buffer(char* buf, int len, int decimal_exponent,
  8382. int min_exp, int max_exp)
  8383. {
  8384. assert(min_exp < 0);
  8385. assert(max_exp > 0);
  8386. const int k = len;
  8387. const int n = len + decimal_exponent;
  8388. // v = buf * 10^(n-k)
  8389. // k is the length of the buffer (number of decimal digits)
  8390. // n is the position of the decimal point relative to the start of the buffer.
  8391. if (k <= n and n <= max_exp)
  8392. {
  8393. // digits[000]
  8394. // len <= max_exp + 2
  8395. std::memset(buf + k, '0', static_cast<size_t>(n - k));
  8396. // Make it look like a floating-point number (#362, #378)
  8397. buf[n + 0] = '.';
  8398. buf[n + 1] = '0';
  8399. return buf + (n + 2);
  8400. }
  8401. if (0 < n and n <= max_exp)
  8402. {
  8403. // dig.its
  8404. // len <= max_digits10 + 1
  8405. assert(k > n);
  8406. std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n));
  8407. buf[n] = '.';
  8408. return buf + (k + 1);
  8409. }
  8410. if (min_exp < n and n <= 0)
  8411. {
  8412. // 0.[000]digits
  8413. // len <= 2 + (-min_exp - 1) + max_digits10
  8414. std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k));
  8415. buf[0] = '0';
  8416. buf[1] = '.';
  8417. std::memset(buf + 2, '0', static_cast<size_t>(-n));
  8418. return buf + (2 + (-n) + k);
  8419. }
  8420. if (k == 1)
  8421. {
  8422. // dE+123
  8423. // len <= 1 + 5
  8424. buf += 1;
  8425. }
  8426. else
  8427. {
  8428. // d.igitsE+123
  8429. // len <= max_digits10 + 1 + 5
  8430. std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1));
  8431. buf[1] = '.';
  8432. buf += 1 + k;
  8433. }
  8434. *buf++ = 'e';
  8435. return append_exponent(buf, n - 1);
  8436. }
  8437. } // namespace dtoa_impl
  8438. /*!
  8439. @brief generates a decimal representation of the floating-point number value in [first, last).
  8440. The format of the resulting decimal representation is similar to printf's %g
  8441. format. Returns an iterator pointing past-the-end of the decimal representation.
  8442. @note The input number must be finite, i.e. NaN's and Inf's are not supported.
  8443. @note The buffer must be large enough.
  8444. @note The result is NOT null-terminated.
  8445. */
  8446. template <typename FloatType>
  8447. char* to_chars(char* first, char* last, FloatType value)
  8448. {
  8449. static_cast<void>(last); // maybe unused - fix warning
  8450. assert(std::isfinite(value));
  8451. // Use signbit(value) instead of (value < 0) since signbit works for -0.
  8452. if (std::signbit(value))
  8453. {
  8454. value = -value;
  8455. *first++ = '-';
  8456. }
  8457. if (value == 0) // +-0
  8458. {
  8459. *first++ = '0';
  8460. // Make it look like a floating-point number (#362, #378)
  8461. *first++ = '.';
  8462. *first++ = '0';
  8463. return first;
  8464. }
  8465. assert(last - first >= std::numeric_limits<FloatType>::max_digits10);
  8466. // Compute v = buffer * 10^decimal_exponent.
  8467. // The decimal digits are stored in the buffer, which needs to be interpreted
  8468. // as an unsigned decimal integer.
  8469. // len is the length of the buffer, i.e. the number of decimal digits.
  8470. int len = 0;
  8471. int decimal_exponent = 0;
  8472. dtoa_impl::grisu2(first, len, decimal_exponent, value);
  8473. assert(len <= std::numeric_limits<FloatType>::max_digits10);
  8474. // Format the buffer like printf("%.*g", prec, value)
  8475. constexpr int kMinExp = -4;
  8476. // Use digits10 here to increase compatibility with version 2.
  8477. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10;
  8478. assert(last - first >= kMaxExp + 2);
  8479. assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10);
  8480. assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6);
  8481. return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp);
  8482. }
  8483. } // namespace detail
  8484. } // namespace nlohmann
  8485. // #include <nlohmann/detail/macro_scope.hpp>
  8486. // #include <nlohmann/detail/meta/cpp_future.hpp>
  8487. // #include <nlohmann/detail/output/output_adapters.hpp>
  8488. // #include <nlohmann/detail/value_t.hpp>
  8489. namespace nlohmann
  8490. {
  8491. namespace detail
  8492. {
  8493. ///////////////////
  8494. // serialization //
  8495. ///////////////////
  8496. template<typename BasicJsonType>
  8497. class serializer
  8498. {
  8499. using string_t = typename BasicJsonType::string_t;
  8500. using number_float_t = typename BasicJsonType::number_float_t;
  8501. using number_integer_t = typename BasicJsonType::number_integer_t;
  8502. using number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  8503. static constexpr uint8_t UTF8_ACCEPT = 0;
  8504. static constexpr uint8_t UTF8_REJECT = 1;
  8505. public:
  8506. /*!
  8507. @param[in] s output stream to serialize to
  8508. @param[in] ichar indentation character to use
  8509. */
  8510. serializer(output_adapter_t<char> s, const char ichar)
  8511. : o(std::move(s)), loc(std::localeconv()),
  8512. thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)),
  8513. decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)),
  8514. indent_char(ichar), indent_string(512, indent_char)
  8515. {}
  8516. // delete because of pointer members
  8517. serializer(const serializer&) = delete;
  8518. serializer& operator=(const serializer&) = delete;
  8519. /*!
  8520. @brief internal implementation of the serialization function
  8521. This function is called by the public member function dump and organizes
  8522. the serialization internally. The indentation level is propagated as
  8523. additional parameter. In case of arrays and objects, the function is
  8524. called recursively.
  8525. - strings and object keys are escaped using `escape_string()`
  8526. - integer numbers are converted implicitly via `operator<<`
  8527. - floating-point numbers are converted to a string using `"%g"` format
  8528. @param[in] val value to serialize
  8529. @param[in] pretty_print whether the output shall be pretty-printed
  8530. @param[in] indent_step the indent level
  8531. @param[in] current_indent the current indent level (only used internally)
  8532. */
  8533. void dump(const BasicJsonType& val, const bool pretty_print,
  8534. const bool ensure_ascii,
  8535. const unsigned int indent_step,
  8536. const unsigned int current_indent = 0)
  8537. {
  8538. switch (val.m_type)
  8539. {
  8540. case value_t::object:
  8541. {
  8542. if (val.m_value.object->empty())
  8543. {
  8544. o->write_characters("{}", 2);
  8545. return;
  8546. }
  8547. if (pretty_print)
  8548. {
  8549. o->write_characters("{\n", 2);
  8550. // variable to hold indentation for recursive calls
  8551. const auto new_indent = current_indent + indent_step;
  8552. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  8553. {
  8554. indent_string.resize(indent_string.size() * 2, ' ');
  8555. }
  8556. // first n-1 elements
  8557. auto i = val.m_value.object->cbegin();
  8558. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  8559. {
  8560. o->write_characters(indent_string.c_str(), new_indent);
  8561. o->write_character('\"');
  8562. dump_escaped(i->first, ensure_ascii);
  8563. o->write_characters("\": ", 3);
  8564. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  8565. o->write_characters(",\n", 2);
  8566. }
  8567. // last element
  8568. assert(i != val.m_value.object->cend());
  8569. assert(std::next(i) == val.m_value.object->cend());
  8570. o->write_characters(indent_string.c_str(), new_indent);
  8571. o->write_character('\"');
  8572. dump_escaped(i->first, ensure_ascii);
  8573. o->write_characters("\": ", 3);
  8574. dump(i->second, true, ensure_ascii, indent_step, new_indent);
  8575. o->write_character('\n');
  8576. o->write_characters(indent_string.c_str(), current_indent);
  8577. o->write_character('}');
  8578. }
  8579. else
  8580. {
  8581. o->write_character('{');
  8582. // first n-1 elements
  8583. auto i = val.m_value.object->cbegin();
  8584. for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)
  8585. {
  8586. o->write_character('\"');
  8587. dump_escaped(i->first, ensure_ascii);
  8588. o->write_characters("\":", 2);
  8589. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  8590. o->write_character(',');
  8591. }
  8592. // last element
  8593. assert(i != val.m_value.object->cend());
  8594. assert(std::next(i) == val.m_value.object->cend());
  8595. o->write_character('\"');
  8596. dump_escaped(i->first, ensure_ascii);
  8597. o->write_characters("\":", 2);
  8598. dump(i->second, false, ensure_ascii, indent_step, current_indent);
  8599. o->write_character('}');
  8600. }
  8601. return;
  8602. }
  8603. case value_t::array:
  8604. {
  8605. if (val.m_value.array->empty())
  8606. {
  8607. o->write_characters("[]", 2);
  8608. return;
  8609. }
  8610. if (pretty_print)
  8611. {
  8612. o->write_characters("[\n", 2);
  8613. // variable to hold indentation for recursive calls
  8614. const auto new_indent = current_indent + indent_step;
  8615. if (JSON_UNLIKELY(indent_string.size() < new_indent))
  8616. {
  8617. indent_string.resize(indent_string.size() * 2, ' ');
  8618. }
  8619. // first n-1 elements
  8620. for (auto i = val.m_value.array->cbegin();
  8621. i != val.m_value.array->cend() - 1; ++i)
  8622. {
  8623. o->write_characters(indent_string.c_str(), new_indent);
  8624. dump(*i, true, ensure_ascii, indent_step, new_indent);
  8625. o->write_characters(",\n", 2);
  8626. }
  8627. // last element
  8628. assert(not val.m_value.array->empty());
  8629. o->write_characters(indent_string.c_str(), new_indent);
  8630. dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);
  8631. o->write_character('\n');
  8632. o->write_characters(indent_string.c_str(), current_indent);
  8633. o->write_character(']');
  8634. }
  8635. else
  8636. {
  8637. o->write_character('[');
  8638. // first n-1 elements
  8639. for (auto i = val.m_value.array->cbegin();
  8640. i != val.m_value.array->cend() - 1; ++i)
  8641. {
  8642. dump(*i, false, ensure_ascii, indent_step, current_indent);
  8643. o->write_character(',');
  8644. }
  8645. // last element
  8646. assert(not val.m_value.array->empty());
  8647. dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);
  8648. o->write_character(']');
  8649. }
  8650. return;
  8651. }
  8652. case value_t::string:
  8653. {
  8654. o->write_character('\"');
  8655. dump_escaped(*val.m_value.string, ensure_ascii);
  8656. o->write_character('\"');
  8657. return;
  8658. }
  8659. case value_t::boolean:
  8660. {
  8661. if (val.m_value.boolean)
  8662. {
  8663. o->write_characters("true", 4);
  8664. }
  8665. else
  8666. {
  8667. o->write_characters("false", 5);
  8668. }
  8669. return;
  8670. }
  8671. case value_t::number_integer:
  8672. {
  8673. dump_integer(val.m_value.number_integer);
  8674. return;
  8675. }
  8676. case value_t::number_unsigned:
  8677. {
  8678. dump_integer(val.m_value.number_unsigned);
  8679. return;
  8680. }
  8681. case value_t::number_float:
  8682. {
  8683. dump_float(val.m_value.number_float);
  8684. return;
  8685. }
  8686. case value_t::discarded:
  8687. {
  8688. o->write_characters("<discarded>", 11);
  8689. return;
  8690. }
  8691. case value_t::null:
  8692. {
  8693. o->write_characters("null", 4);
  8694. return;
  8695. }
  8696. }
  8697. }
  8698. private:
  8699. /*!
  8700. @brief dump escaped string
  8701. Escape a string by replacing certain special characters by a sequence of an
  8702. escape character (backslash) and another character and other control
  8703. characters by a sequence of "\u" followed by a four-digit hex
  8704. representation. The escaped string is written to output stream @a o.
  8705. @param[in] s the string to escape
  8706. @param[in] ensure_ascii whether to escape non-ASCII characters with
  8707. \uXXXX sequences
  8708. @complexity Linear in the length of string @a s.
  8709. */
  8710. void dump_escaped(const string_t& s, const bool ensure_ascii)
  8711. {
  8712. uint32_t codepoint;
  8713. uint8_t state = UTF8_ACCEPT;
  8714. std::size_t bytes = 0; // number of bytes written to string_buffer
  8715. for (std::size_t i = 0; i < s.size(); ++i)
  8716. {
  8717. const auto byte = static_cast<uint8_t>(s[i]);
  8718. switch (decode(state, codepoint, byte))
  8719. {
  8720. case UTF8_ACCEPT: // decode found a new code point
  8721. {
  8722. switch (codepoint)
  8723. {
  8724. case 0x08: // backspace
  8725. {
  8726. string_buffer[bytes++] = '\\';
  8727. string_buffer[bytes++] = 'b';
  8728. break;
  8729. }
  8730. case 0x09: // horizontal tab
  8731. {
  8732. string_buffer[bytes++] = '\\';
  8733. string_buffer[bytes++] = 't';
  8734. break;
  8735. }
  8736. case 0x0A: // newline
  8737. {
  8738. string_buffer[bytes++] = '\\';
  8739. string_buffer[bytes++] = 'n';
  8740. break;
  8741. }
  8742. case 0x0C: // formfeed
  8743. {
  8744. string_buffer[bytes++] = '\\';
  8745. string_buffer[bytes++] = 'f';
  8746. break;
  8747. }
  8748. case 0x0D: // carriage return
  8749. {
  8750. string_buffer[bytes++] = '\\';
  8751. string_buffer[bytes++] = 'r';
  8752. break;
  8753. }
  8754. case 0x22: // quotation mark
  8755. {
  8756. string_buffer[bytes++] = '\\';
  8757. string_buffer[bytes++] = '\"';
  8758. break;
  8759. }
  8760. case 0x5C: // reverse solidus
  8761. {
  8762. string_buffer[bytes++] = '\\';
  8763. string_buffer[bytes++] = '\\';
  8764. break;
  8765. }
  8766. default:
  8767. {
  8768. // escape control characters (0x00..0x1F) or, if
  8769. // ensure_ascii parameter is used, non-ASCII characters
  8770. if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F)))
  8771. {
  8772. if (codepoint <= 0xFFFF)
  8773. {
  8774. std::snprintf(string_buffer.data() + bytes, 7, "\\u%04x",
  8775. static_cast<uint16_t>(codepoint));
  8776. bytes += 6;
  8777. }
  8778. else
  8779. {
  8780. std::snprintf(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x",
  8781. static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)),
  8782. static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF)));
  8783. bytes += 12;
  8784. }
  8785. }
  8786. else
  8787. {
  8788. // copy byte to buffer (all previous bytes
  8789. // been copied have in default case above)
  8790. string_buffer[bytes++] = s[i];
  8791. }
  8792. break;
  8793. }
  8794. }
  8795. // write buffer and reset index; there must be 13 bytes
  8796. // left, as this is the maximal number of bytes to be
  8797. // written ("\uxxxx\uxxxx\0") for one code point
  8798. if (string_buffer.size() - bytes < 13)
  8799. {
  8800. o->write_characters(string_buffer.data(), bytes);
  8801. bytes = 0;
  8802. }
  8803. break;
  8804. }
  8805. case UTF8_REJECT: // decode found invalid UTF-8 byte
  8806. {
  8807. std::string sn(3, '\0');
  8808. snprintf(&sn[0], sn.size(), "%.2X", byte);
  8809. JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn));
  8810. }
  8811. default: // decode found yet incomplete multi-byte code point
  8812. {
  8813. if (not ensure_ascii)
  8814. {
  8815. // code point will not be escaped - copy byte to buffer
  8816. string_buffer[bytes++] = s[i];
  8817. }
  8818. break;
  8819. }
  8820. }
  8821. }
  8822. if (JSON_LIKELY(state == UTF8_ACCEPT))
  8823. {
  8824. // write buffer
  8825. if (bytes > 0)
  8826. {
  8827. o->write_characters(string_buffer.data(), bytes);
  8828. }
  8829. }
  8830. else
  8831. {
  8832. // we finish reading, but do not accept: string was incomplete
  8833. std::string sn(3, '\0');
  8834. snprintf(&sn[0], sn.size(), "%.2X", static_cast<uint8_t>(s.back()));
  8835. JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn));
  8836. }
  8837. }
  8838. /*!
  8839. @brief dump an integer
  8840. Dump a given integer to output stream @a o. Works internally with
  8841. @a number_buffer.
  8842. @param[in] x integer number (signed or unsigned) to dump
  8843. @tparam NumberType either @a number_integer_t or @a number_unsigned_t
  8844. */
  8845. template<typename NumberType, detail::enable_if_t<
  8846. std::is_same<NumberType, number_unsigned_t>::value or
  8847. std::is_same<NumberType, number_integer_t>::value,
  8848. int> = 0>
  8849. void dump_integer(NumberType x)
  8850. {
  8851. // special case for "0"
  8852. if (x == 0)
  8853. {
  8854. o->write_character('0');
  8855. return;
  8856. }
  8857. const bool is_negative = (x <= 0) and (x != 0); // see issue #755
  8858. std::size_t i = 0;
  8859. while (x != 0)
  8860. {
  8861. // spare 1 byte for '\0'
  8862. assert(i < number_buffer.size() - 1);
  8863. const auto digit = std::labs(static_cast<long>(x % 10));
  8864. number_buffer[i++] = static_cast<char>('0' + digit);
  8865. x /= 10;
  8866. }
  8867. if (is_negative)
  8868. {
  8869. // make sure there is capacity for the '-'
  8870. assert(i < number_buffer.size() - 2);
  8871. number_buffer[i++] = '-';
  8872. }
  8873. std::reverse(number_buffer.begin(), number_buffer.begin() + i);
  8874. o->write_characters(number_buffer.data(), i);
  8875. }
  8876. /*!
  8877. @brief dump a floating-point number
  8878. Dump a given floating-point number to output stream @a o. Works internally
  8879. with @a number_buffer.
  8880. @param[in] x floating-point number to dump
  8881. */
  8882. void dump_float(number_float_t x)
  8883. {
  8884. // NaN / inf
  8885. if (not std::isfinite(x))
  8886. {
  8887. o->write_characters("null", 4);
  8888. return;
  8889. }
  8890. // If number_float_t is an IEEE-754 single or double precision number,
  8891. // use the Grisu2 algorithm to produce short numbers which are
  8892. // guaranteed to round-trip, using strtof and strtod, resp.
  8893. //
  8894. // NB: The test below works if <long double> == <double>.
  8895. static constexpr bool is_ieee_single_or_double
  8896. = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or
  8897. (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024);
  8898. dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>());
  8899. }
  8900. void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/)
  8901. {
  8902. char* begin = number_buffer.data();
  8903. char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x);
  8904. o->write_characters(begin, static_cast<size_t>(end - begin));
  8905. }
  8906. void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/)
  8907. {
  8908. // get number of digits for a float -> text -> float round-trip
  8909. static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10;
  8910. // the actual conversion
  8911. std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), "%.*g", d, x);
  8912. // negative value indicates an error
  8913. assert(len > 0);
  8914. // check if buffer was large enough
  8915. assert(static_cast<std::size_t>(len) < number_buffer.size());
  8916. // erase thousands separator
  8917. if (thousands_sep != '\0')
  8918. {
  8919. const auto end = std::remove(number_buffer.begin(),
  8920. number_buffer.begin() + len, thousands_sep);
  8921. std::fill(end, number_buffer.end(), '\0');
  8922. assert((end - number_buffer.begin()) <= len);
  8923. len = (end - number_buffer.begin());
  8924. }
  8925. // convert decimal point to '.'
  8926. if (decimal_point != '\0' and decimal_point != '.')
  8927. {
  8928. const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);
  8929. if (dec_pos != number_buffer.end())
  8930. {
  8931. *dec_pos = '.';
  8932. }
  8933. }
  8934. o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));
  8935. // determine if need to append ".0"
  8936. const bool value_is_int_like =
  8937. std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,
  8938. [](char c)
  8939. {
  8940. return (c == '.' or c == 'e');
  8941. });
  8942. if (value_is_int_like)
  8943. {
  8944. o->write_characters(".0", 2);
  8945. }
  8946. }
  8947. /*!
  8948. @brief check whether a string is UTF-8 encoded
  8949. The function checks each byte of a string whether it is UTF-8 encoded. The
  8950. result of the check is stored in the @a state parameter. The function must
  8951. be called initially with state 0 (accept). State 1 means the string must
  8952. be rejected, because the current byte is not allowed. If the string is
  8953. completely processed, but the state is non-zero, the string ended
  8954. prematurely; that is, the last byte indicated more bytes should have
  8955. followed.
  8956. @param[in,out] state the state of the decoding
  8957. @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT)
  8958. @param[in] byte next byte to decode
  8959. @return new state
  8960. @note The function has been edited: a std::array is used.
  8961. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
  8962. @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
  8963. */
  8964. static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept
  8965. {
  8966. static const std::array<uint8_t, 400> utf8d =
  8967. {
  8968. {
  8969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F
  8970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F
  8971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F
  8972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F
  8973. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F
  8974. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF
  8975. 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF
  8976. 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF
  8977. 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF
  8978. 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0
  8979. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2
  8980. 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4
  8981. 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6
  8982. 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8
  8983. }
  8984. };
  8985. const uint8_t type = utf8d[byte];
  8986. codep = (state != UTF8_ACCEPT)
  8987. ? (byte & 0x3fu) | (codep << 6)
  8988. : static_cast<uint32_t>(0xff >> type) & (byte);
  8989. state = utf8d[256u + state * 16u + type];
  8990. return state;
  8991. }
  8992. private:
  8993. /// the output of the serializer
  8994. output_adapter_t<char> o = nullptr;
  8995. /// a (hopefully) large enough character buffer
  8996. std::array<char, 64> number_buffer{{}};
  8997. /// the locale
  8998. const std::lconv* loc = nullptr;
  8999. /// the locale's thousand separator character
  9000. const char thousands_sep = '\0';
  9001. /// the locale's decimal point character
  9002. const char decimal_point = '\0';
  9003. /// string buffer
  9004. std::array<char, 512> string_buffer{{}};
  9005. /// the indentation character
  9006. const char indent_char;
  9007. /// the indentation string
  9008. string_t indent_string;
  9009. };
  9010. }
  9011. }
  9012. // #include <nlohmann/detail/json_ref.hpp>
  9013. #include <initializer_list>
  9014. #include <utility>
  9015. namespace nlohmann
  9016. {
  9017. namespace detail
  9018. {
  9019. template<typename BasicJsonType>
  9020. class json_ref
  9021. {
  9022. public:
  9023. using value_type = BasicJsonType;
  9024. json_ref(value_type&& value)
  9025. : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)
  9026. {}
  9027. json_ref(const value_type& value)
  9028. : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)
  9029. {}
  9030. json_ref(std::initializer_list<json_ref> init)
  9031. : owned_value(init), value_ref(&owned_value), is_rvalue(true)
  9032. {}
  9033. template<class... Args>
  9034. json_ref(Args&& ... args)
  9035. : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)
  9036. {}
  9037. // class should be movable only
  9038. json_ref(json_ref&&) = default;
  9039. json_ref(const json_ref&) = delete;
  9040. json_ref& operator=(const json_ref&) = delete;
  9041. value_type moved_or_copied() const
  9042. {
  9043. if (is_rvalue)
  9044. {
  9045. return std::move(*value_ref);
  9046. }
  9047. return *value_ref;
  9048. }
  9049. value_type const& operator*() const
  9050. {
  9051. return *static_cast<value_type const*>(value_ref);
  9052. }
  9053. value_type const* operator->() const
  9054. {
  9055. return static_cast<value_type const*>(value_ref);
  9056. }
  9057. private:
  9058. mutable value_type owned_value = nullptr;
  9059. value_type* value_ref = nullptr;
  9060. const bool is_rvalue;
  9061. };
  9062. }
  9063. }
  9064. // #include <nlohmann/detail/json_pointer.hpp>
  9065. #include <cassert> // assert
  9066. #include <numeric> // accumulate
  9067. #include <string> // string
  9068. #include <vector> // vector
  9069. // #include <nlohmann/detail/macro_scope.hpp>
  9070. // #include <nlohmann/detail/exceptions.hpp>
  9071. // #include <nlohmann/detail/value_t.hpp>
  9072. namespace nlohmann
  9073. {
  9074. template<typename BasicJsonType>
  9075. class json_pointer
  9076. {
  9077. // allow basic_json to access private members
  9078. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9079. friend class basic_json;
  9080. public:
  9081. /*!
  9082. @brief create JSON pointer
  9083. Create a JSON pointer according to the syntax described in
  9084. [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
  9085. @param[in] s string representing the JSON pointer; if omitted, the empty
  9086. string is assumed which references the whole JSON value
  9087. @throw parse_error.107 if the given JSON pointer @a s is nonempty and does
  9088. not begin with a slash (`/`); see example below
  9089. @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is
  9090. not followed by `0` (representing `~`) or `1` (representing `/`); see
  9091. example below
  9092. @liveexample{The example shows the construction several valid JSON pointers
  9093. as well as the exceptional behavior.,json_pointer}
  9094. @since version 2.0.0
  9095. */
  9096. explicit json_pointer(const std::string& s = "")
  9097. : reference_tokens(split(s))
  9098. {}
  9099. /*!
  9100. @brief return a string representation of the JSON pointer
  9101. @invariant For each JSON pointer `ptr`, it holds:
  9102. @code {.cpp}
  9103. ptr == json_pointer(ptr.to_string());
  9104. @endcode
  9105. @return a string representation of the JSON pointer
  9106. @liveexample{The example shows the result of `to_string`.,
  9107. json_pointer__to_string}
  9108. @since version 2.0.0
  9109. */
  9110. std::string to_string() const noexcept
  9111. {
  9112. return std::accumulate(reference_tokens.begin(), reference_tokens.end(),
  9113. std::string{},
  9114. [](const std::string & a, const std::string & b)
  9115. {
  9116. return a + "/" + escape(b);
  9117. });
  9118. }
  9119. /// @copydoc to_string()
  9120. operator std::string() const
  9121. {
  9122. return to_string();
  9123. }
  9124. /*!
  9125. @param[in] s reference token to be converted into an array index
  9126. @return integer representation of @a s
  9127. @throw out_of_range.404 if string @a s could not be converted to an integer
  9128. */
  9129. static int array_index(const std::string& s)
  9130. {
  9131. std::size_t processed_chars = 0;
  9132. const int res = std::stoi(s, &processed_chars);
  9133. // check if the string was completely read
  9134. if (JSON_UNLIKELY(processed_chars != s.size()))
  9135. {
  9136. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'"));
  9137. }
  9138. return res;
  9139. }
  9140. private:
  9141. /*!
  9142. @brief remove and return last reference pointer
  9143. @throw out_of_range.405 if JSON pointer has no parent
  9144. */
  9145. std::string pop_back()
  9146. {
  9147. if (JSON_UNLIKELY(is_root()))
  9148. {
  9149. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9150. }
  9151. auto last = reference_tokens.back();
  9152. reference_tokens.pop_back();
  9153. return last;
  9154. }
  9155. /// return whether pointer points to the root document
  9156. bool is_root() const
  9157. {
  9158. return reference_tokens.empty();
  9159. }
  9160. json_pointer top() const
  9161. {
  9162. if (JSON_UNLIKELY(is_root()))
  9163. {
  9164. JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent"));
  9165. }
  9166. json_pointer result = *this;
  9167. result.reference_tokens = {reference_tokens[0]};
  9168. return result;
  9169. }
  9170. /*!
  9171. @brief create and return a reference to the pointed to value
  9172. @complexity Linear in the number of reference tokens.
  9173. @throw parse_error.109 if array index is not a number
  9174. @throw type_error.313 if value cannot be unflattened
  9175. */
  9176. BasicJsonType& get_and_create(BasicJsonType& j) const
  9177. {
  9178. using size_type = typename BasicJsonType::size_type;
  9179. auto result = &j;
  9180. // in case no reference tokens exist, return a reference to the JSON value
  9181. // j which will be overwritten by a primitive value
  9182. for (const auto& reference_token : reference_tokens)
  9183. {
  9184. switch (result->m_type)
  9185. {
  9186. case detail::value_t::null:
  9187. {
  9188. if (reference_token == "0")
  9189. {
  9190. // start a new array if reference token is 0
  9191. result = &result->operator[](0);
  9192. }
  9193. else
  9194. {
  9195. // start a new object otherwise
  9196. result = &result->operator[](reference_token);
  9197. }
  9198. break;
  9199. }
  9200. case detail::value_t::object:
  9201. {
  9202. // create an entry in the object
  9203. result = &result->operator[](reference_token);
  9204. break;
  9205. }
  9206. case detail::value_t::array:
  9207. {
  9208. // create an entry in the array
  9209. JSON_TRY
  9210. {
  9211. result = &result->operator[](static_cast<size_type>(array_index(reference_token)));
  9212. }
  9213. JSON_CATCH(std::invalid_argument&)
  9214. {
  9215. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9216. }
  9217. break;
  9218. }
  9219. /*
  9220. The following code is only reached if there exists a reference
  9221. token _and_ the current value is primitive. In this case, we have
  9222. an error situation, because primitive values may only occur as
  9223. single value; that is, with an empty list of reference tokens.
  9224. */
  9225. default:
  9226. JSON_THROW(detail::type_error::create(313, "invalid value to unflatten"));
  9227. }
  9228. }
  9229. return *result;
  9230. }
  9231. /*!
  9232. @brief return a reference to the pointed to value
  9233. @note This version does not throw if a value is not present, but tries to
  9234. create nested values instead. For instance, calling this function
  9235. with pointer `"/this/that"` on a null value is equivalent to calling
  9236. `operator[]("this").operator[]("that")` on that value, effectively
  9237. changing the null value to an object.
  9238. @param[in] ptr a JSON value
  9239. @return reference to the JSON value pointed to by the JSON pointer
  9240. @complexity Linear in the length of the JSON pointer.
  9241. @throw parse_error.106 if an array index begins with '0'
  9242. @throw parse_error.109 if an array index was not a number
  9243. @throw out_of_range.404 if the JSON pointer can not be resolved
  9244. */
  9245. BasicJsonType& get_unchecked(BasicJsonType* ptr) const
  9246. {
  9247. using size_type = typename BasicJsonType::size_type;
  9248. for (const auto& reference_token : reference_tokens)
  9249. {
  9250. // convert null values to arrays or objects before continuing
  9251. if (ptr->m_type == detail::value_t::null)
  9252. {
  9253. // check if reference token is a number
  9254. const bool nums =
  9255. std::all_of(reference_token.begin(), reference_token.end(),
  9256. [](const char x)
  9257. {
  9258. return (x >= '0' and x <= '9');
  9259. });
  9260. // change value to array for numbers or "-" or to object otherwise
  9261. *ptr = (nums or reference_token == "-")
  9262. ? detail::value_t::array
  9263. : detail::value_t::object;
  9264. }
  9265. switch (ptr->m_type)
  9266. {
  9267. case detail::value_t::object:
  9268. {
  9269. // use unchecked object access
  9270. ptr = &ptr->operator[](reference_token);
  9271. break;
  9272. }
  9273. case detail::value_t::array:
  9274. {
  9275. // error condition (cf. RFC 6901, Sect. 4)
  9276. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9277. {
  9278. JSON_THROW(detail::parse_error::create(106, 0,
  9279. "array index '" + reference_token +
  9280. "' must not begin with '0'"));
  9281. }
  9282. if (reference_token == "-")
  9283. {
  9284. // explicitly treat "-" as index beyond the end
  9285. ptr = &ptr->operator[](ptr->m_value.array->size());
  9286. }
  9287. else
  9288. {
  9289. // convert array index to number; unchecked access
  9290. JSON_TRY
  9291. {
  9292. ptr = &ptr->operator[](
  9293. static_cast<size_type>(array_index(reference_token)));
  9294. }
  9295. JSON_CATCH(std::invalid_argument&)
  9296. {
  9297. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9298. }
  9299. }
  9300. break;
  9301. }
  9302. default:
  9303. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9304. }
  9305. }
  9306. return *ptr;
  9307. }
  9308. /*!
  9309. @throw parse_error.106 if an array index begins with '0'
  9310. @throw parse_error.109 if an array index was not a number
  9311. @throw out_of_range.402 if the array index '-' is used
  9312. @throw out_of_range.404 if the JSON pointer can not be resolved
  9313. */
  9314. BasicJsonType& get_checked(BasicJsonType* ptr) const
  9315. {
  9316. using size_type = typename BasicJsonType::size_type;
  9317. for (const auto& reference_token : reference_tokens)
  9318. {
  9319. switch (ptr->m_type)
  9320. {
  9321. case detail::value_t::object:
  9322. {
  9323. // note: at performs range check
  9324. ptr = &ptr->at(reference_token);
  9325. break;
  9326. }
  9327. case detail::value_t::array:
  9328. {
  9329. if (JSON_UNLIKELY(reference_token == "-"))
  9330. {
  9331. // "-" always fails the range check
  9332. JSON_THROW(detail::out_of_range::create(402,
  9333. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9334. ") is out of range"));
  9335. }
  9336. // error condition (cf. RFC 6901, Sect. 4)
  9337. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9338. {
  9339. JSON_THROW(detail::parse_error::create(106, 0,
  9340. "array index '" + reference_token +
  9341. "' must not begin with '0'"));
  9342. }
  9343. // note: at performs range check
  9344. JSON_TRY
  9345. {
  9346. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9347. }
  9348. JSON_CATCH(std::invalid_argument&)
  9349. {
  9350. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9351. }
  9352. break;
  9353. }
  9354. default:
  9355. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9356. }
  9357. }
  9358. return *ptr;
  9359. }
  9360. /*!
  9361. @brief return a const reference to the pointed to value
  9362. @param[in] ptr a JSON value
  9363. @return const reference to the JSON value pointed to by the JSON
  9364. pointer
  9365. @throw parse_error.106 if an array index begins with '0'
  9366. @throw parse_error.109 if an array index was not a number
  9367. @throw out_of_range.402 if the array index '-' is used
  9368. @throw out_of_range.404 if the JSON pointer can not be resolved
  9369. */
  9370. const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const
  9371. {
  9372. using size_type = typename BasicJsonType::size_type;
  9373. for (const auto& reference_token : reference_tokens)
  9374. {
  9375. switch (ptr->m_type)
  9376. {
  9377. case detail::value_t::object:
  9378. {
  9379. // use unchecked object access
  9380. ptr = &ptr->operator[](reference_token);
  9381. break;
  9382. }
  9383. case detail::value_t::array:
  9384. {
  9385. if (JSON_UNLIKELY(reference_token == "-"))
  9386. {
  9387. // "-" cannot be used for const access
  9388. JSON_THROW(detail::out_of_range::create(402,
  9389. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9390. ") is out of range"));
  9391. }
  9392. // error condition (cf. RFC 6901, Sect. 4)
  9393. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9394. {
  9395. JSON_THROW(detail::parse_error::create(106, 0,
  9396. "array index '" + reference_token +
  9397. "' must not begin with '0'"));
  9398. }
  9399. // use unchecked array access
  9400. JSON_TRY
  9401. {
  9402. ptr = &ptr->operator[](
  9403. static_cast<size_type>(array_index(reference_token)));
  9404. }
  9405. JSON_CATCH(std::invalid_argument&)
  9406. {
  9407. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9408. }
  9409. break;
  9410. }
  9411. default:
  9412. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9413. }
  9414. }
  9415. return *ptr;
  9416. }
  9417. /*!
  9418. @throw parse_error.106 if an array index begins with '0'
  9419. @throw parse_error.109 if an array index was not a number
  9420. @throw out_of_range.402 if the array index '-' is used
  9421. @throw out_of_range.404 if the JSON pointer can not be resolved
  9422. */
  9423. const BasicJsonType& get_checked(const BasicJsonType* ptr) const
  9424. {
  9425. using size_type = typename BasicJsonType::size_type;
  9426. for (const auto& reference_token : reference_tokens)
  9427. {
  9428. switch (ptr->m_type)
  9429. {
  9430. case detail::value_t::object:
  9431. {
  9432. // note: at performs range check
  9433. ptr = &ptr->at(reference_token);
  9434. break;
  9435. }
  9436. case detail::value_t::array:
  9437. {
  9438. if (JSON_UNLIKELY(reference_token == "-"))
  9439. {
  9440. // "-" always fails the range check
  9441. JSON_THROW(detail::out_of_range::create(402,
  9442. "array index '-' (" + std::to_string(ptr->m_value.array->size()) +
  9443. ") is out of range"));
  9444. }
  9445. // error condition (cf. RFC 6901, Sect. 4)
  9446. if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))
  9447. {
  9448. JSON_THROW(detail::parse_error::create(106, 0,
  9449. "array index '" + reference_token +
  9450. "' must not begin with '0'"));
  9451. }
  9452. // note: at performs range check
  9453. JSON_TRY
  9454. {
  9455. ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));
  9456. }
  9457. JSON_CATCH(std::invalid_argument&)
  9458. {
  9459. JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number"));
  9460. }
  9461. break;
  9462. }
  9463. default:
  9464. JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'"));
  9465. }
  9466. }
  9467. return *ptr;
  9468. }
  9469. /*!
  9470. @brief split the string input to reference tokens
  9471. @note This function is only called by the json_pointer constructor.
  9472. All exceptions below are documented there.
  9473. @throw parse_error.107 if the pointer is not empty or begins with '/'
  9474. @throw parse_error.108 if character '~' is not followed by '0' or '1'
  9475. */
  9476. static std::vector<std::string> split(const std::string& reference_string)
  9477. {
  9478. std::vector<std::string> result;
  9479. // special case: empty reference string -> no reference tokens
  9480. if (reference_string.empty())
  9481. {
  9482. return result;
  9483. }
  9484. // check if nonempty reference string begins with slash
  9485. if (JSON_UNLIKELY(reference_string[0] != '/'))
  9486. {
  9487. JSON_THROW(detail::parse_error::create(107, 1,
  9488. "JSON pointer must be empty or begin with '/' - was: '" +
  9489. reference_string + "'"));
  9490. }
  9491. // extract the reference tokens:
  9492. // - slash: position of the last read slash (or end of string)
  9493. // - start: position after the previous slash
  9494. for (
  9495. // search for the first slash after the first character
  9496. std::size_t slash = reference_string.find_first_of('/', 1),
  9497. // set the beginning of the first reference token
  9498. start = 1;
  9499. // we can stop if start == string::npos+1 = 0
  9500. start != 0;
  9501. // set the beginning of the next reference token
  9502. // (will eventually be 0 if slash == std::string::npos)
  9503. start = slash + 1,
  9504. // find next slash
  9505. slash = reference_string.find_first_of('/', start))
  9506. {
  9507. // use the text between the beginning of the reference token
  9508. // (start) and the last slash (slash).
  9509. auto reference_token = reference_string.substr(start, slash - start);
  9510. // check reference tokens are properly escaped
  9511. for (std::size_t pos = reference_token.find_first_of('~');
  9512. pos != std::string::npos;
  9513. pos = reference_token.find_first_of('~', pos + 1))
  9514. {
  9515. assert(reference_token[pos] == '~');
  9516. // ~ must be followed by 0 or 1
  9517. if (JSON_UNLIKELY(pos == reference_token.size() - 1 or
  9518. (reference_token[pos + 1] != '0' and
  9519. reference_token[pos + 1] != '1')))
  9520. {
  9521. JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'"));
  9522. }
  9523. }
  9524. // finally, store the reference token
  9525. unescape(reference_token);
  9526. result.push_back(reference_token);
  9527. }
  9528. return result;
  9529. }
  9530. /*!
  9531. @brief replace all occurrences of a substring by another string
  9532. @param[in,out] s the string to manipulate; changed so that all
  9533. occurrences of @a f are replaced with @a t
  9534. @param[in] f the substring to replace with @a t
  9535. @param[in] t the string to replace @a f
  9536. @pre The search string @a f must not be empty. **This precondition is
  9537. enforced with an assertion.**
  9538. @since version 2.0.0
  9539. */
  9540. static void replace_substring(std::string& s, const std::string& f,
  9541. const std::string& t)
  9542. {
  9543. assert(not f.empty());
  9544. for (auto pos = s.find(f); // find first occurrence of f
  9545. pos != std::string::npos; // make sure f was found
  9546. s.replace(pos, f.size(), t), // replace with t, and
  9547. pos = s.find(f, pos + t.size())) // find next occurrence of f
  9548. {}
  9549. }
  9550. /// escape "~"" to "~0" and "/" to "~1"
  9551. static std::string escape(std::string s)
  9552. {
  9553. replace_substring(s, "~", "~0");
  9554. replace_substring(s, "/", "~1");
  9555. return s;
  9556. }
  9557. /// unescape "~1" to tilde and "~0" to slash (order is important!)
  9558. static void unescape(std::string& s)
  9559. {
  9560. replace_substring(s, "~1", "/");
  9561. replace_substring(s, "~0", "~");
  9562. }
  9563. /*!
  9564. @param[in] reference_string the reference string to the current value
  9565. @param[in] value the value to consider
  9566. @param[in,out] result the result object to insert values to
  9567. @note Empty objects or arrays are flattened to `null`.
  9568. */
  9569. static void flatten(const std::string& reference_string,
  9570. const BasicJsonType& value,
  9571. BasicJsonType& result)
  9572. {
  9573. switch (value.m_type)
  9574. {
  9575. case detail::value_t::array:
  9576. {
  9577. if (value.m_value.array->empty())
  9578. {
  9579. // flatten empty array as null
  9580. result[reference_string] = nullptr;
  9581. }
  9582. else
  9583. {
  9584. // iterate array and use index as reference string
  9585. for (std::size_t i = 0; i < value.m_value.array->size(); ++i)
  9586. {
  9587. flatten(reference_string + "/" + std::to_string(i),
  9588. value.m_value.array->operator[](i), result);
  9589. }
  9590. }
  9591. break;
  9592. }
  9593. case detail::value_t::object:
  9594. {
  9595. if (value.m_value.object->empty())
  9596. {
  9597. // flatten empty object as null
  9598. result[reference_string] = nullptr;
  9599. }
  9600. else
  9601. {
  9602. // iterate object and use keys as reference string
  9603. for (const auto& element : *value.m_value.object)
  9604. {
  9605. flatten(reference_string + "/" + escape(element.first), element.second, result);
  9606. }
  9607. }
  9608. break;
  9609. }
  9610. default:
  9611. {
  9612. // add primitive value with its reference string
  9613. result[reference_string] = value;
  9614. break;
  9615. }
  9616. }
  9617. }
  9618. /*!
  9619. @param[in] value flattened JSON
  9620. @return unflattened JSON
  9621. @throw parse_error.109 if array index is not a number
  9622. @throw type_error.314 if value is not an object
  9623. @throw type_error.315 if object values are not primitive
  9624. @throw type_error.313 if value cannot be unflattened
  9625. */
  9626. static BasicJsonType
  9627. unflatten(const BasicJsonType& value)
  9628. {
  9629. if (JSON_UNLIKELY(not value.is_object()))
  9630. {
  9631. JSON_THROW(detail::type_error::create(314, "only objects can be unflattened"));
  9632. }
  9633. BasicJsonType result;
  9634. // iterate the JSON object values
  9635. for (const auto& element : *value.m_value.object)
  9636. {
  9637. if (JSON_UNLIKELY(not element.second.is_primitive()))
  9638. {
  9639. JSON_THROW(detail::type_error::create(315, "values in object must be primitive"));
  9640. }
  9641. // assign value to reference pointed to by JSON pointer; Note that if
  9642. // the JSON pointer is "" (i.e., points to the whole value), function
  9643. // get_and_create returns a reference to result itself. An assignment
  9644. // will then create a primitive value.
  9645. json_pointer(element.first).get_and_create(result) = element.second;
  9646. }
  9647. return result;
  9648. }
  9649. friend bool operator==(json_pointer const& lhs,
  9650. json_pointer const& rhs) noexcept
  9651. {
  9652. return (lhs.reference_tokens == rhs.reference_tokens);
  9653. }
  9654. friend bool operator!=(json_pointer const& lhs,
  9655. json_pointer const& rhs) noexcept
  9656. {
  9657. return not (lhs == rhs);
  9658. }
  9659. /// the reference tokens
  9660. std::vector<std::string> reference_tokens;
  9661. };
  9662. }
  9663. // #include <nlohmann/adl_serializer.hpp>
  9664. #include <utility>
  9665. // #include <nlohmann/detail/conversions/from_json.hpp>
  9666. // #include <nlohmann/detail/conversions/to_json.hpp>
  9667. namespace nlohmann
  9668. {
  9669. template<typename, typename>
  9670. struct adl_serializer
  9671. {
  9672. /*!
  9673. @brief convert a JSON value to any value type
  9674. This function is usually called by the `get()` function of the
  9675. @ref basic_json class (either explicit or via conversion operators).
  9676. @param[in] j JSON value to read from
  9677. @param[in,out] val value to write to
  9678. */
  9679. template<typename BasicJsonType, typename ValueType>
  9680. static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
  9681. noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
  9682. {
  9683. ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
  9684. }
  9685. /*!
  9686. @brief convert any value type to a JSON value
  9687. This function is usually called by the constructors of the @ref basic_json
  9688. class.
  9689. @param[in,out] j JSON value to write to
  9690. @param[in] val value to read from
  9691. */
  9692. template<typename BasicJsonType, typename ValueType>
  9693. static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
  9694. noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
  9695. {
  9696. ::nlohmann::to_json(j, std::forward<ValueType>(val));
  9697. }
  9698. };
  9699. }
  9700. /*!
  9701. @brief namespace for Niels Lohmann
  9702. @see https://github.com/nlohmann
  9703. @since version 1.0.0
  9704. */
  9705. namespace nlohmann
  9706. {
  9707. /*!
  9708. @brief a class to store JSON values
  9709. @tparam ObjectType type for JSON objects (`std::map` by default; will be used
  9710. in @ref object_t)
  9711. @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
  9712. in @ref array_t)
  9713. @tparam StringType type for JSON strings and object keys (`std::string` by
  9714. default; will be used in @ref string_t)
  9715. @tparam BooleanType type for JSON booleans (`bool` by default; will be used
  9716. in @ref boolean_t)
  9717. @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
  9718. default; will be used in @ref number_integer_t)
  9719. @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
  9720. `uint64_t` by default; will be used in @ref number_unsigned_t)
  9721. @tparam NumberFloatType type for JSON floating-point numbers (`double` by
  9722. default; will be used in @ref number_float_t)
  9723. @tparam AllocatorType type of the allocator to use (`std::allocator` by
  9724. default)
  9725. @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
  9726. and `from_json()` (@ref adl_serializer by default)
  9727. @requirement The class satisfies the following concept requirements:
  9728. - Basic
  9729. - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
  9730. JSON values can be default constructed. The result will be a JSON null
  9731. value.
  9732. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
  9733. A JSON value can be constructed from an rvalue argument.
  9734. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
  9735. A JSON value can be copy-constructed from an lvalue expression.
  9736. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
  9737. A JSON value van be assigned from an rvalue argument.
  9738. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
  9739. A JSON value can be copy-assigned from an lvalue expression.
  9740. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
  9741. JSON values can be destructed.
  9742. - Layout
  9743. - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
  9744. JSON values have
  9745. [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
  9746. All non-static data members are private and standard layout types, the
  9747. class has no virtual functions or (virtual) base classes.
  9748. - Library-wide
  9749. - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
  9750. JSON values can be compared with `==`, see @ref
  9751. operator==(const_reference,const_reference).
  9752. - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
  9753. JSON values can be compared with `<`, see @ref
  9754. operator<(const_reference,const_reference).
  9755. - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
  9756. Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
  9757. other compatible types, using unqualified function call @ref swap().
  9758. - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
  9759. JSON values can be compared against `std::nullptr_t` objects which are used
  9760. to model the `null` value.
  9761. - Container
  9762. - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
  9763. JSON values can be used like STL containers and provide iterator access.
  9764. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
  9765. JSON values can be used like STL containers and provide reverse iterator
  9766. access.
  9767. @invariant The member variables @a m_value and @a m_type have the following
  9768. relationship:
  9769. - If `m_type == value_t::object`, then `m_value.object != nullptr`.
  9770. - If `m_type == value_t::array`, then `m_value.array != nullptr`.
  9771. - If `m_type == value_t::string`, then `m_value.string != nullptr`.
  9772. The invariants are checked by member function assert_invariant().
  9773. @internal
  9774. @note ObjectType trick from http://stackoverflow.com/a/9860911
  9775. @endinternal
  9776. @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
  9777. Format](http://rfc7159.net/rfc7159)
  9778. @since version 1.0.0
  9779. @nosubgrouping
  9780. */
  9781. NLOHMANN_BASIC_JSON_TPL_DECLARATION
  9782. class basic_json
  9783. {
  9784. private:
  9785. template<detail::value_t> friend struct detail::external_constructor;
  9786. friend ::nlohmann::json_pointer<basic_json>;
  9787. friend ::nlohmann::detail::parser<basic_json>;
  9788. friend ::nlohmann::detail::serializer<basic_json>;
  9789. template<typename BasicJsonType>
  9790. friend class ::nlohmann::detail::iter_impl;
  9791. template<typename BasicJsonType, typename CharType>
  9792. friend class ::nlohmann::detail::binary_writer;
  9793. template<typename BasicJsonType, typename SAX>
  9794. friend class ::nlohmann::detail::binary_reader;
  9795. template<typename BasicJsonType>
  9796. friend class ::nlohmann::detail::json_sax_dom_parser;
  9797. template<typename BasicJsonType>
  9798. friend class ::nlohmann::detail::json_sax_dom_callback_parser;
  9799. /// workaround type for MSVC
  9800. using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
  9801. // convenience aliases for types residing in namespace detail;
  9802. using lexer = ::nlohmann::detail::lexer<basic_json>;
  9803. using parser = ::nlohmann::detail::parser<basic_json>;
  9804. using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
  9805. template<typename BasicJsonType>
  9806. using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
  9807. template<typename BasicJsonType>
  9808. using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
  9809. template<typename Iterator>
  9810. using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
  9811. template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
  9812. template<typename CharType>
  9813. using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
  9814. using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
  9815. template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
  9816. using serializer = ::nlohmann::detail::serializer<basic_json>;
  9817. public:
  9818. using value_t = detail::value_t;
  9819. /// JSON Pointer, see @ref nlohmann::json_pointer
  9820. using json_pointer = ::nlohmann::json_pointer<basic_json>;
  9821. template<typename T, typename SFINAE>
  9822. using json_serializer = JSONSerializer<T, SFINAE>;
  9823. /// helper type for initializer lists of basic_json values
  9824. using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
  9825. using input_format_t = detail::input_format_t;
  9826. /// SAX interface type, see @ref nlohmann::json_sax
  9827. using json_sax_t = json_sax<basic_json>;
  9828. ////////////////
  9829. // exceptions //
  9830. ////////////////
  9831. /// @name exceptions
  9832. /// Classes to implement user-defined exceptions.
  9833. /// @{
  9834. /// @copydoc detail::exception
  9835. using exception = detail::exception;
  9836. /// @copydoc detail::parse_error
  9837. using parse_error = detail::parse_error;
  9838. /// @copydoc detail::invalid_iterator
  9839. using invalid_iterator = detail::invalid_iterator;
  9840. /// @copydoc detail::type_error
  9841. using type_error = detail::type_error;
  9842. /// @copydoc detail::out_of_range
  9843. using out_of_range = detail::out_of_range;
  9844. /// @copydoc detail::other_error
  9845. using other_error = detail::other_error;
  9846. /// @}
  9847. /////////////////////
  9848. // container types //
  9849. /////////////////////
  9850. /// @name container types
  9851. /// The canonic container types to use @ref basic_json like any other STL
  9852. /// container.
  9853. /// @{
  9854. /// the type of elements in a basic_json container
  9855. using value_type = basic_json;
  9856. /// the type of an element reference
  9857. using reference = value_type&;
  9858. /// the type of an element const reference
  9859. using const_reference = const value_type&;
  9860. /// a type to represent differences between iterators
  9861. using difference_type = std::ptrdiff_t;
  9862. /// a type to represent container sizes
  9863. using size_type = std::size_t;
  9864. /// the allocator type
  9865. using allocator_type = AllocatorType<basic_json>;
  9866. /// the type of an element pointer
  9867. using pointer = typename std::allocator_traits<allocator_type>::pointer;
  9868. /// the type of an element const pointer
  9869. using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
  9870. /// an iterator for a basic_json container
  9871. using iterator = iter_impl<basic_json>;
  9872. /// a const iterator for a basic_json container
  9873. using const_iterator = iter_impl<const basic_json>;
  9874. /// a reverse iterator for a basic_json container
  9875. using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
  9876. /// a const reverse iterator for a basic_json container
  9877. using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
  9878. /// @}
  9879. /*!
  9880. @brief returns the allocator associated with the container
  9881. */
  9882. static allocator_type get_allocator()
  9883. {
  9884. return allocator_type();
  9885. }
  9886. /*!
  9887. @brief returns version information on the library
  9888. This function returns a JSON object with information about the library,
  9889. including the version number and information on the platform and compiler.
  9890. @return JSON object holding version information
  9891. key | description
  9892. ----------- | ---------------
  9893. `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
  9894. `copyright` | The copyright line for the library as string.
  9895. `name` | The name of the library as string.
  9896. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
  9897. `url` | The URL of the project as string.
  9898. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
  9899. @liveexample{The following code shows an example output of the `meta()`
  9900. function.,meta}
  9901. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  9902. changes to any JSON value.
  9903. @complexity Constant.
  9904. @since 2.1.0
  9905. */
  9906. static basic_json meta()
  9907. {
  9908. basic_json result;
  9909. result["copyright"] = "(C) 2013-2017 Niels Lohmann";
  9910. result["name"] = "JSON for Modern C++";
  9911. result["url"] = "https://github.com/nlohmann/json";
  9912. result["version"]["string"] =
  9913. std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
  9914. std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
  9915. std::to_string(NLOHMANN_JSON_VERSION_PATCH);
  9916. result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
  9917. result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
  9918. result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
  9919. #ifdef _WIN32
  9920. result["platform"] = "win32";
  9921. #elif defined __linux__
  9922. result["platform"] = "linux";
  9923. #elif defined __APPLE__
  9924. result["platform"] = "apple";
  9925. #elif defined __unix__
  9926. result["platform"] = "unix";
  9927. #else
  9928. result["platform"] = "unknown";
  9929. #endif
  9930. #if defined(__ICC) || defined(__INTEL_COMPILER)
  9931. result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
  9932. #elif defined(__clang__)
  9933. result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
  9934. #elif defined(__GNUC__) || defined(__GNUG__)
  9935. result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
  9936. #elif defined(__HP_cc) || defined(__HP_aCC)
  9937. result["compiler"] = "hp"
  9938. #elif defined(__IBMCPP__)
  9939. result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
  9940. #elif defined(_MSC_VER)
  9941. result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
  9942. #elif defined(__PGI)
  9943. result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
  9944. #elif defined(__SUNPRO_CC)
  9945. result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
  9946. #else
  9947. result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
  9948. #endif
  9949. #ifdef __cplusplus
  9950. result["compiler"]["c++"] = std::to_string(__cplusplus);
  9951. #else
  9952. result["compiler"]["c++"] = "unknown";
  9953. #endif
  9954. return result;
  9955. }
  9956. ///////////////////////////
  9957. // JSON value data types //
  9958. ///////////////////////////
  9959. /// @name JSON value data types
  9960. /// The data types to store a JSON value. These types are derived from
  9961. /// the template arguments passed to class @ref basic_json.
  9962. /// @{
  9963. #if defined(JSON_HAS_CPP_14)
  9964. // Use transparent comparator if possible, combined with perfect forwarding
  9965. // on find() and count() calls prevents unnecessary string construction.
  9966. using object_comparator_t = std::less<>;
  9967. #else
  9968. using object_comparator_t = std::less<StringType>;
  9969. #endif
  9970. /*!
  9971. @brief a type for an object
  9972. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
  9973. > An object is an unordered collection of zero or more name/value pairs,
  9974. > where a name is a string and a value is a string, number, boolean, null,
  9975. > object, or array.
  9976. To store objects in C++, a type is defined by the template parameters
  9977. described below.
  9978. @tparam ObjectType the container to store objects (e.g., `std::map` or
  9979. `std::unordered_map`)
  9980. @tparam StringType the type of the keys or names (e.g., `std::string`).
  9981. The comparison function `std::less<StringType>` is used to order elements
  9982. inside the container.
  9983. @tparam AllocatorType the allocator to use for objects (e.g.,
  9984. `std::allocator`)
  9985. #### Default type
  9986. With the default values for @a ObjectType (`std::map`), @a StringType
  9987. (`std::string`), and @a AllocatorType (`std::allocator`), the default
  9988. value for @a object_t is:
  9989. @code {.cpp}
  9990. std::map<
  9991. std::string, // key_type
  9992. basic_json, // value_type
  9993. std::less<std::string>, // key_compare
  9994. std::allocator<std::pair<const std::string, basic_json>> // allocator_type
  9995. >
  9996. @endcode
  9997. #### Behavior
  9998. The choice of @a object_t influences the behavior of the JSON class. With
  9999. the default type, objects have the following behavior:
  10000. - When all names are unique, objects will be interoperable in the sense
  10001. that all software implementations receiving that object will agree on
  10002. the name-value mappings.
  10003. - When the names within an object are not unique, it is unspecified which
  10004. one of the values for a given key will be chosen. For instance,
  10005. `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
  10006. `{"key": 2}`.
  10007. - Internally, name/value pairs are stored in lexicographical order of the
  10008. names. Objects will also be serialized (see @ref dump) in this order.
  10009. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
  10010. and serialized as `{"a": 2, "b": 1}`.
  10011. - When comparing objects, the order of the name/value pairs is irrelevant.
  10012. This makes objects interoperable in the sense that they will not be
  10013. affected by these differences. For instance, `{"b": 1, "a": 2}` and
  10014. `{"a": 2, "b": 1}` will be treated as equal.
  10015. #### Limits
  10016. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  10017. > An implementation may set limits on the maximum depth of nesting.
  10018. In this class, the object's limit of nesting is not explicitly constrained.
  10019. However, a maximum depth of nesting may be introduced by the compiler or
  10020. runtime environment. A theoretical limit can be queried by calling the
  10021. @ref max_size function of a JSON object.
  10022. #### Storage
  10023. Objects are stored as pointers in a @ref basic_json type. That is, for any
  10024. access to object values, a pointer of type `object_t*` must be
  10025. dereferenced.
  10026. @sa @ref array_t -- type for an array value
  10027. @since version 1.0.0
  10028. @note The order name/value pairs are added to the object is *not*
  10029. preserved by the library. Therefore, iterating an object may return
  10030. name/value pairs in a different order than they were originally stored. In
  10031. fact, keys will be traversed in alphabetical order as `std::map` with
  10032. `std::less` is used by default. Please note this behavior conforms to [RFC
  10033. 7159](http://rfc7159.net/rfc7159), because any order implements the
  10034. specified "unordered" nature of JSON objects.
  10035. */
  10036. using object_t = ObjectType<StringType,
  10037. basic_json,
  10038. object_comparator_t,
  10039. AllocatorType<std::pair<const StringType,
  10040. basic_json>>>;
  10041. /*!
  10042. @brief a type for an array
  10043. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
  10044. > An array is an ordered sequence of zero or more values.
  10045. To store objects in C++, a type is defined by the template parameters
  10046. explained below.
  10047. @tparam ArrayType container type to store arrays (e.g., `std::vector` or
  10048. `std::list`)
  10049. @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
  10050. #### Default type
  10051. With the default values for @a ArrayType (`std::vector`) and @a
  10052. AllocatorType (`std::allocator`), the default value for @a array_t is:
  10053. @code {.cpp}
  10054. std::vector<
  10055. basic_json, // value_type
  10056. std::allocator<basic_json> // allocator_type
  10057. >
  10058. @endcode
  10059. #### Limits
  10060. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  10061. > An implementation may set limits on the maximum depth of nesting.
  10062. In this class, the array's limit of nesting is not explicitly constrained.
  10063. However, a maximum depth of nesting may be introduced by the compiler or
  10064. runtime environment. A theoretical limit can be queried by calling the
  10065. @ref max_size function of a JSON array.
  10066. #### Storage
  10067. Arrays are stored as pointers in a @ref basic_json type. That is, for any
  10068. access to array values, a pointer of type `array_t*` must be dereferenced.
  10069. @sa @ref object_t -- type for an object value
  10070. @since version 1.0.0
  10071. */
  10072. using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
  10073. /*!
  10074. @brief a type for a string
  10075. [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
  10076. > A string is a sequence of zero or more Unicode characters.
  10077. To store objects in C++, a type is defined by the template parameter
  10078. described below. Unicode values are split by the JSON class into
  10079. byte-sized characters during deserialization.
  10080. @tparam StringType the container to store strings (e.g., `std::string`).
  10081. Note this container is used for keys/names in objects, see @ref object_t.
  10082. #### Default type
  10083. With the default values for @a StringType (`std::string`), the default
  10084. value for @a string_t is:
  10085. @code {.cpp}
  10086. std::string
  10087. @endcode
  10088. #### Encoding
  10089. Strings are stored in UTF-8 encoding. Therefore, functions like
  10090. `std::string::size()` or `std::string::length()` return the number of
  10091. bytes in the string rather than the number of characters or glyphs.
  10092. #### String comparison
  10093. [RFC 7159](http://rfc7159.net/rfc7159) states:
  10094. > Software implementations are typically required to test names of object
  10095. > members for equality. Implementations that transform the textual
  10096. > representation into sequences of Unicode code units and then perform the
  10097. > comparison numerically, code unit by code unit, are interoperable in the
  10098. > sense that implementations will agree in all cases on equality or
  10099. > inequality of two strings. For example, implementations that compare
  10100. > strings with escaped characters unconverted may incorrectly find that
  10101. > `"a\\b"` and `"a\u005Cb"` are not equal.
  10102. This implementation is interoperable as it does compare strings code unit
  10103. by code unit.
  10104. #### Storage
  10105. String values are stored as pointers in a @ref basic_json type. That is,
  10106. for any access to string values, a pointer of type `string_t*` must be
  10107. dereferenced.
  10108. @since version 1.0.0
  10109. */
  10110. using string_t = StringType;
  10111. /*!
  10112. @brief a type for a boolean
  10113. [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
  10114. type which differentiates the two literals `true` and `false`.
  10115. To store objects in C++, a type is defined by the template parameter @a
  10116. BooleanType which chooses the type to use.
  10117. #### Default type
  10118. With the default values for @a BooleanType (`bool`), the default value for
  10119. @a boolean_t is:
  10120. @code {.cpp}
  10121. bool
  10122. @endcode
  10123. #### Storage
  10124. Boolean values are stored directly inside a @ref basic_json type.
  10125. @since version 1.0.0
  10126. */
  10127. using boolean_t = BooleanType;
  10128. /*!
  10129. @brief a type for a number (integer)
  10130. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  10131. > The representation of numbers is similar to that used in most
  10132. > programming languages. A number is represented in base 10 using decimal
  10133. > digits. It contains an integer component that may be prefixed with an
  10134. > optional minus sign, which may be followed by a fraction part and/or an
  10135. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  10136. > cannot be represented in the grammar below (such as Infinity and NaN)
  10137. > are not permitted.
  10138. This description includes both integer and floating-point numbers.
  10139. However, C++ allows more precise storage if it is known whether the number
  10140. is a signed integer, an unsigned integer or a floating-point number.
  10141. Therefore, three different types, @ref number_integer_t, @ref
  10142. number_unsigned_t and @ref number_float_t are used.
  10143. To store integer numbers in C++, a type is defined by the template
  10144. parameter @a NumberIntegerType which chooses the type to use.
  10145. #### Default type
  10146. With the default values for @a NumberIntegerType (`int64_t`), the default
  10147. value for @a number_integer_t is:
  10148. @code {.cpp}
  10149. int64_t
  10150. @endcode
  10151. #### Default behavior
  10152. - The restrictions about leading zeros is not enforced in C++. Instead,
  10153. leading zeros in integer literals lead to an interpretation as octal
  10154. number. Internally, the value will be stored as decimal number. For
  10155. instance, the C++ integer literal `010` will be serialized to `8`.
  10156. During deserialization, leading zeros yield an error.
  10157. - Not-a-number (NaN) values will be serialized to `null`.
  10158. #### Limits
  10159. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  10160. > An implementation may set limits on the range and precision of numbers.
  10161. When the default type is used, the maximal integer number that can be
  10162. stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
  10163. that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
  10164. that are out of range will yield over/underflow when used in a
  10165. constructor. During deserialization, too large or small integer numbers
  10166. will be automatically be stored as @ref number_unsigned_t or @ref
  10167. number_float_t.
  10168. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  10169. > Note that when such software is used, numbers that are integers and are
  10170. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  10171. > that implementations will agree exactly on their numeric values.
  10172. As this range is a subrange of the exactly supported range [INT64_MIN,
  10173. INT64_MAX], this class's integer type is interoperable.
  10174. #### Storage
  10175. Integer number values are stored directly inside a @ref basic_json type.
  10176. @sa @ref number_float_t -- type for number values (floating-point)
  10177. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  10178. @since version 1.0.0
  10179. */
  10180. using number_integer_t = NumberIntegerType;
  10181. /*!
  10182. @brief a type for a number (unsigned)
  10183. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  10184. > The representation of numbers is similar to that used in most
  10185. > programming languages. A number is represented in base 10 using decimal
  10186. > digits. It contains an integer component that may be prefixed with an
  10187. > optional minus sign, which may be followed by a fraction part and/or an
  10188. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  10189. > cannot be represented in the grammar below (such as Infinity and NaN)
  10190. > are not permitted.
  10191. This description includes both integer and floating-point numbers.
  10192. However, C++ allows more precise storage if it is known whether the number
  10193. is a signed integer, an unsigned integer or a floating-point number.
  10194. Therefore, three different types, @ref number_integer_t, @ref
  10195. number_unsigned_t and @ref number_float_t are used.
  10196. To store unsigned integer numbers in C++, a type is defined by the
  10197. template parameter @a NumberUnsignedType which chooses the type to use.
  10198. #### Default type
  10199. With the default values for @a NumberUnsignedType (`uint64_t`), the
  10200. default value for @a number_unsigned_t is:
  10201. @code {.cpp}
  10202. uint64_t
  10203. @endcode
  10204. #### Default behavior
  10205. - The restrictions about leading zeros is not enforced in C++. Instead,
  10206. leading zeros in integer literals lead to an interpretation as octal
  10207. number. Internally, the value will be stored as decimal number. For
  10208. instance, the C++ integer literal `010` will be serialized to `8`.
  10209. During deserialization, leading zeros yield an error.
  10210. - Not-a-number (NaN) values will be serialized to `null`.
  10211. #### Limits
  10212. [RFC 7159](http://rfc7159.net/rfc7159) specifies:
  10213. > An implementation may set limits on the range and precision of numbers.
  10214. When the default type is used, the maximal integer number that can be
  10215. stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
  10216. number that can be stored is `0`. Integer numbers that are out of range
  10217. will yield over/underflow when used in a constructor. During
  10218. deserialization, too large or small integer numbers will be automatically
  10219. be stored as @ref number_integer_t or @ref number_float_t.
  10220. [RFC 7159](http://rfc7159.net/rfc7159) further states:
  10221. > Note that when such software is used, numbers that are integers and are
  10222. > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
  10223. > that implementations will agree exactly on their numeric values.
  10224. As this range is a subrange (when considered in conjunction with the
  10225. number_integer_t type) of the exactly supported range [0, UINT64_MAX],
  10226. this class's integer type is interoperable.
  10227. #### Storage
  10228. Integer number values are stored directly inside a @ref basic_json type.
  10229. @sa @ref number_float_t -- type for number values (floating-point)
  10230. @sa @ref number_integer_t -- type for number values (integer)
  10231. @since version 2.0.0
  10232. */
  10233. using number_unsigned_t = NumberUnsignedType;
  10234. /*!
  10235. @brief a type for a number (floating-point)
  10236. [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
  10237. > The representation of numbers is similar to that used in most
  10238. > programming languages. A number is represented in base 10 using decimal
  10239. > digits. It contains an integer component that may be prefixed with an
  10240. > optional minus sign, which may be followed by a fraction part and/or an
  10241. > exponent part. Leading zeros are not allowed. (...) Numeric values that
  10242. > cannot be represented in the grammar below (such as Infinity and NaN)
  10243. > are not permitted.
  10244. This description includes both integer and floating-point numbers.
  10245. However, C++ allows more precise storage if it is known whether the number
  10246. is a signed integer, an unsigned integer or a floating-point number.
  10247. Therefore, three different types, @ref number_integer_t, @ref
  10248. number_unsigned_t and @ref number_float_t are used.
  10249. To store floating-point numbers in C++, a type is defined by the template
  10250. parameter @a NumberFloatType which chooses the type to use.
  10251. #### Default type
  10252. With the default values for @a NumberFloatType (`double`), the default
  10253. value for @a number_float_t is:
  10254. @code {.cpp}
  10255. double
  10256. @endcode
  10257. #### Default behavior
  10258. - The restrictions about leading zeros is not enforced in C++. Instead,
  10259. leading zeros in floating-point literals will be ignored. Internally,
  10260. the value will be stored as decimal number. For instance, the C++
  10261. floating-point literal `01.2` will be serialized to `1.2`. During
  10262. deserialization, leading zeros yield an error.
  10263. - Not-a-number (NaN) values will be serialized to `null`.
  10264. #### Limits
  10265. [RFC 7159](http://rfc7159.net/rfc7159) states:
  10266. > This specification allows implementations to set limits on the range and
  10267. > precision of numbers accepted. Since software that implements IEEE
  10268. > 754-2008 binary64 (double precision) numbers is generally available and
  10269. > widely used, good interoperability can be achieved by implementations
  10270. > that expect no more precision or range than these provide, in the sense
  10271. > that implementations will approximate JSON numbers within the expected
  10272. > precision.
  10273. This implementation does exactly follow this approach, as it uses double
  10274. precision floating-point numbers. Note values smaller than
  10275. `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
  10276. will be stored as NaN internally and be serialized to `null`.
  10277. #### Storage
  10278. Floating-point number values are stored directly inside a @ref basic_json
  10279. type.
  10280. @sa @ref number_integer_t -- type for number values (integer)
  10281. @sa @ref number_unsigned_t -- type for number values (unsigned integer)
  10282. @since version 1.0.0
  10283. */
  10284. using number_float_t = NumberFloatType;
  10285. /// @}
  10286. private:
  10287. /// helper for exception-safe object creation
  10288. template<typename T, typename... Args>
  10289. static T* create(Args&& ... args)
  10290. {
  10291. AllocatorType<T> alloc;
  10292. using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
  10293. auto deleter = [&](T * object)
  10294. {
  10295. AllocatorTraits::deallocate(alloc, object, 1);
  10296. };
  10297. std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
  10298. AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
  10299. assert(object != nullptr);
  10300. return object.release();
  10301. }
  10302. ////////////////////////
  10303. // JSON value storage //
  10304. ////////////////////////
  10305. /*!
  10306. @brief a JSON value
  10307. The actual storage for a JSON value of the @ref basic_json class. This
  10308. union combines the different storage types for the JSON value types
  10309. defined in @ref value_t.
  10310. JSON type | value_t type | used type
  10311. --------- | --------------- | ------------------------
  10312. object | object | pointer to @ref object_t
  10313. array | array | pointer to @ref array_t
  10314. string | string | pointer to @ref string_t
  10315. boolean | boolean | @ref boolean_t
  10316. number | number_integer | @ref number_integer_t
  10317. number | number_unsigned | @ref number_unsigned_t
  10318. number | number_float | @ref number_float_t
  10319. null | null | *no value is stored*
  10320. @note Variable-length types (objects, arrays, and strings) are stored as
  10321. pointers. The size of the union should not exceed 64 bits if the default
  10322. value types are used.
  10323. @since version 1.0.0
  10324. */
  10325. union json_value
  10326. {
  10327. /// object (stored with pointer to save storage)
  10328. object_t* object;
  10329. /// array (stored with pointer to save storage)
  10330. array_t* array;
  10331. /// string (stored with pointer to save storage)
  10332. string_t* string;
  10333. /// boolean
  10334. boolean_t boolean;
  10335. /// number (integer)
  10336. number_integer_t number_integer;
  10337. /// number (unsigned integer)
  10338. number_unsigned_t number_unsigned;
  10339. /// number (floating-point)
  10340. number_float_t number_float;
  10341. /// default constructor (for null values)
  10342. json_value() = default;
  10343. /// constructor for booleans
  10344. json_value(boolean_t v) noexcept : boolean(v) {}
  10345. /// constructor for numbers (integer)
  10346. json_value(number_integer_t v) noexcept : number_integer(v) {}
  10347. /// constructor for numbers (unsigned)
  10348. json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
  10349. /// constructor for numbers (floating-point)
  10350. json_value(number_float_t v) noexcept : number_float(v) {}
  10351. /// constructor for empty values of a given type
  10352. json_value(value_t t)
  10353. {
  10354. switch (t)
  10355. {
  10356. case value_t::object:
  10357. {
  10358. object = create<object_t>();
  10359. break;
  10360. }
  10361. case value_t::array:
  10362. {
  10363. array = create<array_t>();
  10364. break;
  10365. }
  10366. case value_t::string:
  10367. {
  10368. string = create<string_t>("");
  10369. break;
  10370. }
  10371. case value_t::boolean:
  10372. {
  10373. boolean = boolean_t(false);
  10374. break;
  10375. }
  10376. case value_t::number_integer:
  10377. {
  10378. number_integer = number_integer_t(0);
  10379. break;
  10380. }
  10381. case value_t::number_unsigned:
  10382. {
  10383. number_unsigned = number_unsigned_t(0);
  10384. break;
  10385. }
  10386. case value_t::number_float:
  10387. {
  10388. number_float = number_float_t(0.0);
  10389. break;
  10390. }
  10391. case value_t::null:
  10392. {
  10393. object = nullptr; // silence warning, see #821
  10394. break;
  10395. }
  10396. default:
  10397. {
  10398. object = nullptr; // silence warning, see #821
  10399. if (JSON_UNLIKELY(t == value_t::null))
  10400. {
  10401. JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.2.0")); // LCOV_EXCL_LINE
  10402. }
  10403. break;
  10404. }
  10405. }
  10406. }
  10407. /// constructor for strings
  10408. json_value(const string_t& value)
  10409. {
  10410. string = create<string_t>(value);
  10411. }
  10412. /// constructor for rvalue strings
  10413. json_value(string_t&& value)
  10414. {
  10415. string = create<string_t>(std::move(value));
  10416. }
  10417. /// constructor for objects
  10418. json_value(const object_t& value)
  10419. {
  10420. object = create<object_t>(value);
  10421. }
  10422. /// constructor for rvalue objects
  10423. json_value(object_t&& value)
  10424. {
  10425. object = create<object_t>(std::move(value));
  10426. }
  10427. /// constructor for arrays
  10428. json_value(const array_t& value)
  10429. {
  10430. array = create<array_t>(value);
  10431. }
  10432. /// constructor for rvalue arrays
  10433. json_value(array_t&& value)
  10434. {
  10435. array = create<array_t>(std::move(value));
  10436. }
  10437. void destroy(value_t t) noexcept
  10438. {
  10439. switch (t)
  10440. {
  10441. case value_t::object:
  10442. {
  10443. AllocatorType<object_t> alloc;
  10444. std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
  10445. std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
  10446. break;
  10447. }
  10448. case value_t::array:
  10449. {
  10450. AllocatorType<array_t> alloc;
  10451. std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
  10452. std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
  10453. break;
  10454. }
  10455. case value_t::string:
  10456. {
  10457. AllocatorType<string_t> alloc;
  10458. std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
  10459. std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
  10460. break;
  10461. }
  10462. default:
  10463. {
  10464. break;
  10465. }
  10466. }
  10467. }
  10468. };
  10469. /*!
  10470. @brief checks the class invariants
  10471. This function asserts the class invariants. It needs to be called at the
  10472. end of every constructor to make sure that created objects respect the
  10473. invariant. Furthermore, it has to be called each time the type of a JSON
  10474. value is changed, because the invariant expresses a relationship between
  10475. @a m_type and @a m_value.
  10476. */
  10477. void assert_invariant() const noexcept
  10478. {
  10479. assert(m_type != value_t::object or m_value.object != nullptr);
  10480. assert(m_type != value_t::array or m_value.array != nullptr);
  10481. assert(m_type != value_t::string or m_value.string != nullptr);
  10482. }
  10483. public:
  10484. //////////////////////////
  10485. // JSON parser callback //
  10486. //////////////////////////
  10487. /*!
  10488. @brief parser event types
  10489. The parser callback distinguishes the following events:
  10490. - `object_start`: the parser read `{` and started to process a JSON object
  10491. - `key`: the parser read a key of a value in an object
  10492. - `object_end`: the parser read `}` and finished processing a JSON object
  10493. - `array_start`: the parser read `[` and started to process a JSON array
  10494. - `array_end`: the parser read `]` and finished processing a JSON array
  10495. - `value`: the parser finished reading a JSON value
  10496. @image html callback_events.png "Example when certain parse events are triggered"
  10497. @sa @ref parser_callback_t for more information and examples
  10498. */
  10499. using parse_event_t = typename parser::parse_event_t;
  10500. /*!
  10501. @brief per-element parser callback type
  10502. With a parser callback function, the result of parsing a JSON text can be
  10503. influenced. When passed to @ref parse, it is called on certain events
  10504. (passed as @ref parse_event_t via parameter @a event) with a set recursion
  10505. depth @a depth and context JSON value @a parsed. The return value of the
  10506. callback function is a boolean indicating whether the element that emitted
  10507. the callback shall be kept or not.
  10508. We distinguish six scenarios (determined by the event type) in which the
  10509. callback function can be called. The following table describes the values
  10510. of the parameters @a depth, @a event, and @a parsed.
  10511. parameter @a event | description | parameter @a depth | parameter @a parsed
  10512. ------------------ | ----------- | ------------------ | -------------------
  10513. 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
  10514. 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
  10515. 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
  10516. 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
  10517. 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
  10518. parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
  10519. @image html callback_events.png "Example when certain parse events are triggered"
  10520. Discarding a value (i.e., returning `false`) has different effects
  10521. depending on the context in which function was called:
  10522. - Discarded values in structured types are skipped. That is, the parser
  10523. will behave as if the discarded value was never read.
  10524. - In case a value outside a structured type is skipped, it is replaced
  10525. with `null`. This case happens if the top-level element is skipped.
  10526. @param[in] depth the depth of the recursion during parsing
  10527. @param[in] event an event of type parse_event_t indicating the context in
  10528. the callback function has been called
  10529. @param[in,out] parsed the current intermediate parse result; note that
  10530. writing to this value has no effect for parse_event_t::key events
  10531. @return Whether the JSON value which called the function during parsing
  10532. should be kept (`true`) or not (`false`). In the latter case, it is either
  10533. skipped completely or replaced by an empty discarded object.
  10534. @sa @ref parse for examples
  10535. @since version 1.0.0
  10536. */
  10537. using parser_callback_t = typename parser::parser_callback_t;
  10538. //////////////////
  10539. // constructors //
  10540. //////////////////
  10541. /// @name constructors and destructors
  10542. /// Constructors of class @ref basic_json, copy/move constructor, copy
  10543. /// assignment, static functions creating objects, and the destructor.
  10544. /// @{
  10545. /*!
  10546. @brief create an empty value with a given type
  10547. Create an empty JSON value with a given type. The value will be default
  10548. initialized with an empty value which depends on the type:
  10549. Value type | initial value
  10550. ----------- | -------------
  10551. null | `null`
  10552. boolean | `false`
  10553. string | `""`
  10554. number | `0`
  10555. object | `{}`
  10556. array | `[]`
  10557. @param[in] v the type of the value to create
  10558. @complexity Constant.
  10559. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10560. changes to any JSON value.
  10561. @liveexample{The following code shows the constructor for different @ref
  10562. value_t values,basic_json__value_t}
  10563. @sa @ref clear() -- restores the postcondition of this constructor
  10564. @since version 1.0.0
  10565. */
  10566. basic_json(const value_t v)
  10567. : m_type(v), m_value(v)
  10568. {
  10569. assert_invariant();
  10570. }
  10571. /*!
  10572. @brief create a null object
  10573. Create a `null` JSON value. It either takes a null pointer as parameter
  10574. (explicitly creating `null`) or no parameter (implicitly creating `null`).
  10575. The passed null pointer itself is not read -- it is only used to choose
  10576. the right constructor.
  10577. @complexity Constant.
  10578. @exceptionsafety No-throw guarantee: this constructor never throws
  10579. exceptions.
  10580. @liveexample{The following code shows the constructor with and without a
  10581. null pointer parameter.,basic_json__nullptr_t}
  10582. @since version 1.0.0
  10583. */
  10584. basic_json(std::nullptr_t = nullptr) noexcept
  10585. : basic_json(value_t::null)
  10586. {
  10587. assert_invariant();
  10588. }
  10589. /*!
  10590. @brief create a JSON value
  10591. This is a "catch all" constructor for all compatible JSON types; that is,
  10592. types for which a `to_json()` method exists. The constructor forwards the
  10593. parameter @a val to that method (to `json_serializer<U>::to_json` method
  10594. with `U = uncvref_t<CompatibleType>`, to be exact).
  10595. Template type @a CompatibleType includes, but is not limited to, the
  10596. following types:
  10597. - **arrays**: @ref array_t and all kinds of compatible containers such as
  10598. `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
  10599. `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
  10600. `std::multiset`, and `std::unordered_multiset` with a `value_type` from
  10601. which a @ref basic_json value can be constructed.
  10602. - **objects**: @ref object_t and all kinds of compatible associative
  10603. containers such as `std::map`, `std::unordered_map`, `std::multimap`,
  10604. and `std::unordered_multimap` with a `key_type` compatible to
  10605. @ref string_t and a `value_type` from which a @ref basic_json value can
  10606. be constructed.
  10607. - **strings**: @ref string_t, string literals, and all compatible string
  10608. containers can be used.
  10609. - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
  10610. @ref number_float_t, and all convertible number types such as `int`,
  10611. `size_t`, `int64_t`, `float` or `double` can be used.
  10612. - **boolean**: @ref boolean_t / `bool` can be used.
  10613. See the examples below.
  10614. @tparam CompatibleType a type such that:
  10615. - @a CompatibleType is not derived from `std::istream`,
  10616. - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
  10617. constructors),
  10618. - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
  10619. - @a CompatibleType is not a @ref basic_json nested type (e.g.,
  10620. @ref json_pointer, @ref iterator, etc ...)
  10621. - @ref @ref json_serializer<U> has a
  10622. `to_json(basic_json_t&, CompatibleType&&)` method
  10623. @tparam U = `uncvref_t<CompatibleType>`
  10624. @param[in] val the value to be forwarded to the respective constructor
  10625. @complexity Usually linear in the size of the passed @a val, also
  10626. depending on the implementation of the called `to_json()`
  10627. method.
  10628. @exceptionsafety Depends on the called constructor. For types directly
  10629. supported by the library (i.e., all types for which no `to_json()` function
  10630. was provided), strong guarantee holds: if an exception is thrown, there are
  10631. no changes to any JSON value.
  10632. @liveexample{The following code shows the constructor with several
  10633. compatible types.,basic_json__CompatibleType}
  10634. @since version 2.1.0
  10635. */
  10636. template <typename CompatibleType,
  10637. typename U = detail::uncvref_t<CompatibleType>,
  10638. detail::enable_if_t<
  10639. detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
  10640. basic_json(CompatibleType && val) noexcept(noexcept(
  10641. JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
  10642. std::forward<CompatibleType>(val))))
  10643. {
  10644. JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
  10645. assert_invariant();
  10646. }
  10647. /*!
  10648. @brief create a JSON value from an existing one
  10649. This is a constructor for existing @ref basic_json types.
  10650. It does not hijack copy/move constructors, since the parameter has different
  10651. template arguments than the current ones.
  10652. The constructor tries to convert the internal @ref m_value of the parameter.
  10653. @tparam BasicJsonType a type such that:
  10654. - @a BasicJsonType is a @ref basic_json type.
  10655. - @a BasicJsonType has different template arguments than @ref basic_json_t.
  10656. @param[in] val the @ref basic_json value to be converted.
  10657. @complexity Usually linear in the size of the passed @a val, also
  10658. depending on the implementation of the called `to_json()`
  10659. method.
  10660. @exceptionsafety Depends on the called constructor. For types directly
  10661. supported by the library (i.e., all types for which no `to_json()` function
  10662. was provided), strong guarantee holds: if an exception is thrown, there are
  10663. no changes to any JSON value.
  10664. @since version 3.2.0
  10665. */
  10666. template <typename BasicJsonType,
  10667. detail::enable_if_t<
  10668. detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
  10669. basic_json(const BasicJsonType& val)
  10670. {
  10671. using other_boolean_t = typename BasicJsonType::boolean_t;
  10672. using other_number_float_t = typename BasicJsonType::number_float_t;
  10673. using other_number_integer_t = typename BasicJsonType::number_integer_t;
  10674. using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
  10675. using other_string_t = typename BasicJsonType::string_t;
  10676. using other_object_t = typename BasicJsonType::object_t;
  10677. using other_array_t = typename BasicJsonType::array_t;
  10678. switch (val.type())
  10679. {
  10680. case value_t::boolean:
  10681. JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
  10682. break;
  10683. case value_t::number_float:
  10684. JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
  10685. break;
  10686. case value_t::number_integer:
  10687. JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
  10688. break;
  10689. case value_t::number_unsigned:
  10690. JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
  10691. break;
  10692. case value_t::string:
  10693. JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
  10694. break;
  10695. case value_t::object:
  10696. JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
  10697. break;
  10698. case value_t::array:
  10699. JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
  10700. break;
  10701. case value_t::null:
  10702. *this = nullptr;
  10703. break;
  10704. case value_t::discarded:
  10705. m_type = value_t::discarded;
  10706. break;
  10707. }
  10708. assert_invariant();
  10709. }
  10710. /*!
  10711. @brief create a container (array or object) from an initializer list
  10712. Creates a JSON value of type array or object from the passed initializer
  10713. list @a init. In case @a type_deduction is `true` (default), the type of
  10714. the JSON value to be created is deducted from the initializer list @a init
  10715. according to the following rules:
  10716. 1. If the list is empty, an empty JSON object value `{}` is created.
  10717. 2. If the list consists of pairs whose first element is a string, a JSON
  10718. object value is created where the first elements of the pairs are
  10719. treated as keys and the second elements are as values.
  10720. 3. In all other cases, an array is created.
  10721. The rules aim to create the best fit between a C++ initializer list and
  10722. JSON values. The rationale is as follows:
  10723. 1. The empty initializer list is written as `{}` which is exactly an empty
  10724. JSON object.
  10725. 2. C++ has no way of describing mapped types other than to list a list of
  10726. pairs. As JSON requires that keys must be of type string, rule 2 is the
  10727. weakest constraint one can pose on initializer lists to interpret them
  10728. as an object.
  10729. 3. In all other cases, the initializer list could not be interpreted as
  10730. JSON object type, so interpreting it as JSON array type is safe.
  10731. With the rules described above, the following JSON values cannot be
  10732. expressed by an initializer list:
  10733. - the empty array (`[]`): use @ref array(initializer_list_t)
  10734. with an empty initializer list in this case
  10735. - arrays whose elements satisfy rule 2: use @ref
  10736. array(initializer_list_t) with the same initializer list
  10737. in this case
  10738. @note When used without parentheses around an empty initializer list, @ref
  10739. basic_json() is called instead of this function, yielding the JSON null
  10740. value.
  10741. @param[in] init initializer list with JSON values
  10742. @param[in] type_deduction internal parameter; when set to `true`, the type
  10743. of the JSON value is deducted from the initializer list @a init; when set
  10744. to `false`, the type provided via @a manual_type is forced. This mode is
  10745. used by the functions @ref array(initializer_list_t) and
  10746. @ref object(initializer_list_t).
  10747. @param[in] manual_type internal parameter; when @a type_deduction is set
  10748. to `false`, the created JSON value will use the provided type (only @ref
  10749. value_t::array and @ref value_t::object are valid); when @a type_deduction
  10750. is set to `true`, this parameter has no effect
  10751. @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
  10752. `value_t::object`, but @a init contains an element which is not a pair
  10753. whose first element is a string. In this case, the constructor could not
  10754. create an object. If @a type_deduction would have be `true`, an array
  10755. would have been created. See @ref object(initializer_list_t)
  10756. for an example.
  10757. @complexity Linear in the size of the initializer list @a init.
  10758. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10759. changes to any JSON value.
  10760. @liveexample{The example below shows how JSON values are created from
  10761. initializer lists.,basic_json__list_init_t}
  10762. @sa @ref array(initializer_list_t) -- create a JSON array
  10763. value from an initializer list
  10764. @sa @ref object(initializer_list_t) -- create a JSON object
  10765. value from an initializer list
  10766. @since version 1.0.0
  10767. */
  10768. basic_json(initializer_list_t init,
  10769. bool type_deduction = true,
  10770. value_t manual_type = value_t::array)
  10771. {
  10772. // check if each element is an array with two elements whose first
  10773. // element is a string
  10774. bool is_an_object = std::all_of(init.begin(), init.end(),
  10775. [](const detail::json_ref<basic_json>& element_ref)
  10776. {
  10777. return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());
  10778. });
  10779. // adjust type if type deduction is not wanted
  10780. if (not type_deduction)
  10781. {
  10782. // if array is wanted, do not create an object though possible
  10783. if (manual_type == value_t::array)
  10784. {
  10785. is_an_object = false;
  10786. }
  10787. // if object is wanted but impossible, throw an exception
  10788. if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))
  10789. {
  10790. JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
  10791. }
  10792. }
  10793. if (is_an_object)
  10794. {
  10795. // the initializer list is a list of pairs -> create object
  10796. m_type = value_t::object;
  10797. m_value = value_t::object;
  10798. std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
  10799. {
  10800. auto element = element_ref.moved_or_copied();
  10801. m_value.object->emplace(
  10802. std::move(*((*element.m_value.array)[0].m_value.string)),
  10803. std::move((*element.m_value.array)[1]));
  10804. });
  10805. }
  10806. else
  10807. {
  10808. // the initializer list describes an array -> create array
  10809. m_type = value_t::array;
  10810. m_value.array = create<array_t>(init.begin(), init.end());
  10811. }
  10812. assert_invariant();
  10813. }
  10814. /*!
  10815. @brief explicitly create an array from an initializer list
  10816. Creates a JSON array value from a given initializer list. That is, given a
  10817. list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
  10818. initializer list is empty, the empty array `[]` is created.
  10819. @note This function is only needed to express two edge cases that cannot
  10820. be realized with the initializer list constructor (@ref
  10821. basic_json(initializer_list_t, bool, value_t)). These cases
  10822. are:
  10823. 1. creating an array whose elements are all pairs whose first element is a
  10824. string -- in this case, the initializer list constructor would create an
  10825. object, taking the first elements as keys
  10826. 2. creating an empty array -- passing the empty initializer list to the
  10827. initializer list constructor yields an empty object
  10828. @param[in] init initializer list with JSON values to create an array from
  10829. (optional)
  10830. @return JSON array value
  10831. @complexity Linear in the size of @a init.
  10832. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10833. changes to any JSON value.
  10834. @liveexample{The following code shows an example for the `array`
  10835. function.,array}
  10836. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  10837. create a JSON value from an initializer list
  10838. @sa @ref object(initializer_list_t) -- create a JSON object
  10839. value from an initializer list
  10840. @since version 1.0.0
  10841. */
  10842. static basic_json array(initializer_list_t init = {})
  10843. {
  10844. return basic_json(init, false, value_t::array);
  10845. }
  10846. /*!
  10847. @brief explicitly create an object from an initializer list
  10848. Creates a JSON object value from a given initializer list. The initializer
  10849. lists elements must be pairs, and their first elements must be strings. If
  10850. the initializer list is empty, the empty object `{}` is created.
  10851. @note This function is only added for symmetry reasons. In contrast to the
  10852. related function @ref array(initializer_list_t), there are
  10853. no cases which can only be expressed by this function. That is, any
  10854. initializer list @a init can also be passed to the initializer list
  10855. constructor @ref basic_json(initializer_list_t, bool, value_t).
  10856. @param[in] init initializer list to create an object from (optional)
  10857. @return JSON object value
  10858. @throw type_error.301 if @a init is not a list of pairs whose first
  10859. elements are strings. In this case, no object can be created. When such a
  10860. value is passed to @ref basic_json(initializer_list_t, bool, value_t),
  10861. an array would have been created from the passed initializer list @a init.
  10862. See example below.
  10863. @complexity Linear in the size of @a init.
  10864. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10865. changes to any JSON value.
  10866. @liveexample{The following code shows an example for the `object`
  10867. function.,object}
  10868. @sa @ref basic_json(initializer_list_t, bool, value_t) --
  10869. create a JSON value from an initializer list
  10870. @sa @ref array(initializer_list_t) -- create a JSON array
  10871. value from an initializer list
  10872. @since version 1.0.0
  10873. */
  10874. static basic_json object(initializer_list_t init = {})
  10875. {
  10876. return basic_json(init, false, value_t::object);
  10877. }
  10878. /*!
  10879. @brief construct an array with count copies of given value
  10880. Constructs a JSON array value by creating @a cnt copies of a passed value.
  10881. In case @a cnt is `0`, an empty array is created.
  10882. @param[in] cnt the number of JSON copies of @a val to create
  10883. @param[in] val the JSON value to copy
  10884. @post `std::distance(begin(),end()) == cnt` holds.
  10885. @complexity Linear in @a cnt.
  10886. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10887. changes to any JSON value.
  10888. @liveexample{The following code shows examples for the @ref
  10889. basic_json(size_type\, const basic_json&)
  10890. constructor.,basic_json__size_type_basic_json}
  10891. @since version 1.0.0
  10892. */
  10893. basic_json(size_type cnt, const basic_json& val)
  10894. : m_type(value_t::array)
  10895. {
  10896. m_value.array = create<array_t>(cnt, val);
  10897. assert_invariant();
  10898. }
  10899. /*!
  10900. @brief construct a JSON container given an iterator range
  10901. Constructs the JSON value with the contents of the range `[first, last)`.
  10902. The semantics depends on the different types a JSON value can have:
  10903. - In case of a null type, invalid_iterator.206 is thrown.
  10904. - In case of other primitive types (number, boolean, or string), @a first
  10905. must be `begin()` and @a last must be `end()`. In this case, the value is
  10906. copied. Otherwise, invalid_iterator.204 is thrown.
  10907. - In case of structured types (array, object), the constructor behaves as
  10908. similar versions for `std::vector` or `std::map`; that is, a JSON array
  10909. or object is constructed from the values in the range.
  10910. @tparam InputIT an input iterator type (@ref iterator or @ref
  10911. const_iterator)
  10912. @param[in] first begin of the range to copy from (included)
  10913. @param[in] last end of the range to copy from (excluded)
  10914. @pre Iterators @a first and @a last must be initialized. **This
  10915. precondition is enforced with an assertion (see warning).** If
  10916. assertions are switched off, a violation of this precondition yields
  10917. undefined behavior.
  10918. @pre Range `[first, last)` is valid. Usually, this precondition cannot be
  10919. checked efficiently. Only certain edge cases are detected; see the
  10920. description of the exceptions below. A violation of this precondition
  10921. yields undefined behavior.
  10922. @warning A precondition is enforced with a runtime assertion that will
  10923. result in calling `std::abort` if this precondition is not met.
  10924. Assertions can be disabled by defining `NDEBUG` at compile time.
  10925. See https://en.cppreference.com/w/cpp/error/assert for more
  10926. information.
  10927. @throw invalid_iterator.201 if iterators @a first and @a last are not
  10928. compatible (i.e., do not belong to the same JSON value). In this case,
  10929. the range `[first, last)` is undefined.
  10930. @throw invalid_iterator.204 if iterators @a first and @a last belong to a
  10931. primitive type (number, boolean, or string), but @a first does not point
  10932. to the first element any more. In this case, the range `[first, last)` is
  10933. undefined. See example code below.
  10934. @throw invalid_iterator.206 if iterators @a first and @a last belong to a
  10935. null value. In this case, the range `[first, last)` is undefined.
  10936. @complexity Linear in distance between @a first and @a last.
  10937. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  10938. changes to any JSON value.
  10939. @liveexample{The example below shows several ways to create JSON values by
  10940. specifying a subrange with iterators.,basic_json__InputIt_InputIt}
  10941. @since version 1.0.0
  10942. */
  10943. template<class InputIT, typename std::enable_if<
  10944. std::is_same<InputIT, typename basic_json_t::iterator>::value or
  10945. std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
  10946. basic_json(InputIT first, InputIT last)
  10947. {
  10948. assert(first.m_object != nullptr);
  10949. assert(last.m_object != nullptr);
  10950. // make sure iterator fits the current value
  10951. if (JSON_UNLIKELY(first.m_object != last.m_object))
  10952. {
  10953. JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
  10954. }
  10955. // copy type from first iterator
  10956. m_type = first.m_object->m_type;
  10957. // check if iterator range is complete for primitive values
  10958. switch (m_type)
  10959. {
  10960. case value_t::boolean:
  10961. case value_t::number_float:
  10962. case value_t::number_integer:
  10963. case value_t::number_unsigned:
  10964. case value_t::string:
  10965. {
  10966. if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
  10967. or not last.m_it.primitive_iterator.is_end()))
  10968. {
  10969. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  10970. }
  10971. break;
  10972. }
  10973. default:
  10974. break;
  10975. }
  10976. switch (m_type)
  10977. {
  10978. case value_t::number_integer:
  10979. {
  10980. m_value.number_integer = first.m_object->m_value.number_integer;
  10981. break;
  10982. }
  10983. case value_t::number_unsigned:
  10984. {
  10985. m_value.number_unsigned = first.m_object->m_value.number_unsigned;
  10986. break;
  10987. }
  10988. case value_t::number_float:
  10989. {
  10990. m_value.number_float = first.m_object->m_value.number_float;
  10991. break;
  10992. }
  10993. case value_t::boolean:
  10994. {
  10995. m_value.boolean = first.m_object->m_value.boolean;
  10996. break;
  10997. }
  10998. case value_t::string:
  10999. {
  11000. m_value = *first.m_object->m_value.string;
  11001. break;
  11002. }
  11003. case value_t::object:
  11004. {
  11005. m_value.object = create<object_t>(first.m_it.object_iterator,
  11006. last.m_it.object_iterator);
  11007. break;
  11008. }
  11009. case value_t::array:
  11010. {
  11011. m_value.array = create<array_t>(first.m_it.array_iterator,
  11012. last.m_it.array_iterator);
  11013. break;
  11014. }
  11015. default:
  11016. JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
  11017. std::string(first.m_object->type_name())));
  11018. }
  11019. assert_invariant();
  11020. }
  11021. ///////////////////////////////////////
  11022. // other constructors and destructor //
  11023. ///////////////////////////////////////
  11024. /// @private
  11025. basic_json(const detail::json_ref<basic_json>& ref)
  11026. : basic_json(ref.moved_or_copied())
  11027. {}
  11028. /*!
  11029. @brief copy constructor
  11030. Creates a copy of a given JSON value.
  11031. @param[in] other the JSON value to copy
  11032. @post `*this == other`
  11033. @complexity Linear in the size of @a other.
  11034. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11035. changes to any JSON value.
  11036. @requirement This function helps `basic_json` satisfying the
  11037. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  11038. requirements:
  11039. - The complexity is linear.
  11040. - As postcondition, it holds: `other == basic_json(other)`.
  11041. @liveexample{The following code shows an example for the copy
  11042. constructor.,basic_json__basic_json}
  11043. @since version 1.0.0
  11044. */
  11045. basic_json(const basic_json& other)
  11046. : m_type(other.m_type)
  11047. {
  11048. // check of passed value is valid
  11049. other.assert_invariant();
  11050. switch (m_type)
  11051. {
  11052. case value_t::object:
  11053. {
  11054. m_value = *other.m_value.object;
  11055. break;
  11056. }
  11057. case value_t::array:
  11058. {
  11059. m_value = *other.m_value.array;
  11060. break;
  11061. }
  11062. case value_t::string:
  11063. {
  11064. m_value = *other.m_value.string;
  11065. break;
  11066. }
  11067. case value_t::boolean:
  11068. {
  11069. m_value = other.m_value.boolean;
  11070. break;
  11071. }
  11072. case value_t::number_integer:
  11073. {
  11074. m_value = other.m_value.number_integer;
  11075. break;
  11076. }
  11077. case value_t::number_unsigned:
  11078. {
  11079. m_value = other.m_value.number_unsigned;
  11080. break;
  11081. }
  11082. case value_t::number_float:
  11083. {
  11084. m_value = other.m_value.number_float;
  11085. break;
  11086. }
  11087. default:
  11088. break;
  11089. }
  11090. assert_invariant();
  11091. }
  11092. /*!
  11093. @brief move constructor
  11094. Move constructor. Constructs a JSON value with the contents of the given
  11095. value @a other using move semantics. It "steals" the resources from @a
  11096. other and leaves it as JSON null value.
  11097. @param[in,out] other value to move to this object
  11098. @post `*this` has the same value as @a other before the call.
  11099. @post @a other is a JSON null value.
  11100. @complexity Constant.
  11101. @exceptionsafety No-throw guarantee: this constructor never throws
  11102. exceptions.
  11103. @requirement This function helps `basic_json` satisfying the
  11104. [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
  11105. requirements.
  11106. @liveexample{The code below shows the move constructor explicitly called
  11107. via std::move.,basic_json__moveconstructor}
  11108. @since version 1.0.0
  11109. */
  11110. basic_json(basic_json&& other) noexcept
  11111. : m_type(std::move(other.m_type)),
  11112. m_value(std::move(other.m_value))
  11113. {
  11114. // check that passed value is valid
  11115. other.assert_invariant();
  11116. // invalidate payload
  11117. other.m_type = value_t::null;
  11118. other.m_value = {};
  11119. assert_invariant();
  11120. }
  11121. /*!
  11122. @brief copy assignment
  11123. Copy assignment operator. Copies a JSON value via the "copy and swap"
  11124. strategy: It is expressed in terms of the copy constructor, destructor,
  11125. and the `swap()` member function.
  11126. @param[in] other value to copy from
  11127. @complexity Linear.
  11128. @requirement This function helps `basic_json` satisfying the
  11129. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  11130. requirements:
  11131. - The complexity is linear.
  11132. @liveexample{The code below shows and example for the copy assignment. It
  11133. creates a copy of value `a` which is then swapped with `b`. Finally\, the
  11134. copy of `a` (which is the null value after the swap) is
  11135. destroyed.,basic_json__copyassignment}
  11136. @since version 1.0.0
  11137. */
  11138. reference& operator=(basic_json other) noexcept (
  11139. std::is_nothrow_move_constructible<value_t>::value and
  11140. std::is_nothrow_move_assignable<value_t>::value and
  11141. std::is_nothrow_move_constructible<json_value>::value and
  11142. std::is_nothrow_move_assignable<json_value>::value
  11143. )
  11144. {
  11145. // check that passed value is valid
  11146. other.assert_invariant();
  11147. using std::swap;
  11148. swap(m_type, other.m_type);
  11149. swap(m_value, other.m_value);
  11150. assert_invariant();
  11151. return *this;
  11152. }
  11153. /*!
  11154. @brief destructor
  11155. Destroys the JSON value and frees all allocated memory.
  11156. @complexity Linear.
  11157. @requirement This function helps `basic_json` satisfying the
  11158. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  11159. requirements:
  11160. - The complexity is linear.
  11161. - All stored elements are destroyed and all memory is freed.
  11162. @since version 1.0.0
  11163. */
  11164. ~basic_json() noexcept
  11165. {
  11166. assert_invariant();
  11167. m_value.destroy(m_type);
  11168. }
  11169. /// @}
  11170. public:
  11171. ///////////////////////
  11172. // object inspection //
  11173. ///////////////////////
  11174. /// @name object inspection
  11175. /// Functions to inspect the type of a JSON value.
  11176. /// @{
  11177. /*!
  11178. @brief serialization
  11179. Serialization function for JSON values. The function tries to mimic
  11180. Python's `json.dumps()` function, and currently supports its @a indent
  11181. and @a ensure_ascii parameters.
  11182. @param[in] indent If indent is nonnegative, then array elements and object
  11183. members will be pretty-printed with that indent level. An indent level of
  11184. `0` will only insert newlines. `-1` (the default) selects the most compact
  11185. representation.
  11186. @param[in] indent_char The character to use for indentation if @a indent is
  11187. greater than `0`. The default is ` ` (space).
  11188. @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
  11189. in the output are escaped with `\uXXXX` sequences, and the result consists
  11190. of ASCII characters only.
  11191. @return string containing the serialization of the JSON value
  11192. @throw type_error.316 if a string stored inside the JSON value is not
  11193. UTF-8 encoded
  11194. @complexity Linear.
  11195. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11196. changes in the JSON value.
  11197. @liveexample{The following example shows the effect of different @a indent\,
  11198. @a indent_char\, and @a ensure_ascii parameters to the result of the
  11199. serialization.,dump}
  11200. @see https://docs.python.org/2/library/json.html#json.dump
  11201. @since version 1.0.0; indentation character @a indent_char, option
  11202. @a ensure_ascii and exceptions added in version 3.0.0
  11203. */
  11204. string_t dump(const int indent = -1, const char indent_char = ' ',
  11205. const bool ensure_ascii = false) const
  11206. {
  11207. string_t result;
  11208. serializer s(detail::output_adapter<char, string_t>(result), indent_char);
  11209. if (indent >= 0)
  11210. {
  11211. s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
  11212. }
  11213. else
  11214. {
  11215. s.dump(*this, false, ensure_ascii, 0);
  11216. }
  11217. return result;
  11218. }
  11219. /*!
  11220. @brief return the type of the JSON value (explicit)
  11221. Return the type of the JSON value as a value from the @ref value_t
  11222. enumeration.
  11223. @return the type of the JSON value
  11224. Value type | return value
  11225. ------------------------- | -------------------------
  11226. null | value_t::null
  11227. boolean | value_t::boolean
  11228. string | value_t::string
  11229. number (integer) | value_t::number_integer
  11230. number (unsigned integer) | value_t::number_unsigned
  11231. number (floating-point) | value_t::number_float
  11232. object | value_t::object
  11233. array | value_t::array
  11234. discarded | value_t::discarded
  11235. @complexity Constant.
  11236. @exceptionsafety No-throw guarantee: this member function never throws
  11237. exceptions.
  11238. @liveexample{The following code exemplifies `type()` for all JSON
  11239. types.,type}
  11240. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  11241. @sa @ref type_name() -- return the type as string
  11242. @since version 1.0.0
  11243. */
  11244. constexpr value_t type() const noexcept
  11245. {
  11246. return m_type;
  11247. }
  11248. /*!
  11249. @brief return whether type is primitive
  11250. This function returns true if and only if the JSON type is primitive
  11251. (string, number, boolean, or null).
  11252. @return `true` if type is primitive (string, number, boolean, or null),
  11253. `false` otherwise.
  11254. @complexity Constant.
  11255. @exceptionsafety No-throw guarantee: this member function never throws
  11256. exceptions.
  11257. @liveexample{The following code exemplifies `is_primitive()` for all JSON
  11258. types.,is_primitive}
  11259. @sa @ref is_structured() -- returns whether JSON value is structured
  11260. @sa @ref is_null() -- returns whether JSON value is `null`
  11261. @sa @ref is_string() -- returns whether JSON value is a string
  11262. @sa @ref is_boolean() -- returns whether JSON value is a boolean
  11263. @sa @ref is_number() -- returns whether JSON value is a number
  11264. @since version 1.0.0
  11265. */
  11266. constexpr bool is_primitive() const noexcept
  11267. {
  11268. return is_null() or is_string() or is_boolean() or is_number();
  11269. }
  11270. /*!
  11271. @brief return whether type is structured
  11272. This function returns true if and only if the JSON type is structured
  11273. (array or object).
  11274. @return `true` if type is structured (array or object), `false` otherwise.
  11275. @complexity Constant.
  11276. @exceptionsafety No-throw guarantee: this member function never throws
  11277. exceptions.
  11278. @liveexample{The following code exemplifies `is_structured()` for all JSON
  11279. types.,is_structured}
  11280. @sa @ref is_primitive() -- returns whether value is primitive
  11281. @sa @ref is_array() -- returns whether value is an array
  11282. @sa @ref is_object() -- returns whether value is an object
  11283. @since version 1.0.0
  11284. */
  11285. constexpr bool is_structured() const noexcept
  11286. {
  11287. return is_array() or is_object();
  11288. }
  11289. /*!
  11290. @brief return whether value is null
  11291. This function returns true if and only if the JSON value is null.
  11292. @return `true` if type is null, `false` otherwise.
  11293. @complexity Constant.
  11294. @exceptionsafety No-throw guarantee: this member function never throws
  11295. exceptions.
  11296. @liveexample{The following code exemplifies `is_null()` for all JSON
  11297. types.,is_null}
  11298. @since version 1.0.0
  11299. */
  11300. constexpr bool is_null() const noexcept
  11301. {
  11302. return (m_type == value_t::null);
  11303. }
  11304. /*!
  11305. @brief return whether value is a boolean
  11306. This function returns true if and only if the JSON value is a boolean.
  11307. @return `true` if type is boolean, `false` otherwise.
  11308. @complexity Constant.
  11309. @exceptionsafety No-throw guarantee: this member function never throws
  11310. exceptions.
  11311. @liveexample{The following code exemplifies `is_boolean()` for all JSON
  11312. types.,is_boolean}
  11313. @since version 1.0.0
  11314. */
  11315. constexpr bool is_boolean() const noexcept
  11316. {
  11317. return (m_type == value_t::boolean);
  11318. }
  11319. /*!
  11320. @brief return whether value is a number
  11321. This function returns true if and only if the JSON value is a number. This
  11322. includes both integer (signed and unsigned) and floating-point values.
  11323. @return `true` if type is number (regardless whether integer, unsigned
  11324. integer or floating-type), `false` otherwise.
  11325. @complexity Constant.
  11326. @exceptionsafety No-throw guarantee: this member function never throws
  11327. exceptions.
  11328. @liveexample{The following code exemplifies `is_number()` for all JSON
  11329. types.,is_number}
  11330. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  11331. integer number
  11332. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  11333. number
  11334. @sa @ref is_number_float() -- check if value is a floating-point number
  11335. @since version 1.0.0
  11336. */
  11337. constexpr bool is_number() const noexcept
  11338. {
  11339. return is_number_integer() or is_number_float();
  11340. }
  11341. /*!
  11342. @brief return whether value is an integer number
  11343. This function returns true if and only if the JSON value is a signed or
  11344. unsigned integer number. This excludes floating-point values.
  11345. @return `true` if type is an integer or unsigned integer number, `false`
  11346. otherwise.
  11347. @complexity Constant.
  11348. @exceptionsafety No-throw guarantee: this member function never throws
  11349. exceptions.
  11350. @liveexample{The following code exemplifies `is_number_integer()` for all
  11351. JSON types.,is_number_integer}
  11352. @sa @ref is_number() -- check if value is a number
  11353. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  11354. number
  11355. @sa @ref is_number_float() -- check if value is a floating-point number
  11356. @since version 1.0.0
  11357. */
  11358. constexpr bool is_number_integer() const noexcept
  11359. {
  11360. return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);
  11361. }
  11362. /*!
  11363. @brief return whether value is an unsigned integer number
  11364. This function returns true if and only if the JSON value is an unsigned
  11365. integer number. This excludes floating-point and signed integer values.
  11366. @return `true` if type is an unsigned integer number, `false` otherwise.
  11367. @complexity Constant.
  11368. @exceptionsafety No-throw guarantee: this member function never throws
  11369. exceptions.
  11370. @liveexample{The following code exemplifies `is_number_unsigned()` for all
  11371. JSON types.,is_number_unsigned}
  11372. @sa @ref is_number() -- check if value is a number
  11373. @sa @ref is_number_integer() -- check if value is an integer or unsigned
  11374. integer number
  11375. @sa @ref is_number_float() -- check if value is a floating-point number
  11376. @since version 2.0.0
  11377. */
  11378. constexpr bool is_number_unsigned() const noexcept
  11379. {
  11380. return (m_type == value_t::number_unsigned);
  11381. }
  11382. /*!
  11383. @brief return whether value is a floating-point number
  11384. This function returns true if and only if the JSON value is a
  11385. floating-point number. This excludes signed and unsigned integer values.
  11386. @return `true` if type is a floating-point number, `false` otherwise.
  11387. @complexity Constant.
  11388. @exceptionsafety No-throw guarantee: this member function never throws
  11389. exceptions.
  11390. @liveexample{The following code exemplifies `is_number_float()` for all
  11391. JSON types.,is_number_float}
  11392. @sa @ref is_number() -- check if value is number
  11393. @sa @ref is_number_integer() -- check if value is an integer number
  11394. @sa @ref is_number_unsigned() -- check if value is an unsigned integer
  11395. number
  11396. @since version 1.0.0
  11397. */
  11398. constexpr bool is_number_float() const noexcept
  11399. {
  11400. return (m_type == value_t::number_float);
  11401. }
  11402. /*!
  11403. @brief return whether value is an object
  11404. This function returns true if and only if the JSON value is an object.
  11405. @return `true` if type is object, `false` otherwise.
  11406. @complexity Constant.
  11407. @exceptionsafety No-throw guarantee: this member function never throws
  11408. exceptions.
  11409. @liveexample{The following code exemplifies `is_object()` for all JSON
  11410. types.,is_object}
  11411. @since version 1.0.0
  11412. */
  11413. constexpr bool is_object() const noexcept
  11414. {
  11415. return (m_type == value_t::object);
  11416. }
  11417. /*!
  11418. @brief return whether value is an array
  11419. This function returns true if and only if the JSON value is an array.
  11420. @return `true` if type is array, `false` otherwise.
  11421. @complexity Constant.
  11422. @exceptionsafety No-throw guarantee: this member function never throws
  11423. exceptions.
  11424. @liveexample{The following code exemplifies `is_array()` for all JSON
  11425. types.,is_array}
  11426. @since version 1.0.0
  11427. */
  11428. constexpr bool is_array() const noexcept
  11429. {
  11430. return (m_type == value_t::array);
  11431. }
  11432. /*!
  11433. @brief return whether value is a string
  11434. This function returns true if and only if the JSON value is a string.
  11435. @return `true` if type is string, `false` otherwise.
  11436. @complexity Constant.
  11437. @exceptionsafety No-throw guarantee: this member function never throws
  11438. exceptions.
  11439. @liveexample{The following code exemplifies `is_string()` for all JSON
  11440. types.,is_string}
  11441. @since version 1.0.0
  11442. */
  11443. constexpr bool is_string() const noexcept
  11444. {
  11445. return (m_type == value_t::string);
  11446. }
  11447. /*!
  11448. @brief return whether value is discarded
  11449. This function returns true if and only if the JSON value was discarded
  11450. during parsing with a callback function (see @ref parser_callback_t).
  11451. @note This function will always be `false` for JSON values after parsing.
  11452. That is, discarded values can only occur during parsing, but will be
  11453. removed when inside a structured value or replaced by null in other cases.
  11454. @return `true` if type is discarded, `false` otherwise.
  11455. @complexity Constant.
  11456. @exceptionsafety No-throw guarantee: this member function never throws
  11457. exceptions.
  11458. @liveexample{The following code exemplifies `is_discarded()` for all JSON
  11459. types.,is_discarded}
  11460. @since version 1.0.0
  11461. */
  11462. constexpr bool is_discarded() const noexcept
  11463. {
  11464. return (m_type == value_t::discarded);
  11465. }
  11466. /*!
  11467. @brief return the type of the JSON value (implicit)
  11468. Implicitly return the type of the JSON value as a value from the @ref
  11469. value_t enumeration.
  11470. @return the type of the JSON value
  11471. @complexity Constant.
  11472. @exceptionsafety No-throw guarantee: this member function never throws
  11473. exceptions.
  11474. @liveexample{The following code exemplifies the @ref value_t operator for
  11475. all JSON types.,operator__value_t}
  11476. @sa @ref type() -- return the type of the JSON value (explicit)
  11477. @sa @ref type_name() -- return the type as string
  11478. @since version 1.0.0
  11479. */
  11480. constexpr operator value_t() const noexcept
  11481. {
  11482. return m_type;
  11483. }
  11484. /// @}
  11485. private:
  11486. //////////////////
  11487. // value access //
  11488. //////////////////
  11489. /// get a boolean (explicit)
  11490. boolean_t get_impl(boolean_t* /*unused*/) const
  11491. {
  11492. if (JSON_LIKELY(is_boolean()))
  11493. {
  11494. return m_value.boolean;
  11495. }
  11496. JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
  11497. }
  11498. /// get a pointer to the value (object)
  11499. object_t* get_impl_ptr(object_t* /*unused*/) noexcept
  11500. {
  11501. return is_object() ? m_value.object : nullptr;
  11502. }
  11503. /// get a pointer to the value (object)
  11504. constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
  11505. {
  11506. return is_object() ? m_value.object : nullptr;
  11507. }
  11508. /// get a pointer to the value (array)
  11509. array_t* get_impl_ptr(array_t* /*unused*/) noexcept
  11510. {
  11511. return is_array() ? m_value.array : nullptr;
  11512. }
  11513. /// get a pointer to the value (array)
  11514. constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
  11515. {
  11516. return is_array() ? m_value.array : nullptr;
  11517. }
  11518. /// get a pointer to the value (string)
  11519. string_t* get_impl_ptr(string_t* /*unused*/) noexcept
  11520. {
  11521. return is_string() ? m_value.string : nullptr;
  11522. }
  11523. /// get a pointer to the value (string)
  11524. constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
  11525. {
  11526. return is_string() ? m_value.string : nullptr;
  11527. }
  11528. /// get a pointer to the value (boolean)
  11529. boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
  11530. {
  11531. return is_boolean() ? &m_value.boolean : nullptr;
  11532. }
  11533. /// get a pointer to the value (boolean)
  11534. constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
  11535. {
  11536. return is_boolean() ? &m_value.boolean : nullptr;
  11537. }
  11538. /// get a pointer to the value (integer number)
  11539. number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
  11540. {
  11541. return is_number_integer() ? &m_value.number_integer : nullptr;
  11542. }
  11543. /// get a pointer to the value (integer number)
  11544. constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
  11545. {
  11546. return is_number_integer() ? &m_value.number_integer : nullptr;
  11547. }
  11548. /// get a pointer to the value (unsigned number)
  11549. number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
  11550. {
  11551. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  11552. }
  11553. /// get a pointer to the value (unsigned number)
  11554. constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
  11555. {
  11556. return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
  11557. }
  11558. /// get a pointer to the value (floating-point number)
  11559. number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
  11560. {
  11561. return is_number_float() ? &m_value.number_float : nullptr;
  11562. }
  11563. /// get a pointer to the value (floating-point number)
  11564. constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
  11565. {
  11566. return is_number_float() ? &m_value.number_float : nullptr;
  11567. }
  11568. /*!
  11569. @brief helper function to implement get_ref()
  11570. This function helps to implement get_ref() without code duplication for
  11571. const and non-const overloads
  11572. @tparam ThisType will be deduced as `basic_json` or `const basic_json`
  11573. @throw type_error.303 if ReferenceType does not match underlying value
  11574. type of the current JSON
  11575. */
  11576. template<typename ReferenceType, typename ThisType>
  11577. static ReferenceType get_ref_impl(ThisType& obj)
  11578. {
  11579. // delegate the call to get_ptr<>()
  11580. auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
  11581. if (JSON_LIKELY(ptr != nullptr))
  11582. {
  11583. return *ptr;
  11584. }
  11585. JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
  11586. }
  11587. public:
  11588. /// @name value access
  11589. /// Direct access to the stored value of a JSON value.
  11590. /// @{
  11591. /*!
  11592. @brief get special-case overload
  11593. This overloads avoids a lot of template boilerplate, it can be seen as the
  11594. identity method
  11595. @tparam BasicJsonType == @ref basic_json
  11596. @return a copy of *this
  11597. @complexity Constant.
  11598. @since version 2.1.0
  11599. */
  11600. template<typename BasicJsonType, detail::enable_if_t<
  11601. std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
  11602. int> = 0>
  11603. basic_json get() const
  11604. {
  11605. return *this;
  11606. }
  11607. /*!
  11608. @brief get special-case overload
  11609. This overloads converts the current @ref basic_json in a different
  11610. @ref basic_json type
  11611. @tparam BasicJsonType == @ref basic_json
  11612. @return a copy of *this, converted into @tparam BasicJsonType
  11613. @complexity Depending on the implementation of the called `from_json()`
  11614. method.
  11615. @since version 3.2.0
  11616. */
  11617. template<typename BasicJsonType, detail::enable_if_t<
  11618. not std::is_same<BasicJsonType, basic_json>::value and
  11619. detail::is_basic_json<BasicJsonType>::value, int> = 0>
  11620. BasicJsonType get() const
  11621. {
  11622. return *this;
  11623. }
  11624. /*!
  11625. @brief get a value (explicit)
  11626. Explicit type conversion between the JSON value and a compatible value
  11627. which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  11628. and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  11629. The value is converted by calling the @ref json_serializer<ValueType>
  11630. `from_json()` method.
  11631. The function is equivalent to executing
  11632. @code {.cpp}
  11633. ValueType ret;
  11634. JSONSerializer<ValueType>::from_json(*this, ret);
  11635. return ret;
  11636. @endcode
  11637. This overloads is chosen if:
  11638. - @a ValueType is not @ref basic_json,
  11639. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  11640. `void from_json(const basic_json&, ValueType&)`, and
  11641. - @ref json_serializer<ValueType> does not have a `from_json()` method of
  11642. the form `ValueType from_json(const basic_json&)`
  11643. @tparam ValueTypeCV the provided value type
  11644. @tparam ValueType the returned value type
  11645. @return copy of the JSON value, converted to @a ValueType
  11646. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  11647. @liveexample{The example below shows several conversions from JSON values
  11648. to other types. There a few things to note: (1) Floating-point numbers can
  11649. be converted to integers\, (2) A JSON array can be converted to a standard
  11650. `std::vector<short>`\, (3) A JSON object can be converted to C++
  11651. associative containers such as `std::unordered_map<std::string\,
  11652. json>`.,get__ValueType_const}
  11653. @since version 2.1.0
  11654. */
  11655. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  11656. detail::enable_if_t <
  11657. not detail::is_basic_json<ValueType>::value and
  11658. detail::has_from_json<basic_json_t, ValueType>::value and
  11659. not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  11660. int> = 0>
  11661. ValueType get() const noexcept(noexcept(
  11662. JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
  11663. {
  11664. // we cannot static_assert on ValueTypeCV being non-const, because
  11665. // there is support for get<const basic_json_t>(), which is why we
  11666. // still need the uncvref
  11667. static_assert(not std::is_reference<ValueTypeCV>::value,
  11668. "get() cannot be used with reference types, you might want to use get_ref()");
  11669. static_assert(std::is_default_constructible<ValueType>::value,
  11670. "types must be DefaultConstructible when used with get()");
  11671. ValueType ret;
  11672. JSONSerializer<ValueType>::from_json(*this, ret);
  11673. return ret;
  11674. }
  11675. /*!
  11676. @brief get a value (explicit); special case
  11677. Explicit type conversion between the JSON value and a compatible value
  11678. which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
  11679. and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
  11680. The value is converted by calling the @ref json_serializer<ValueType>
  11681. `from_json()` method.
  11682. The function is equivalent to executing
  11683. @code {.cpp}
  11684. return JSONSerializer<ValueTypeCV>::from_json(*this);
  11685. @endcode
  11686. This overloads is chosen if:
  11687. - @a ValueType is not @ref basic_json and
  11688. - @ref json_serializer<ValueType> has a `from_json()` method of the form
  11689. `ValueType from_json(const basic_json&)`
  11690. @note If @ref json_serializer<ValueType> has both overloads of
  11691. `from_json()`, this one is chosen.
  11692. @tparam ValueTypeCV the provided value type
  11693. @tparam ValueType the returned value type
  11694. @return copy of the JSON value, converted to @a ValueType
  11695. @throw what @ref json_serializer<ValueType> `from_json()` method throws
  11696. @since version 2.1.0
  11697. */
  11698. template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
  11699. detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
  11700. detail::has_non_default_from_json<basic_json_t, ValueType>::value,
  11701. int> = 0>
  11702. ValueType get() const noexcept(noexcept(
  11703. JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
  11704. {
  11705. static_assert(not std::is_reference<ValueTypeCV>::value,
  11706. "get() cannot be used with reference types, you might want to use get_ref()");
  11707. return JSONSerializer<ValueTypeCV>::from_json(*this);
  11708. }
  11709. /*!
  11710. @brief get a pointer value (explicit)
  11711. Explicit pointer access to the internally stored JSON value. No copies are
  11712. made.
  11713. @warning The pointer becomes invalid if the underlying JSON object
  11714. changes.
  11715. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  11716. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  11717. @ref number_unsigned_t, or @ref number_float_t.
  11718. @return pointer to the internally stored JSON value if the requested
  11719. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  11720. @complexity Constant.
  11721. @liveexample{The example below shows how pointers to internal values of a
  11722. JSON value can be requested. Note that no type conversions are made and a
  11723. `nullptr` is returned if the value and the requested pointer type does not
  11724. match.,get__PointerType}
  11725. @sa @ref get_ptr() for explicit pointer-member access
  11726. @since version 1.0.0
  11727. */
  11728. template<typename PointerType, typename std::enable_if<
  11729. std::is_pointer<PointerType>::value, int>::type = 0>
  11730. PointerType get() noexcept
  11731. {
  11732. // delegate the call to get_ptr
  11733. return get_ptr<PointerType>();
  11734. }
  11735. /*!
  11736. @brief get a pointer value (explicit)
  11737. @copydoc get()
  11738. */
  11739. template<typename PointerType, typename std::enable_if<
  11740. std::is_pointer<PointerType>::value, int>::type = 0>
  11741. constexpr const PointerType get() const noexcept
  11742. {
  11743. // delegate the call to get_ptr
  11744. return get_ptr<PointerType>();
  11745. }
  11746. /*!
  11747. @brief get a pointer value (implicit)
  11748. Implicit pointer access to the internally stored JSON value. No copies are
  11749. made.
  11750. @warning Writing data to the pointee of the result yields an undefined
  11751. state.
  11752. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
  11753. object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
  11754. @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
  11755. assertion.
  11756. @return pointer to the internally stored JSON value if the requested
  11757. pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
  11758. @complexity Constant.
  11759. @liveexample{The example below shows how pointers to internal values of a
  11760. JSON value can be requested. Note that no type conversions are made and a
  11761. `nullptr` is returned if the value and the requested pointer type does not
  11762. match.,get_ptr}
  11763. @since version 1.0.0
  11764. */
  11765. template<typename PointerType, typename std::enable_if<
  11766. std::is_pointer<PointerType>::value, int>::type = 0>
  11767. PointerType get_ptr() noexcept
  11768. {
  11769. // get the type of the PointerType (remove pointer and const)
  11770. using pointee_t = typename std::remove_const<typename
  11771. std::remove_pointer<typename
  11772. std::remove_const<PointerType>::type>::type>::type;
  11773. // make sure the type matches the allowed types
  11774. static_assert(
  11775. std::is_same<object_t, pointee_t>::value
  11776. or std::is_same<array_t, pointee_t>::value
  11777. or std::is_same<string_t, pointee_t>::value
  11778. or std::is_same<boolean_t, pointee_t>::value
  11779. or std::is_same<number_integer_t, pointee_t>::value
  11780. or std::is_same<number_unsigned_t, pointee_t>::value
  11781. or std::is_same<number_float_t, pointee_t>::value
  11782. , "incompatible pointer type");
  11783. // delegate the call to get_impl_ptr<>()
  11784. return get_impl_ptr(static_cast<PointerType>(nullptr));
  11785. }
  11786. /*!
  11787. @brief get a pointer value (implicit)
  11788. @copydoc get_ptr()
  11789. */
  11790. template<typename PointerType, typename std::enable_if<
  11791. std::is_pointer<PointerType>::value and
  11792. std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
  11793. constexpr const PointerType get_ptr() const noexcept
  11794. {
  11795. // get the type of the PointerType (remove pointer and const)
  11796. using pointee_t = typename std::remove_const<typename
  11797. std::remove_pointer<typename
  11798. std::remove_const<PointerType>::type>::type>::type;
  11799. // make sure the type matches the allowed types
  11800. static_assert(
  11801. std::is_same<object_t, pointee_t>::value
  11802. or std::is_same<array_t, pointee_t>::value
  11803. or std::is_same<string_t, pointee_t>::value
  11804. or std::is_same<boolean_t, pointee_t>::value
  11805. or std::is_same<number_integer_t, pointee_t>::value
  11806. or std::is_same<number_unsigned_t, pointee_t>::value
  11807. or std::is_same<number_float_t, pointee_t>::value
  11808. , "incompatible pointer type");
  11809. // delegate the call to get_impl_ptr<>() const
  11810. return get_impl_ptr(static_cast<PointerType>(nullptr));
  11811. }
  11812. /*!
  11813. @brief get a reference value (implicit)
  11814. Implicit reference access to the internally stored JSON value. No copies
  11815. are made.
  11816. @warning Writing data to the referee of the result yields an undefined
  11817. state.
  11818. @tparam ReferenceType reference type; must be a reference to @ref array_t,
  11819. @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
  11820. @ref number_float_t. Enforced by static assertion.
  11821. @return reference to the internally stored JSON value if the requested
  11822. reference type @a ReferenceType fits to the JSON value; throws
  11823. type_error.303 otherwise
  11824. @throw type_error.303 in case passed type @a ReferenceType is incompatible
  11825. with the stored JSON value; see example below
  11826. @complexity Constant.
  11827. @liveexample{The example shows several calls to `get_ref()`.,get_ref}
  11828. @since version 1.1.0
  11829. */
  11830. template<typename ReferenceType, typename std::enable_if<
  11831. std::is_reference<ReferenceType>::value, int>::type = 0>
  11832. ReferenceType get_ref()
  11833. {
  11834. // delegate call to get_ref_impl
  11835. return get_ref_impl<ReferenceType>(*this);
  11836. }
  11837. /*!
  11838. @brief get a reference value (implicit)
  11839. @copydoc get_ref()
  11840. */
  11841. template<typename ReferenceType, typename std::enable_if<
  11842. std::is_reference<ReferenceType>::value and
  11843. std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
  11844. ReferenceType get_ref() const
  11845. {
  11846. // delegate call to get_ref_impl
  11847. return get_ref_impl<ReferenceType>(*this);
  11848. }
  11849. /*!
  11850. @brief get a value (implicit)
  11851. Implicit type conversion between the JSON value and a compatible value.
  11852. The call is realized by calling @ref get() const.
  11853. @tparam ValueType non-pointer type compatible to the JSON value, for
  11854. instance `int` for JSON integer numbers, `bool` for JSON booleans, or
  11855. `std::vector` types for JSON arrays. The character type of @ref string_t
  11856. as well as an initializer list of this type is excluded to avoid
  11857. ambiguities as these types implicitly convert to `std::string`.
  11858. @return copy of the JSON value, converted to type @a ValueType
  11859. @throw type_error.302 in case passed type @a ValueType is incompatible
  11860. to the JSON value type (e.g., the JSON value is of type boolean, but a
  11861. string is requested); see example below
  11862. @complexity Linear in the size of the JSON value.
  11863. @liveexample{The example below shows several conversions from JSON values
  11864. to other types. There a few things to note: (1) Floating-point numbers can
  11865. be converted to integers\, (2) A JSON array can be converted to a standard
  11866. `std::vector<short>`\, (3) A JSON object can be converted to C++
  11867. associative containers such as `std::unordered_map<std::string\,
  11868. json>`.,operator__ValueType}
  11869. @since version 1.0.0
  11870. */
  11871. template < typename ValueType, typename std::enable_if <
  11872. not std::is_pointer<ValueType>::value and
  11873. not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
  11874. not std::is_same<ValueType, typename string_t::value_type>::value and
  11875. not detail::is_basic_json<ValueType>::value
  11876. #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
  11877. and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
  11878. #if defined(JSON_HAS_CPP_17) && defined(_MSC_VER) and _MSC_VER <= 1914
  11879. and not std::is_same<ValueType, typename std::string_view>::value
  11880. #endif
  11881. #endif
  11882. , int >::type = 0 >
  11883. operator ValueType() const
  11884. {
  11885. // delegate the call to get<>() const
  11886. return get<ValueType>();
  11887. }
  11888. /// @}
  11889. ////////////////////
  11890. // element access //
  11891. ////////////////////
  11892. /// @name element access
  11893. /// Access to the JSON value.
  11894. /// @{
  11895. /*!
  11896. @brief access specified array element with bounds checking
  11897. Returns a reference to the element at specified location @a idx, with
  11898. bounds checking.
  11899. @param[in] idx index of the element to access
  11900. @return reference to the element at index @a idx
  11901. @throw type_error.304 if the JSON value is not an array; in this case,
  11902. calling `at` with an index makes no sense. See example below.
  11903. @throw out_of_range.401 if the index @a idx is out of range of the array;
  11904. that is, `idx >= size()`. See example below.
  11905. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11906. changes in the JSON value.
  11907. @complexity Constant.
  11908. @since version 1.0.0
  11909. @liveexample{The example below shows how array elements can be read and
  11910. written using `at()`. It also demonstrates the different exceptions that
  11911. can be thrown.,at__size_type}
  11912. */
  11913. reference at(size_type idx)
  11914. {
  11915. // at only works for arrays
  11916. if (JSON_LIKELY(is_array()))
  11917. {
  11918. JSON_TRY
  11919. {
  11920. return m_value.array->at(idx);
  11921. }
  11922. JSON_CATCH (std::out_of_range&)
  11923. {
  11924. // create better exception explanation
  11925. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11926. }
  11927. }
  11928. else
  11929. {
  11930. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  11931. }
  11932. }
  11933. /*!
  11934. @brief access specified array element with bounds checking
  11935. Returns a const reference to the element at specified location @a idx,
  11936. with bounds checking.
  11937. @param[in] idx index of the element to access
  11938. @return const reference to the element at index @a idx
  11939. @throw type_error.304 if the JSON value is not an array; in this case,
  11940. calling `at` with an index makes no sense. See example below.
  11941. @throw out_of_range.401 if the index @a idx is out of range of the array;
  11942. that is, `idx >= size()`. See example below.
  11943. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11944. changes in the JSON value.
  11945. @complexity Constant.
  11946. @since version 1.0.0
  11947. @liveexample{The example below shows how array elements can be read using
  11948. `at()`. It also demonstrates the different exceptions that can be thrown.,
  11949. at__size_type_const}
  11950. */
  11951. const_reference at(size_type idx) const
  11952. {
  11953. // at only works for arrays
  11954. if (JSON_LIKELY(is_array()))
  11955. {
  11956. JSON_TRY
  11957. {
  11958. return m_value.array->at(idx);
  11959. }
  11960. JSON_CATCH (std::out_of_range&)
  11961. {
  11962. // create better exception explanation
  11963. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  11964. }
  11965. }
  11966. else
  11967. {
  11968. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  11969. }
  11970. }
  11971. /*!
  11972. @brief access specified object element with bounds checking
  11973. Returns a reference to the element at with specified key @a key, with
  11974. bounds checking.
  11975. @param[in] key key of the element to access
  11976. @return reference to the element at key @a key
  11977. @throw type_error.304 if the JSON value is not an object; in this case,
  11978. calling `at` with a key makes no sense. See example below.
  11979. @throw out_of_range.403 if the key @a key is is not stored in the object;
  11980. that is, `find(key) == end()`. See example below.
  11981. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  11982. changes in the JSON value.
  11983. @complexity Logarithmic in the size of the container.
  11984. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  11985. access by reference
  11986. @sa @ref value() for access by value with a default value
  11987. @since version 1.0.0
  11988. @liveexample{The example below shows how object elements can be read and
  11989. written using `at()`. It also demonstrates the different exceptions that
  11990. can be thrown.,at__object_t_key_type}
  11991. */
  11992. reference at(const typename object_t::key_type& key)
  11993. {
  11994. // at only works for objects
  11995. if (JSON_LIKELY(is_object()))
  11996. {
  11997. JSON_TRY
  11998. {
  11999. return m_value.object->at(key);
  12000. }
  12001. JSON_CATCH (std::out_of_range&)
  12002. {
  12003. // create better exception explanation
  12004. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  12005. }
  12006. }
  12007. else
  12008. {
  12009. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  12010. }
  12011. }
  12012. /*!
  12013. @brief access specified object element with bounds checking
  12014. Returns a const reference to the element at with specified key @a key,
  12015. with bounds checking.
  12016. @param[in] key key of the element to access
  12017. @return const reference to the element at key @a key
  12018. @throw type_error.304 if the JSON value is not an object; in this case,
  12019. calling `at` with a key makes no sense. See example below.
  12020. @throw out_of_range.403 if the key @a key is is not stored in the object;
  12021. that is, `find(key) == end()`. See example below.
  12022. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12023. changes in the JSON value.
  12024. @complexity Logarithmic in the size of the container.
  12025. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  12026. access by reference
  12027. @sa @ref value() for access by value with a default value
  12028. @since version 1.0.0
  12029. @liveexample{The example below shows how object elements can be read using
  12030. `at()`. It also demonstrates the different exceptions that can be thrown.,
  12031. at__object_t_key_type_const}
  12032. */
  12033. const_reference at(const typename object_t::key_type& key) const
  12034. {
  12035. // at only works for objects
  12036. if (JSON_LIKELY(is_object()))
  12037. {
  12038. JSON_TRY
  12039. {
  12040. return m_value.object->at(key);
  12041. }
  12042. JSON_CATCH (std::out_of_range&)
  12043. {
  12044. // create better exception explanation
  12045. JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
  12046. }
  12047. }
  12048. else
  12049. {
  12050. JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
  12051. }
  12052. }
  12053. /*!
  12054. @brief access specified array element
  12055. Returns a reference to the element at specified location @a idx.
  12056. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
  12057. then the array is silently filled up with `null` values to make `idx` a
  12058. valid reference to the last stored element.
  12059. @param[in] idx index of the element to access
  12060. @return reference to the element at index @a idx
  12061. @throw type_error.305 if the JSON value is not an array or null; in that
  12062. cases, using the [] operator with an index makes no sense.
  12063. @complexity Constant if @a idx is in the range of the array. Otherwise
  12064. linear in `idx - size()`.
  12065. @liveexample{The example below shows how array elements can be read and
  12066. written using `[]` operator. Note the addition of `null`
  12067. values.,operatorarray__size_type}
  12068. @since version 1.0.0
  12069. */
  12070. reference operator[](size_type idx)
  12071. {
  12072. // implicitly convert null value to an empty array
  12073. if (is_null())
  12074. {
  12075. m_type = value_t::array;
  12076. m_value.array = create<array_t>();
  12077. assert_invariant();
  12078. }
  12079. // operator[] only works for arrays
  12080. if (JSON_LIKELY(is_array()))
  12081. {
  12082. // fill up array with null values if given idx is outside range
  12083. if (idx >= m_value.array->size())
  12084. {
  12085. m_value.array->insert(m_value.array->end(),
  12086. idx - m_value.array->size() + 1,
  12087. basic_json());
  12088. }
  12089. return m_value.array->operator[](idx);
  12090. }
  12091. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12092. }
  12093. /*!
  12094. @brief access specified array element
  12095. Returns a const reference to the element at specified location @a idx.
  12096. @param[in] idx index of the element to access
  12097. @return const reference to the element at index @a idx
  12098. @throw type_error.305 if the JSON value is not an array; in that case,
  12099. using the [] operator with an index makes no sense.
  12100. @complexity Constant.
  12101. @liveexample{The example below shows how array elements can be read using
  12102. the `[]` operator.,operatorarray__size_type_const}
  12103. @since version 1.0.0
  12104. */
  12105. const_reference operator[](size_type idx) const
  12106. {
  12107. // const operator[] only works for arrays
  12108. if (JSON_LIKELY(is_array()))
  12109. {
  12110. return m_value.array->operator[](idx);
  12111. }
  12112. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12113. }
  12114. /*!
  12115. @brief access specified object element
  12116. Returns a reference to the element at with specified key @a key.
  12117. @note If @a key is not found in the object, then it is silently added to
  12118. the object and filled with a `null` value to make `key` a valid reference.
  12119. In case the value was `null` before, it is converted to an object.
  12120. @param[in] key key of the element to access
  12121. @return reference to the element at key @a key
  12122. @throw type_error.305 if the JSON value is not an object or null; in that
  12123. cases, using the [] operator with a key makes no sense.
  12124. @complexity Logarithmic in the size of the container.
  12125. @liveexample{The example below shows how object elements can be read and
  12126. written using the `[]` operator.,operatorarray__key_type}
  12127. @sa @ref at(const typename object_t::key_type&) for access by reference
  12128. with range checking
  12129. @sa @ref value() for access by value with a default value
  12130. @since version 1.0.0
  12131. */
  12132. reference operator[](const typename object_t::key_type& key)
  12133. {
  12134. // implicitly convert null value to an empty object
  12135. if (is_null())
  12136. {
  12137. m_type = value_t::object;
  12138. m_value.object = create<object_t>();
  12139. assert_invariant();
  12140. }
  12141. // operator[] only works for objects
  12142. if (JSON_LIKELY(is_object()))
  12143. {
  12144. return m_value.object->operator[](key);
  12145. }
  12146. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12147. }
  12148. /*!
  12149. @brief read-only access specified object element
  12150. Returns a const reference to the element at with specified key @a key. No
  12151. bounds checking is performed.
  12152. @warning If the element with key @a key does not exist, the behavior is
  12153. undefined.
  12154. @param[in] key key of the element to access
  12155. @return const reference to the element at key @a key
  12156. @pre The element with key @a key must exist. **This precondition is
  12157. enforced with an assertion.**
  12158. @throw type_error.305 if the JSON value is not an object; in that case,
  12159. using the [] operator with a key makes no sense.
  12160. @complexity Logarithmic in the size of the container.
  12161. @liveexample{The example below shows how object elements can be read using
  12162. the `[]` operator.,operatorarray__key_type_const}
  12163. @sa @ref at(const typename object_t::key_type&) for access by reference
  12164. with range checking
  12165. @sa @ref value() for access by value with a default value
  12166. @since version 1.0.0
  12167. */
  12168. const_reference operator[](const typename object_t::key_type& key) const
  12169. {
  12170. // const operator[] only works for objects
  12171. if (JSON_LIKELY(is_object()))
  12172. {
  12173. assert(m_value.object->find(key) != m_value.object->end());
  12174. return m_value.object->find(key)->second;
  12175. }
  12176. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12177. }
  12178. /*!
  12179. @brief access specified object element
  12180. Returns a reference to the element at with specified key @a key.
  12181. @note If @a key is not found in the object, then it is silently added to
  12182. the object and filled with a `null` value to make `key` a valid reference.
  12183. In case the value was `null` before, it is converted to an object.
  12184. @param[in] key key of the element to access
  12185. @return reference to the element at key @a key
  12186. @throw type_error.305 if the JSON value is not an object or null; in that
  12187. cases, using the [] operator with a key makes no sense.
  12188. @complexity Logarithmic in the size of the container.
  12189. @liveexample{The example below shows how object elements can be read and
  12190. written using the `[]` operator.,operatorarray__key_type}
  12191. @sa @ref at(const typename object_t::key_type&) for access by reference
  12192. with range checking
  12193. @sa @ref value() for access by value with a default value
  12194. @since version 1.1.0
  12195. */
  12196. template<typename T>
  12197. reference operator[](T* key)
  12198. {
  12199. // implicitly convert null to object
  12200. if (is_null())
  12201. {
  12202. m_type = value_t::object;
  12203. m_value = value_t::object;
  12204. assert_invariant();
  12205. }
  12206. // at only works for objects
  12207. if (JSON_LIKELY(is_object()))
  12208. {
  12209. return m_value.object->operator[](key);
  12210. }
  12211. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12212. }
  12213. /*!
  12214. @brief read-only access specified object element
  12215. Returns a const reference to the element at with specified key @a key. No
  12216. bounds checking is performed.
  12217. @warning If the element with key @a key does not exist, the behavior is
  12218. undefined.
  12219. @param[in] key key of the element to access
  12220. @return const reference to the element at key @a key
  12221. @pre The element with key @a key must exist. **This precondition is
  12222. enforced with an assertion.**
  12223. @throw type_error.305 if the JSON value is not an object; in that case,
  12224. using the [] operator with a key makes no sense.
  12225. @complexity Logarithmic in the size of the container.
  12226. @liveexample{The example below shows how object elements can be read using
  12227. the `[]` operator.,operatorarray__key_type_const}
  12228. @sa @ref at(const typename object_t::key_type&) for access by reference
  12229. with range checking
  12230. @sa @ref value() for access by value with a default value
  12231. @since version 1.1.0
  12232. */
  12233. template<typename T>
  12234. const_reference operator[](T* key) const
  12235. {
  12236. // at only works for objects
  12237. if (JSON_LIKELY(is_object()))
  12238. {
  12239. assert(m_value.object->find(key) != m_value.object->end());
  12240. return m_value.object->find(key)->second;
  12241. }
  12242. JSON_THROW(type_error::create(305, "cannot use operator[] with " + std::string(type_name())));
  12243. }
  12244. /*!
  12245. @brief access specified object element with default value
  12246. Returns either a copy of an object's element at the specified key @a key
  12247. or a given default value if no element with key @a key exists.
  12248. The function is basically equivalent to executing
  12249. @code {.cpp}
  12250. try {
  12251. return at(key);
  12252. } catch(out_of_range) {
  12253. return default_value;
  12254. }
  12255. @endcode
  12256. @note Unlike @ref at(const typename object_t::key_type&), this function
  12257. does not throw if the given key @a key was not found.
  12258. @note Unlike @ref operator[](const typename object_t::key_type& key), this
  12259. function does not implicitly add an element to the position defined by @a
  12260. key. This function is furthermore also applicable to const objects.
  12261. @param[in] key key of the element to access
  12262. @param[in] default_value the value to return if @a key is not found
  12263. @tparam ValueType type compatible to JSON values, for instance `int` for
  12264. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  12265. JSON arrays. Note the type of the expected value at @a key and the default
  12266. value @a default_value must be compatible.
  12267. @return copy of the element at key @a key or @a default_value if @a key
  12268. is not found
  12269. @throw type_error.306 if the JSON value is not an object; in that case,
  12270. using `value()` with a key makes no sense.
  12271. @complexity Logarithmic in the size of the container.
  12272. @liveexample{The example below shows how object elements can be queried
  12273. with a default value.,basic_json__value}
  12274. @sa @ref at(const typename object_t::key_type&) for access by reference
  12275. with range checking
  12276. @sa @ref operator[](const typename object_t::key_type&) for unchecked
  12277. access by reference
  12278. @since version 1.0.0
  12279. */
  12280. template<class ValueType, typename std::enable_if<
  12281. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  12282. ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
  12283. {
  12284. // at only works for objects
  12285. if (JSON_LIKELY(is_object()))
  12286. {
  12287. // if key is found, return value and given default value otherwise
  12288. const auto it = find(key);
  12289. if (it != end())
  12290. {
  12291. return *it;
  12292. }
  12293. return default_value;
  12294. }
  12295. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  12296. }
  12297. /*!
  12298. @brief overload for a default value of type const char*
  12299. @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
  12300. */
  12301. string_t value(const typename object_t::key_type& key, const char* default_value) const
  12302. {
  12303. return value(key, string_t(default_value));
  12304. }
  12305. /*!
  12306. @brief access specified object element via JSON Pointer with default value
  12307. Returns either a copy of an object's element at the specified key @a key
  12308. or a given default value if no element with key @a key exists.
  12309. The function is basically equivalent to executing
  12310. @code {.cpp}
  12311. try {
  12312. return at(ptr);
  12313. } catch(out_of_range) {
  12314. return default_value;
  12315. }
  12316. @endcode
  12317. @note Unlike @ref at(const json_pointer&), this function does not throw
  12318. if the given key @a key was not found.
  12319. @param[in] ptr a JSON pointer to the element to access
  12320. @param[in] default_value the value to return if @a ptr found no value
  12321. @tparam ValueType type compatible to JSON values, for instance `int` for
  12322. JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
  12323. JSON arrays. Note the type of the expected value at @a key and the default
  12324. value @a default_value must be compatible.
  12325. @return copy of the element at key @a key or @a default_value if @a key
  12326. is not found
  12327. @throw type_error.306 if the JSON value is not an object; in that case,
  12328. using `value()` with a key makes no sense.
  12329. @complexity Logarithmic in the size of the container.
  12330. @liveexample{The example below shows how object elements can be queried
  12331. with a default value.,basic_json__value_ptr}
  12332. @sa @ref operator[](const json_pointer&) for unchecked access by reference
  12333. @since version 2.0.2
  12334. */
  12335. template<class ValueType, typename std::enable_if<
  12336. std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
  12337. ValueType value(const json_pointer& ptr, const ValueType& default_value) const
  12338. {
  12339. // at only works for objects
  12340. if (JSON_LIKELY(is_object()))
  12341. {
  12342. // if pointer resolves a value, return it or use default value
  12343. JSON_TRY
  12344. {
  12345. return ptr.get_checked(this);
  12346. }
  12347. JSON_INTERNAL_CATCH (out_of_range&)
  12348. {
  12349. return default_value;
  12350. }
  12351. }
  12352. JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
  12353. }
  12354. /*!
  12355. @brief overload for a default value of type const char*
  12356. @copydoc basic_json::value(const json_pointer&, ValueType) const
  12357. */
  12358. string_t value(const json_pointer& ptr, const char* default_value) const
  12359. {
  12360. return value(ptr, string_t(default_value));
  12361. }
  12362. /*!
  12363. @brief access the first element
  12364. Returns a reference to the first element in the container. For a JSON
  12365. container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
  12366. @return In case of a structured type (array or object), a reference to the
  12367. first element is returned. In case of number, string, or boolean values, a
  12368. reference to the value is returned.
  12369. @complexity Constant.
  12370. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  12371. or an empty array or object (undefined behavior, **guarded by
  12372. assertions**).
  12373. @post The JSON value remains unchanged.
  12374. @throw invalid_iterator.214 when called on `null` value
  12375. @liveexample{The following code shows an example for `front()`.,front}
  12376. @sa @ref back() -- access the last element
  12377. @since version 1.0.0
  12378. */
  12379. reference front()
  12380. {
  12381. return *begin();
  12382. }
  12383. /*!
  12384. @copydoc basic_json::front()
  12385. */
  12386. const_reference front() const
  12387. {
  12388. return *cbegin();
  12389. }
  12390. /*!
  12391. @brief access the last element
  12392. Returns a reference to the last element in the container. For a JSON
  12393. container `c`, the expression `c.back()` is equivalent to
  12394. @code {.cpp}
  12395. auto tmp = c.end();
  12396. --tmp;
  12397. return *tmp;
  12398. @endcode
  12399. @return In case of a structured type (array or object), a reference to the
  12400. last element is returned. In case of number, string, or boolean values, a
  12401. reference to the value is returned.
  12402. @complexity Constant.
  12403. @pre The JSON value must not be `null` (would throw `std::out_of_range`)
  12404. or an empty array or object (undefined behavior, **guarded by
  12405. assertions**).
  12406. @post The JSON value remains unchanged.
  12407. @throw invalid_iterator.214 when called on a `null` value. See example
  12408. below.
  12409. @liveexample{The following code shows an example for `back()`.,back}
  12410. @sa @ref front() -- access the first element
  12411. @since version 1.0.0
  12412. */
  12413. reference back()
  12414. {
  12415. auto tmp = end();
  12416. --tmp;
  12417. return *tmp;
  12418. }
  12419. /*!
  12420. @copydoc basic_json::back()
  12421. */
  12422. const_reference back() const
  12423. {
  12424. auto tmp = cend();
  12425. --tmp;
  12426. return *tmp;
  12427. }
  12428. /*!
  12429. @brief remove element given an iterator
  12430. Removes the element specified by iterator @a pos. The iterator @a pos must
  12431. be valid and dereferenceable. Thus the `end()` iterator (which is valid,
  12432. but is not dereferenceable) cannot be used as a value for @a pos.
  12433. If called on a primitive type other than `null`, the resulting JSON value
  12434. will be `null`.
  12435. @param[in] pos iterator to the element to remove
  12436. @return Iterator following the last removed element. If the iterator @a
  12437. pos refers to the last element, the `end()` iterator is returned.
  12438. @tparam IteratorType an @ref iterator or @ref const_iterator
  12439. @post Invalidates iterators and references at or after the point of the
  12440. erase, including the `end()` iterator.
  12441. @throw type_error.307 if called on a `null` value; example: `"cannot use
  12442. erase() with null"`
  12443. @throw invalid_iterator.202 if called on an iterator which does not belong
  12444. to the current JSON value; example: `"iterator does not fit current
  12445. value"`
  12446. @throw invalid_iterator.205 if called on a primitive type with invalid
  12447. iterator (i.e., any iterator which is not `begin()`); example: `"iterator
  12448. out of range"`
  12449. @complexity The complexity depends on the type:
  12450. - objects: amortized constant
  12451. - arrays: linear in distance between @a pos and the end of the container
  12452. - strings: linear in the length of the string
  12453. - other types: constant
  12454. @liveexample{The example shows the result of `erase()` for different JSON
  12455. types.,erase__IteratorType}
  12456. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  12457. the given range
  12458. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  12459. from an object at the given key
  12460. @sa @ref erase(const size_type) -- removes the element from an array at
  12461. the given index
  12462. @since version 1.0.0
  12463. */
  12464. template<class IteratorType, typename std::enable_if<
  12465. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  12466. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  12467. = 0>
  12468. IteratorType erase(IteratorType pos)
  12469. {
  12470. // make sure iterator fits the current value
  12471. if (JSON_UNLIKELY(this != pos.m_object))
  12472. {
  12473. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  12474. }
  12475. IteratorType result = end();
  12476. switch (m_type)
  12477. {
  12478. case value_t::boolean:
  12479. case value_t::number_float:
  12480. case value_t::number_integer:
  12481. case value_t::number_unsigned:
  12482. case value_t::string:
  12483. {
  12484. if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
  12485. {
  12486. JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
  12487. }
  12488. if (is_string())
  12489. {
  12490. AllocatorType<string_t> alloc;
  12491. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  12492. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  12493. m_value.string = nullptr;
  12494. }
  12495. m_type = value_t::null;
  12496. assert_invariant();
  12497. break;
  12498. }
  12499. case value_t::object:
  12500. {
  12501. result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
  12502. break;
  12503. }
  12504. case value_t::array:
  12505. {
  12506. result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
  12507. break;
  12508. }
  12509. default:
  12510. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  12511. }
  12512. return result;
  12513. }
  12514. /*!
  12515. @brief remove elements given an iterator range
  12516. Removes the element specified by the range `[first; last)`. The iterator
  12517. @a first does not need to be dereferenceable if `first == last`: erasing
  12518. an empty range is a no-op.
  12519. If called on a primitive type other than `null`, the resulting JSON value
  12520. will be `null`.
  12521. @param[in] first iterator to the beginning of the range to remove
  12522. @param[in] last iterator past the end of the range to remove
  12523. @return Iterator following the last removed element. If the iterator @a
  12524. second refers to the last element, the `end()` iterator is returned.
  12525. @tparam IteratorType an @ref iterator or @ref const_iterator
  12526. @post Invalidates iterators and references at or after the point of the
  12527. erase, including the `end()` iterator.
  12528. @throw type_error.307 if called on a `null` value; example: `"cannot use
  12529. erase() with null"`
  12530. @throw invalid_iterator.203 if called on iterators which does not belong
  12531. to the current JSON value; example: `"iterators do not fit current value"`
  12532. @throw invalid_iterator.204 if called on a primitive type with invalid
  12533. iterators (i.e., if `first != begin()` and `last != end()`); example:
  12534. `"iterators out of range"`
  12535. @complexity The complexity depends on the type:
  12536. - objects: `log(size()) + std::distance(first, last)`
  12537. - arrays: linear in the distance between @a first and @a last, plus linear
  12538. in the distance between @a last and end of the container
  12539. - strings: linear in the length of the string
  12540. - other types: constant
  12541. @liveexample{The example shows the result of `erase()` for different JSON
  12542. types.,erase__IteratorType_IteratorType}
  12543. @sa @ref erase(IteratorType) -- removes the element at a given position
  12544. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  12545. from an object at the given key
  12546. @sa @ref erase(const size_type) -- removes the element from an array at
  12547. the given index
  12548. @since version 1.0.0
  12549. */
  12550. template<class IteratorType, typename std::enable_if<
  12551. std::is_same<IteratorType, typename basic_json_t::iterator>::value or
  12552. std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
  12553. = 0>
  12554. IteratorType erase(IteratorType first, IteratorType last)
  12555. {
  12556. // make sure iterator fits the current value
  12557. if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))
  12558. {
  12559. JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
  12560. }
  12561. IteratorType result = end();
  12562. switch (m_type)
  12563. {
  12564. case value_t::boolean:
  12565. case value_t::number_float:
  12566. case value_t::number_integer:
  12567. case value_t::number_unsigned:
  12568. case value_t::string:
  12569. {
  12570. if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()
  12571. or not last.m_it.primitive_iterator.is_end()))
  12572. {
  12573. JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
  12574. }
  12575. if (is_string())
  12576. {
  12577. AllocatorType<string_t> alloc;
  12578. std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
  12579. std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
  12580. m_value.string = nullptr;
  12581. }
  12582. m_type = value_t::null;
  12583. assert_invariant();
  12584. break;
  12585. }
  12586. case value_t::object:
  12587. {
  12588. result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
  12589. last.m_it.object_iterator);
  12590. break;
  12591. }
  12592. case value_t::array:
  12593. {
  12594. result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
  12595. last.m_it.array_iterator);
  12596. break;
  12597. }
  12598. default:
  12599. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  12600. }
  12601. return result;
  12602. }
  12603. /*!
  12604. @brief remove element from a JSON object given a key
  12605. Removes elements from a JSON object with the key value @a key.
  12606. @param[in] key value of the elements to remove
  12607. @return Number of elements removed. If @a ObjectType is the default
  12608. `std::map` type, the return value will always be `0` (@a key was not
  12609. found) or `1` (@a key was found).
  12610. @post References and iterators to the erased elements are invalidated.
  12611. Other references and iterators are not affected.
  12612. @throw type_error.307 when called on a type other than JSON object;
  12613. example: `"cannot use erase() with null"`
  12614. @complexity `log(size()) + count(key)`
  12615. @liveexample{The example shows the effect of `erase()`.,erase__key_type}
  12616. @sa @ref erase(IteratorType) -- removes the element at a given position
  12617. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  12618. the given range
  12619. @sa @ref erase(const size_type) -- removes the element from an array at
  12620. the given index
  12621. @since version 1.0.0
  12622. */
  12623. size_type erase(const typename object_t::key_type& key)
  12624. {
  12625. // this erase only works for objects
  12626. if (JSON_LIKELY(is_object()))
  12627. {
  12628. return m_value.object->erase(key);
  12629. }
  12630. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  12631. }
  12632. /*!
  12633. @brief remove element from a JSON array given an index
  12634. Removes element from a JSON array at the index @a idx.
  12635. @param[in] idx index of the element to remove
  12636. @throw type_error.307 when called on a type other than JSON object;
  12637. example: `"cannot use erase() with null"`
  12638. @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
  12639. is out of range"`
  12640. @complexity Linear in distance between @a idx and the end of the container.
  12641. @liveexample{The example shows the effect of `erase()`.,erase__size_type}
  12642. @sa @ref erase(IteratorType) -- removes the element at a given position
  12643. @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
  12644. the given range
  12645. @sa @ref erase(const typename object_t::key_type&) -- removes the element
  12646. from an object at the given key
  12647. @since version 1.0.0
  12648. */
  12649. void erase(const size_type idx)
  12650. {
  12651. // this erase only works for arrays
  12652. if (JSON_LIKELY(is_array()))
  12653. {
  12654. if (JSON_UNLIKELY(idx >= size()))
  12655. {
  12656. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  12657. }
  12658. m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
  12659. }
  12660. else
  12661. {
  12662. JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
  12663. }
  12664. }
  12665. /// @}
  12666. ////////////
  12667. // lookup //
  12668. ////////////
  12669. /// @name lookup
  12670. /// @{
  12671. /*!
  12672. @brief find an element in a JSON object
  12673. Finds an element in a JSON object with key equivalent to @a key. If the
  12674. element is not found or the JSON value is not an object, end() is
  12675. returned.
  12676. @note This method always returns @ref end() when executed on a JSON type
  12677. that is not an object.
  12678. @param[in] key key value of the element to search for.
  12679. @return Iterator to an element with key equivalent to @a key. If no such
  12680. element is found or the JSON value is not an object, past-the-end (see
  12681. @ref end()) iterator is returned.
  12682. @complexity Logarithmic in the size of the JSON object.
  12683. @liveexample{The example shows how `find()` is used.,find__key_type}
  12684. @since version 1.0.0
  12685. */
  12686. template<typename KeyT>
  12687. iterator find(KeyT&& key)
  12688. {
  12689. auto result = end();
  12690. if (is_object())
  12691. {
  12692. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  12693. }
  12694. return result;
  12695. }
  12696. /*!
  12697. @brief find an element in a JSON object
  12698. @copydoc find(KeyT&&)
  12699. */
  12700. template<typename KeyT>
  12701. const_iterator find(KeyT&& key) const
  12702. {
  12703. auto result = cend();
  12704. if (is_object())
  12705. {
  12706. result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
  12707. }
  12708. return result;
  12709. }
  12710. /*!
  12711. @brief returns the number of occurrences of a key in a JSON object
  12712. Returns the number of elements with key @a key. If ObjectType is the
  12713. default `std::map` type, the return value will always be `0` (@a key was
  12714. not found) or `1` (@a key was found).
  12715. @note This method always returns `0` when executed on a JSON type that is
  12716. not an object.
  12717. @param[in] key key value of the element to count
  12718. @return Number of elements with key @a key. If the JSON value is not an
  12719. object, the return value will be `0`.
  12720. @complexity Logarithmic in the size of the JSON object.
  12721. @liveexample{The example shows how `count()` is used.,count}
  12722. @since version 1.0.0
  12723. */
  12724. template<typename KeyT>
  12725. size_type count(KeyT&& key) const
  12726. {
  12727. // return 0 for all nonobject types
  12728. return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
  12729. }
  12730. /// @}
  12731. ///////////////
  12732. // iterators //
  12733. ///////////////
  12734. /// @name iterators
  12735. /// @{
  12736. /*!
  12737. @brief returns an iterator to the first element
  12738. Returns an iterator to the first element.
  12739. @image html range-begin-end.svg "Illustration from cppreference.com"
  12740. @return iterator to the first element
  12741. @complexity Constant.
  12742. @requirement This function helps `basic_json` satisfying the
  12743. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12744. requirements:
  12745. - The complexity is constant.
  12746. @liveexample{The following code shows an example for `begin()`.,begin}
  12747. @sa @ref cbegin() -- returns a const iterator to the beginning
  12748. @sa @ref end() -- returns an iterator to the end
  12749. @sa @ref cend() -- returns a const iterator to the end
  12750. @since version 1.0.0
  12751. */
  12752. iterator begin() noexcept
  12753. {
  12754. iterator result(this);
  12755. result.set_begin();
  12756. return result;
  12757. }
  12758. /*!
  12759. @copydoc basic_json::cbegin()
  12760. */
  12761. const_iterator begin() const noexcept
  12762. {
  12763. return cbegin();
  12764. }
  12765. /*!
  12766. @brief returns a const iterator to the first element
  12767. Returns a const iterator to the first element.
  12768. @image html range-begin-end.svg "Illustration from cppreference.com"
  12769. @return const iterator to the first element
  12770. @complexity Constant.
  12771. @requirement This function helps `basic_json` satisfying the
  12772. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12773. requirements:
  12774. - The complexity is constant.
  12775. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
  12776. @liveexample{The following code shows an example for `cbegin()`.,cbegin}
  12777. @sa @ref begin() -- returns an iterator to the beginning
  12778. @sa @ref end() -- returns an iterator to the end
  12779. @sa @ref cend() -- returns a const iterator to the end
  12780. @since version 1.0.0
  12781. */
  12782. const_iterator cbegin() const noexcept
  12783. {
  12784. const_iterator result(this);
  12785. result.set_begin();
  12786. return result;
  12787. }
  12788. /*!
  12789. @brief returns an iterator to one past the last element
  12790. Returns an iterator to one past the last element.
  12791. @image html range-begin-end.svg "Illustration from cppreference.com"
  12792. @return iterator one past the last element
  12793. @complexity Constant.
  12794. @requirement This function helps `basic_json` satisfying the
  12795. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12796. requirements:
  12797. - The complexity is constant.
  12798. @liveexample{The following code shows an example for `end()`.,end}
  12799. @sa @ref cend() -- returns a const iterator to the end
  12800. @sa @ref begin() -- returns an iterator to the beginning
  12801. @sa @ref cbegin() -- returns a const iterator to the beginning
  12802. @since version 1.0.0
  12803. */
  12804. iterator end() noexcept
  12805. {
  12806. iterator result(this);
  12807. result.set_end();
  12808. return result;
  12809. }
  12810. /*!
  12811. @copydoc basic_json::cend()
  12812. */
  12813. const_iterator end() const noexcept
  12814. {
  12815. return cend();
  12816. }
  12817. /*!
  12818. @brief returns a const iterator to one past the last element
  12819. Returns a const iterator to one past the last element.
  12820. @image html range-begin-end.svg "Illustration from cppreference.com"
  12821. @return const iterator one past the last element
  12822. @complexity Constant.
  12823. @requirement This function helps `basic_json` satisfying the
  12824. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  12825. requirements:
  12826. - The complexity is constant.
  12827. - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
  12828. @liveexample{The following code shows an example for `cend()`.,cend}
  12829. @sa @ref end() -- returns an iterator to the end
  12830. @sa @ref begin() -- returns an iterator to the beginning
  12831. @sa @ref cbegin() -- returns a const iterator to the beginning
  12832. @since version 1.0.0
  12833. */
  12834. const_iterator cend() const noexcept
  12835. {
  12836. const_iterator result(this);
  12837. result.set_end();
  12838. return result;
  12839. }
  12840. /*!
  12841. @brief returns an iterator to the reverse-beginning
  12842. Returns an iterator to the reverse-beginning; that is, the last element.
  12843. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  12844. @complexity Constant.
  12845. @requirement This function helps `basic_json` satisfying the
  12846. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  12847. requirements:
  12848. - The complexity is constant.
  12849. - Has the semantics of `reverse_iterator(end())`.
  12850. @liveexample{The following code shows an example for `rbegin()`.,rbegin}
  12851. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  12852. @sa @ref rend() -- returns a reverse iterator to the end
  12853. @sa @ref crend() -- returns a const reverse iterator to the end
  12854. @since version 1.0.0
  12855. */
  12856. reverse_iterator rbegin() noexcept
  12857. {
  12858. return reverse_iterator(end());
  12859. }
  12860. /*!
  12861. @copydoc basic_json::crbegin()
  12862. */
  12863. const_reverse_iterator rbegin() const noexcept
  12864. {
  12865. return crbegin();
  12866. }
  12867. /*!
  12868. @brief returns an iterator to the reverse-end
  12869. Returns an iterator to the reverse-end; that is, one before the first
  12870. element.
  12871. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  12872. @complexity Constant.
  12873. @requirement This function helps `basic_json` satisfying the
  12874. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  12875. requirements:
  12876. - The complexity is constant.
  12877. - Has the semantics of `reverse_iterator(begin())`.
  12878. @liveexample{The following code shows an example for `rend()`.,rend}
  12879. @sa @ref crend() -- returns a const reverse iterator to the end
  12880. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  12881. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  12882. @since version 1.0.0
  12883. */
  12884. reverse_iterator rend() noexcept
  12885. {
  12886. return reverse_iterator(begin());
  12887. }
  12888. /*!
  12889. @copydoc basic_json::crend()
  12890. */
  12891. const_reverse_iterator rend() const noexcept
  12892. {
  12893. return crend();
  12894. }
  12895. /*!
  12896. @brief returns a const reverse iterator to the last element
  12897. Returns a const iterator to the reverse-beginning; that is, the last
  12898. element.
  12899. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  12900. @complexity Constant.
  12901. @requirement This function helps `basic_json` satisfying the
  12902. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  12903. requirements:
  12904. - The complexity is constant.
  12905. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
  12906. @liveexample{The following code shows an example for `crbegin()`.,crbegin}
  12907. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  12908. @sa @ref rend() -- returns a reverse iterator to the end
  12909. @sa @ref crend() -- returns a const reverse iterator to the end
  12910. @since version 1.0.0
  12911. */
  12912. const_reverse_iterator crbegin() const noexcept
  12913. {
  12914. return const_reverse_iterator(cend());
  12915. }
  12916. /*!
  12917. @brief returns a const reverse iterator to one before the first
  12918. Returns a const reverse iterator to the reverse-end; that is, one before
  12919. the first element.
  12920. @image html range-rbegin-rend.svg "Illustration from cppreference.com"
  12921. @complexity Constant.
  12922. @requirement This function helps `basic_json` satisfying the
  12923. [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
  12924. requirements:
  12925. - The complexity is constant.
  12926. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
  12927. @liveexample{The following code shows an example for `crend()`.,crend}
  12928. @sa @ref rend() -- returns a reverse iterator to the end
  12929. @sa @ref rbegin() -- returns a reverse iterator to the beginning
  12930. @sa @ref crbegin() -- returns a const reverse iterator to the beginning
  12931. @since version 1.0.0
  12932. */
  12933. const_reverse_iterator crend() const noexcept
  12934. {
  12935. return const_reverse_iterator(cbegin());
  12936. }
  12937. public:
  12938. /*!
  12939. @brief wrapper to access iterator member functions in range-based for
  12940. This function allows to access @ref iterator::key() and @ref
  12941. iterator::value() during range-based for loops. In these loops, a
  12942. reference to the JSON values is returned, so there is no access to the
  12943. underlying iterator.
  12944. For loop without iterator_wrapper:
  12945. @code{cpp}
  12946. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  12947. {
  12948. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  12949. }
  12950. @endcode
  12951. Range-based for loop without iterator proxy:
  12952. @code{cpp}
  12953. for (auto it : j_object)
  12954. {
  12955. // "it" is of type json::reference and has no key() member
  12956. std::cout << "value: " << it << '\n';
  12957. }
  12958. @endcode
  12959. Range-based for loop with iterator proxy:
  12960. @code{cpp}
  12961. for (auto it : json::iterator_wrapper(j_object))
  12962. {
  12963. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  12964. }
  12965. @endcode
  12966. @note When iterating over an array, `key()` will return the index of the
  12967. element as string (see example).
  12968. @param[in] ref reference to a JSON value
  12969. @return iteration proxy object wrapping @a ref with an interface to use in
  12970. range-based for loops
  12971. @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
  12972. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  12973. changes in the JSON value.
  12974. @complexity Constant.
  12975. @note The name of this function is not yet final and may change in the
  12976. future.
  12977. @deprecated This stream operator is deprecated and will be removed in
  12978. future 4.0.0 of the library. Please use @ref items() instead;
  12979. that is, replace `json::iterator_wrapper(j)` with `j.items()`.
  12980. */
  12981. JSON_DEPRECATED
  12982. static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
  12983. {
  12984. return ref.items();
  12985. }
  12986. /*!
  12987. @copydoc iterator_wrapper(reference)
  12988. */
  12989. JSON_DEPRECATED
  12990. static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
  12991. {
  12992. return ref.items();
  12993. }
  12994. /*!
  12995. @brief helper to access iterator member functions in range-based for
  12996. This function allows to access @ref iterator::key() and @ref
  12997. iterator::value() during range-based for loops. In these loops, a
  12998. reference to the JSON values is returned, so there is no access to the
  12999. underlying iterator.
  13000. For loop without `items()` function:
  13001. @code{cpp}
  13002. for (auto it = j_object.begin(); it != j_object.end(); ++it)
  13003. {
  13004. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  13005. }
  13006. @endcode
  13007. Range-based for loop without `items()` function:
  13008. @code{cpp}
  13009. for (auto it : j_object)
  13010. {
  13011. // "it" is of type json::reference and has no key() member
  13012. std::cout << "value: " << it << '\n';
  13013. }
  13014. @endcode
  13015. Range-based for loop with `items()` function:
  13016. @code{cpp}
  13017. for (auto it : j_object.items())
  13018. {
  13019. std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
  13020. }
  13021. @endcode
  13022. @note When iterating over an array, `key()` will return the index of the
  13023. element as string (see example). For primitive types (e.g., numbers),
  13024. `key()` returns an empty string.
  13025. @return iteration proxy object wrapping @a ref with an interface to use in
  13026. range-based for loops
  13027. @liveexample{The following code shows how the function is used.,items}
  13028. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  13029. changes in the JSON value.
  13030. @complexity Constant.
  13031. @since version 3.1.0.
  13032. */
  13033. iteration_proxy<iterator> items() noexcept
  13034. {
  13035. return iteration_proxy<iterator>(*this);
  13036. }
  13037. /*!
  13038. @copydoc items()
  13039. */
  13040. iteration_proxy<const_iterator> items() const noexcept
  13041. {
  13042. return iteration_proxy<const_iterator>(*this);
  13043. }
  13044. /// @}
  13045. //////////////
  13046. // capacity //
  13047. //////////////
  13048. /// @name capacity
  13049. /// @{
  13050. /*!
  13051. @brief checks whether the container is empty.
  13052. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
  13053. @return The return value depends on the different types and is
  13054. defined as follows:
  13055. Value type | return value
  13056. ----------- | -------------
  13057. null | `true`
  13058. boolean | `false`
  13059. string | `false`
  13060. number | `false`
  13061. object | result of function `object_t::empty()`
  13062. array | result of function `array_t::empty()`
  13063. @liveexample{The following code uses `empty()` to check if a JSON
  13064. object contains any elements.,empty}
  13065. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  13066. the Container concept; that is, their `empty()` functions have constant
  13067. complexity.
  13068. @iterators No changes.
  13069. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13070. @note This function does not return whether a string stored as JSON value
  13071. is empty - it returns whether the JSON container itself is empty which is
  13072. false in the case of a string.
  13073. @requirement This function helps `basic_json` satisfying the
  13074. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13075. requirements:
  13076. - The complexity is constant.
  13077. - Has the semantics of `begin() == end()`.
  13078. @sa @ref size() -- returns the number of elements
  13079. @since version 1.0.0
  13080. */
  13081. bool empty() const noexcept
  13082. {
  13083. switch (m_type)
  13084. {
  13085. case value_t::null:
  13086. {
  13087. // null values are empty
  13088. return true;
  13089. }
  13090. case value_t::array:
  13091. {
  13092. // delegate call to array_t::empty()
  13093. return m_value.array->empty();
  13094. }
  13095. case value_t::object:
  13096. {
  13097. // delegate call to object_t::empty()
  13098. return m_value.object->empty();
  13099. }
  13100. default:
  13101. {
  13102. // all other types are nonempty
  13103. return false;
  13104. }
  13105. }
  13106. }
  13107. /*!
  13108. @brief returns the number of elements
  13109. Returns the number of elements in a JSON value.
  13110. @return The return value depends on the different types and is
  13111. defined as follows:
  13112. Value type | return value
  13113. ----------- | -------------
  13114. null | `0`
  13115. boolean | `1`
  13116. string | `1`
  13117. number | `1`
  13118. object | result of function object_t::size()
  13119. array | result of function array_t::size()
  13120. @liveexample{The following code calls `size()` on the different value
  13121. types.,size}
  13122. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  13123. the Container concept; that is, their size() functions have constant
  13124. complexity.
  13125. @iterators No changes.
  13126. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13127. @note This function does not return the length of a string stored as JSON
  13128. value - it returns the number of elements in the JSON value which is 1 in
  13129. the case of a string.
  13130. @requirement This function helps `basic_json` satisfying the
  13131. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13132. requirements:
  13133. - The complexity is constant.
  13134. - Has the semantics of `std::distance(begin(), end())`.
  13135. @sa @ref empty() -- checks whether the container is empty
  13136. @sa @ref max_size() -- returns the maximal number of elements
  13137. @since version 1.0.0
  13138. */
  13139. size_type size() const noexcept
  13140. {
  13141. switch (m_type)
  13142. {
  13143. case value_t::null:
  13144. {
  13145. // null values are empty
  13146. return 0;
  13147. }
  13148. case value_t::array:
  13149. {
  13150. // delegate call to array_t::size()
  13151. return m_value.array->size();
  13152. }
  13153. case value_t::object:
  13154. {
  13155. // delegate call to object_t::size()
  13156. return m_value.object->size();
  13157. }
  13158. default:
  13159. {
  13160. // all other types have size 1
  13161. return 1;
  13162. }
  13163. }
  13164. }
  13165. /*!
  13166. @brief returns the maximum possible number of elements
  13167. Returns the maximum number of elements a JSON value is able to hold due to
  13168. system or library implementation limitations, i.e. `std::distance(begin(),
  13169. end())` for the JSON value.
  13170. @return The return value depends on the different types and is
  13171. defined as follows:
  13172. Value type | return value
  13173. ----------- | -------------
  13174. null | `0` (same as `size()`)
  13175. boolean | `1` (same as `size()`)
  13176. string | `1` (same as `size()`)
  13177. number | `1` (same as `size()`)
  13178. object | result of function `object_t::max_size()`
  13179. array | result of function `array_t::max_size()`
  13180. @liveexample{The following code calls `max_size()` on the different value
  13181. types. Note the output is implementation specific.,max_size}
  13182. @complexity Constant, as long as @ref array_t and @ref object_t satisfy
  13183. the Container concept; that is, their `max_size()` functions have constant
  13184. complexity.
  13185. @iterators No changes.
  13186. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13187. @requirement This function helps `basic_json` satisfying the
  13188. [Container](https://en.cppreference.com/w/cpp/named_req/Container)
  13189. requirements:
  13190. - The complexity is constant.
  13191. - Has the semantics of returning `b.size()` where `b` is the largest
  13192. possible JSON value.
  13193. @sa @ref size() -- returns the number of elements
  13194. @since version 1.0.0
  13195. */
  13196. size_type max_size() const noexcept
  13197. {
  13198. switch (m_type)
  13199. {
  13200. case value_t::array:
  13201. {
  13202. // delegate call to array_t::max_size()
  13203. return m_value.array->max_size();
  13204. }
  13205. case value_t::object:
  13206. {
  13207. // delegate call to object_t::max_size()
  13208. return m_value.object->max_size();
  13209. }
  13210. default:
  13211. {
  13212. // all other types have max_size() == size()
  13213. return size();
  13214. }
  13215. }
  13216. }
  13217. /// @}
  13218. ///////////////
  13219. // modifiers //
  13220. ///////////////
  13221. /// @name modifiers
  13222. /// @{
  13223. /*!
  13224. @brief clears the contents
  13225. Clears the content of a JSON value and resets it to the default value as
  13226. if @ref basic_json(value_t) would have been called with the current value
  13227. type from @ref type():
  13228. Value type | initial value
  13229. ----------- | -------------
  13230. null | `null`
  13231. boolean | `false`
  13232. string | `""`
  13233. number | `0`
  13234. object | `{}`
  13235. array | `[]`
  13236. @post Has the same effect as calling
  13237. @code {.cpp}
  13238. *this = basic_json(type());
  13239. @endcode
  13240. @liveexample{The example below shows the effect of `clear()` to different
  13241. JSON types.,clear}
  13242. @complexity Linear in the size of the JSON value.
  13243. @iterators All iterators, pointers and references related to this container
  13244. are invalidated.
  13245. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13246. @sa @ref basic_json(value_t) -- constructor that creates an object with the
  13247. same value than calling `clear()`
  13248. @since version 1.0.0
  13249. */
  13250. void clear() noexcept
  13251. {
  13252. switch (m_type)
  13253. {
  13254. case value_t::number_integer:
  13255. {
  13256. m_value.number_integer = 0;
  13257. break;
  13258. }
  13259. case value_t::number_unsigned:
  13260. {
  13261. m_value.number_unsigned = 0;
  13262. break;
  13263. }
  13264. case value_t::number_float:
  13265. {
  13266. m_value.number_float = 0.0;
  13267. break;
  13268. }
  13269. case value_t::boolean:
  13270. {
  13271. m_value.boolean = false;
  13272. break;
  13273. }
  13274. case value_t::string:
  13275. {
  13276. m_value.string->clear();
  13277. break;
  13278. }
  13279. case value_t::array:
  13280. {
  13281. m_value.array->clear();
  13282. break;
  13283. }
  13284. case value_t::object:
  13285. {
  13286. m_value.object->clear();
  13287. break;
  13288. }
  13289. default:
  13290. break;
  13291. }
  13292. }
  13293. /*!
  13294. @brief add an object to an array
  13295. Appends the given element @a val to the end of the JSON value. If the
  13296. function is called on a JSON null value, an empty array is created before
  13297. appending @a val.
  13298. @param[in] val the value to add to the JSON array
  13299. @throw type_error.308 when called on a type other than JSON array or
  13300. null; example: `"cannot use push_back() with number"`
  13301. @complexity Amortized constant.
  13302. @liveexample{The example shows how `push_back()` and `+=` can be used to
  13303. add elements to a JSON array. Note how the `null` value was silently
  13304. converted to a JSON array.,push_back}
  13305. @since version 1.0.0
  13306. */
  13307. void push_back(basic_json&& val)
  13308. {
  13309. // push_back only works for null objects or arrays
  13310. if (JSON_UNLIKELY(not(is_null() or is_array())))
  13311. {
  13312. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  13313. }
  13314. // transform null object into an array
  13315. if (is_null())
  13316. {
  13317. m_type = value_t::array;
  13318. m_value = value_t::array;
  13319. assert_invariant();
  13320. }
  13321. // add element to array (move semantics)
  13322. m_value.array->push_back(std::move(val));
  13323. // invalidate object
  13324. val.m_type = value_t::null;
  13325. }
  13326. /*!
  13327. @brief add an object to an array
  13328. @copydoc push_back(basic_json&&)
  13329. */
  13330. reference operator+=(basic_json&& val)
  13331. {
  13332. push_back(std::move(val));
  13333. return *this;
  13334. }
  13335. /*!
  13336. @brief add an object to an array
  13337. @copydoc push_back(basic_json&&)
  13338. */
  13339. void push_back(const basic_json& val)
  13340. {
  13341. // push_back only works for null objects or arrays
  13342. if (JSON_UNLIKELY(not(is_null() or is_array())))
  13343. {
  13344. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  13345. }
  13346. // transform null object into an array
  13347. if (is_null())
  13348. {
  13349. m_type = value_t::array;
  13350. m_value = value_t::array;
  13351. assert_invariant();
  13352. }
  13353. // add element to array
  13354. m_value.array->push_back(val);
  13355. }
  13356. /*!
  13357. @brief add an object to an array
  13358. @copydoc push_back(basic_json&&)
  13359. */
  13360. reference operator+=(const basic_json& val)
  13361. {
  13362. push_back(val);
  13363. return *this;
  13364. }
  13365. /*!
  13366. @brief add an object to an object
  13367. Inserts the given element @a val to the JSON object. If the function is
  13368. called on a JSON null value, an empty object is created before inserting
  13369. @a val.
  13370. @param[in] val the value to add to the JSON object
  13371. @throw type_error.308 when called on a type other than JSON object or
  13372. null; example: `"cannot use push_back() with number"`
  13373. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  13374. @liveexample{The example shows how `push_back()` and `+=` can be used to
  13375. add elements to a JSON object. Note how the `null` value was silently
  13376. converted to a JSON object.,push_back__object_t__value}
  13377. @since version 1.0.0
  13378. */
  13379. void push_back(const typename object_t::value_type& val)
  13380. {
  13381. // push_back only works for null objects or objects
  13382. if (JSON_UNLIKELY(not(is_null() or is_object())))
  13383. {
  13384. JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
  13385. }
  13386. // transform null object into an object
  13387. if (is_null())
  13388. {
  13389. m_type = value_t::object;
  13390. m_value = value_t::object;
  13391. assert_invariant();
  13392. }
  13393. // add element to array
  13394. m_value.object->insert(val);
  13395. }
  13396. /*!
  13397. @brief add an object to an object
  13398. @copydoc push_back(const typename object_t::value_type&)
  13399. */
  13400. reference operator+=(const typename object_t::value_type& val)
  13401. {
  13402. push_back(val);
  13403. return *this;
  13404. }
  13405. /*!
  13406. @brief add an object to an object
  13407. This function allows to use `push_back` with an initializer list. In case
  13408. 1. the current value is an object,
  13409. 2. the initializer list @a init contains only two elements, and
  13410. 3. the first element of @a init is a string,
  13411. @a init is converted into an object element and added using
  13412. @ref push_back(const typename object_t::value_type&). Otherwise, @a init
  13413. is converted to a JSON value and added using @ref push_back(basic_json&&).
  13414. @param[in] init an initializer list
  13415. @complexity Linear in the size of the initializer list @a init.
  13416. @note This function is required to resolve an ambiguous overload error,
  13417. because pairs like `{"key", "value"}` can be both interpreted as
  13418. `object_t::value_type` or `std::initializer_list<basic_json>`, see
  13419. https://github.com/nlohmann/json/issues/235 for more information.
  13420. @liveexample{The example shows how initializer lists are treated as
  13421. objects when possible.,push_back__initializer_list}
  13422. */
  13423. void push_back(initializer_list_t init)
  13424. {
  13425. if (is_object() and init.size() == 2 and (*init.begin())->is_string())
  13426. {
  13427. basic_json&& key = init.begin()->moved_or_copied();
  13428. push_back(typename object_t::value_type(
  13429. std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
  13430. }
  13431. else
  13432. {
  13433. push_back(basic_json(init));
  13434. }
  13435. }
  13436. /*!
  13437. @brief add an object to an object
  13438. @copydoc push_back(initializer_list_t)
  13439. */
  13440. reference operator+=(initializer_list_t init)
  13441. {
  13442. push_back(init);
  13443. return *this;
  13444. }
  13445. /*!
  13446. @brief add an object to an array
  13447. Creates a JSON value from the passed parameters @a args to the end of the
  13448. JSON value. If the function is called on a JSON null value, an empty array
  13449. is created before appending the value created from @a args.
  13450. @param[in] args arguments to forward to a constructor of @ref basic_json
  13451. @tparam Args compatible types to create a @ref basic_json object
  13452. @throw type_error.311 when called on a type other than JSON array or
  13453. null; example: `"cannot use emplace_back() with number"`
  13454. @complexity Amortized constant.
  13455. @liveexample{The example shows how `push_back()` can be used to add
  13456. elements to a JSON array. Note how the `null` value was silently converted
  13457. to a JSON array.,emplace_back}
  13458. @since version 2.0.8
  13459. */
  13460. template<class... Args>
  13461. void emplace_back(Args&& ... args)
  13462. {
  13463. // emplace_back only works for null objects or arrays
  13464. if (JSON_UNLIKELY(not(is_null() or is_array())))
  13465. {
  13466. JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
  13467. }
  13468. // transform null object into an array
  13469. if (is_null())
  13470. {
  13471. m_type = value_t::array;
  13472. m_value = value_t::array;
  13473. assert_invariant();
  13474. }
  13475. // add element to array (perfect forwarding)
  13476. m_value.array->emplace_back(std::forward<Args>(args)...);
  13477. }
  13478. /*!
  13479. @brief add an object to an object if key does not exist
  13480. Inserts a new element into a JSON object constructed in-place with the
  13481. given @a args if there is no element with the key in the container. If the
  13482. function is called on a JSON null value, an empty object is created before
  13483. appending the value created from @a args.
  13484. @param[in] args arguments to forward to a constructor of @ref basic_json
  13485. @tparam Args compatible types to create a @ref basic_json object
  13486. @return a pair consisting of an iterator to the inserted element, or the
  13487. already-existing element if no insertion happened, and a bool
  13488. denoting whether the insertion took place.
  13489. @throw type_error.311 when called on a type other than JSON object or
  13490. null; example: `"cannot use emplace() with number"`
  13491. @complexity Logarithmic in the size of the container, O(log(`size()`)).
  13492. @liveexample{The example shows how `emplace()` can be used to add elements
  13493. to a JSON object. Note how the `null` value was silently converted to a
  13494. JSON object. Further note how no value is added if there was already one
  13495. value stored with the same key.,emplace}
  13496. @since version 2.0.8
  13497. */
  13498. template<class... Args>
  13499. std::pair<iterator, bool> emplace(Args&& ... args)
  13500. {
  13501. // emplace only works for null objects or arrays
  13502. if (JSON_UNLIKELY(not(is_null() or is_object())))
  13503. {
  13504. JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
  13505. }
  13506. // transform null object into an object
  13507. if (is_null())
  13508. {
  13509. m_type = value_t::object;
  13510. m_value = value_t::object;
  13511. assert_invariant();
  13512. }
  13513. // add element to array (perfect forwarding)
  13514. auto res = m_value.object->emplace(std::forward<Args>(args)...);
  13515. // create result iterator and set iterator to the result of emplace
  13516. auto it = begin();
  13517. it.m_it.object_iterator = res.first;
  13518. // return pair of iterator and boolean
  13519. return {it, res.second};
  13520. }
  13521. /*!
  13522. @brief inserts element
  13523. Inserts element @a val before iterator @a pos.
  13524. @param[in] pos iterator before which the content will be inserted; may be
  13525. the end() iterator
  13526. @param[in] val element to insert
  13527. @return iterator pointing to the inserted @a val.
  13528. @throw type_error.309 if called on JSON values other than arrays;
  13529. example: `"cannot use insert() with string"`
  13530. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  13531. example: `"iterator does not fit current value"`
  13532. @complexity Constant plus linear in the distance between @a pos and end of
  13533. the container.
  13534. @liveexample{The example shows how `insert()` is used.,insert}
  13535. @since version 1.0.0
  13536. */
  13537. iterator insert(const_iterator pos, const basic_json& val)
  13538. {
  13539. // insert only works for arrays
  13540. if (JSON_LIKELY(is_array()))
  13541. {
  13542. // check if iterator pos fits to this JSON value
  13543. if (JSON_UNLIKELY(pos.m_object != this))
  13544. {
  13545. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13546. }
  13547. // insert to array and return iterator
  13548. iterator result(this);
  13549. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
  13550. return result;
  13551. }
  13552. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  13553. }
  13554. /*!
  13555. @brief inserts element
  13556. @copydoc insert(const_iterator, const basic_json&)
  13557. */
  13558. iterator insert(const_iterator pos, basic_json&& val)
  13559. {
  13560. return insert(pos, val);
  13561. }
  13562. /*!
  13563. @brief inserts elements
  13564. Inserts @a cnt copies of @a val before iterator @a pos.
  13565. @param[in] pos iterator before which the content will be inserted; may be
  13566. the end() iterator
  13567. @param[in] cnt number of copies of @a val to insert
  13568. @param[in] val element to insert
  13569. @return iterator pointing to the first element inserted, or @a pos if
  13570. `cnt==0`
  13571. @throw type_error.309 if called on JSON values other than arrays; example:
  13572. `"cannot use insert() with string"`
  13573. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  13574. example: `"iterator does not fit current value"`
  13575. @complexity Linear in @a cnt plus linear in the distance between @a pos
  13576. and end of the container.
  13577. @liveexample{The example shows how `insert()` is used.,insert__count}
  13578. @since version 1.0.0
  13579. */
  13580. iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
  13581. {
  13582. // insert only works for arrays
  13583. if (JSON_LIKELY(is_array()))
  13584. {
  13585. // check if iterator pos fits to this JSON value
  13586. if (JSON_UNLIKELY(pos.m_object != this))
  13587. {
  13588. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13589. }
  13590. // insert to array and return iterator
  13591. iterator result(this);
  13592. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
  13593. return result;
  13594. }
  13595. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  13596. }
  13597. /*!
  13598. @brief inserts elements
  13599. Inserts elements from range `[first, last)` before iterator @a pos.
  13600. @param[in] pos iterator before which the content will be inserted; may be
  13601. the end() iterator
  13602. @param[in] first begin of the range of elements to insert
  13603. @param[in] last end of the range of elements to insert
  13604. @throw type_error.309 if called on JSON values other than arrays; example:
  13605. `"cannot use insert() with string"`
  13606. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  13607. example: `"iterator does not fit current value"`
  13608. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  13609. same JSON value; example: `"iterators do not fit"`
  13610. @throw invalid_iterator.211 if @a first or @a last are iterators into
  13611. container for which insert is called; example: `"passed iterators may not
  13612. belong to container"`
  13613. @return iterator pointing to the first element inserted, or @a pos if
  13614. `first==last`
  13615. @complexity Linear in `std::distance(first, last)` plus linear in the
  13616. distance between @a pos and end of the container.
  13617. @liveexample{The example shows how `insert()` is used.,insert__range}
  13618. @since version 1.0.0
  13619. */
  13620. iterator insert(const_iterator pos, const_iterator first, const_iterator last)
  13621. {
  13622. // insert only works for arrays
  13623. if (JSON_UNLIKELY(not is_array()))
  13624. {
  13625. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  13626. }
  13627. // check if iterator pos fits to this JSON value
  13628. if (JSON_UNLIKELY(pos.m_object != this))
  13629. {
  13630. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13631. }
  13632. // check if range iterators belong to the same JSON object
  13633. if (JSON_UNLIKELY(first.m_object != last.m_object))
  13634. {
  13635. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  13636. }
  13637. if (JSON_UNLIKELY(first.m_object == this))
  13638. {
  13639. JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
  13640. }
  13641. // insert to array and return iterator
  13642. iterator result(this);
  13643. result.m_it.array_iterator = m_value.array->insert(
  13644. pos.m_it.array_iterator,
  13645. first.m_it.array_iterator,
  13646. last.m_it.array_iterator);
  13647. return result;
  13648. }
  13649. /*!
  13650. @brief inserts elements
  13651. Inserts elements from initializer list @a ilist before iterator @a pos.
  13652. @param[in] pos iterator before which the content will be inserted; may be
  13653. the end() iterator
  13654. @param[in] ilist initializer list to insert the values from
  13655. @throw type_error.309 if called on JSON values other than arrays; example:
  13656. `"cannot use insert() with string"`
  13657. @throw invalid_iterator.202 if @a pos is not an iterator of *this;
  13658. example: `"iterator does not fit current value"`
  13659. @return iterator pointing to the first element inserted, or @a pos if
  13660. `ilist` is empty
  13661. @complexity Linear in `ilist.size()` plus linear in the distance between
  13662. @a pos and end of the container.
  13663. @liveexample{The example shows how `insert()` is used.,insert__ilist}
  13664. @since version 1.0.0
  13665. */
  13666. iterator insert(const_iterator pos, initializer_list_t ilist)
  13667. {
  13668. // insert only works for arrays
  13669. if (JSON_UNLIKELY(not is_array()))
  13670. {
  13671. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  13672. }
  13673. // check if iterator pos fits to this JSON value
  13674. if (JSON_UNLIKELY(pos.m_object != this))
  13675. {
  13676. JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
  13677. }
  13678. // insert to array and return iterator
  13679. iterator result(this);
  13680. result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());
  13681. return result;
  13682. }
  13683. /*!
  13684. @brief inserts elements
  13685. Inserts elements from range `[first, last)`.
  13686. @param[in] first begin of the range of elements to insert
  13687. @param[in] last end of the range of elements to insert
  13688. @throw type_error.309 if called on JSON values other than objects; example:
  13689. `"cannot use insert() with string"`
  13690. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  13691. point to an object; example: `"iterators first and last must point to
  13692. objects"`
  13693. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  13694. same JSON value; example: `"iterators do not fit"`
  13695. @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
  13696. of elements to insert.
  13697. @liveexample{The example shows how `insert()` is used.,insert__range_object}
  13698. @since version 3.0.0
  13699. */
  13700. void insert(const_iterator first, const_iterator last)
  13701. {
  13702. // insert only works for objects
  13703. if (JSON_UNLIKELY(not is_object()))
  13704. {
  13705. JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
  13706. }
  13707. // check if range iterators belong to the same JSON object
  13708. if (JSON_UNLIKELY(first.m_object != last.m_object))
  13709. {
  13710. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  13711. }
  13712. // passed iterators must belong to objects
  13713. if (JSON_UNLIKELY(not first.m_object->is_object()))
  13714. {
  13715. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  13716. }
  13717. m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
  13718. }
  13719. /*!
  13720. @brief updates a JSON object from another object, overwriting existing keys
  13721. Inserts all values from JSON object @a j and overwrites existing keys.
  13722. @param[in] j JSON object to read values from
  13723. @throw type_error.312 if called on JSON values other than objects; example:
  13724. `"cannot use update() with string"`
  13725. @complexity O(N*log(size() + N)), where N is the number of elements to
  13726. insert.
  13727. @liveexample{The example shows how `update()` is used.,update}
  13728. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  13729. @since version 3.0.0
  13730. */
  13731. void update(const_reference j)
  13732. {
  13733. // implicitly convert null value to an empty object
  13734. if (is_null())
  13735. {
  13736. m_type = value_t::object;
  13737. m_value.object = create<object_t>();
  13738. assert_invariant();
  13739. }
  13740. if (JSON_UNLIKELY(not is_object()))
  13741. {
  13742. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  13743. }
  13744. if (JSON_UNLIKELY(not j.is_object()))
  13745. {
  13746. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
  13747. }
  13748. for (auto it = j.cbegin(); it != j.cend(); ++it)
  13749. {
  13750. m_value.object->operator[](it.key()) = it.value();
  13751. }
  13752. }
  13753. /*!
  13754. @brief updates a JSON object from another object, overwriting existing keys
  13755. Inserts all values from from range `[first, last)` and overwrites existing
  13756. keys.
  13757. @param[in] first begin of the range of elements to insert
  13758. @param[in] last end of the range of elements to insert
  13759. @throw type_error.312 if called on JSON values other than objects; example:
  13760. `"cannot use update() with string"`
  13761. @throw invalid_iterator.202 if iterator @a first or @a last does does not
  13762. point to an object; example: `"iterators first and last must point to
  13763. objects"`
  13764. @throw invalid_iterator.210 if @a first and @a last do not belong to the
  13765. same JSON value; example: `"iterators do not fit"`
  13766. @complexity O(N*log(size() + N)), where N is the number of elements to
  13767. insert.
  13768. @liveexample{The example shows how `update()` is used__range.,update}
  13769. @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
  13770. @since version 3.0.0
  13771. */
  13772. void update(const_iterator first, const_iterator last)
  13773. {
  13774. // implicitly convert null value to an empty object
  13775. if (is_null())
  13776. {
  13777. m_type = value_t::object;
  13778. m_value.object = create<object_t>();
  13779. assert_invariant();
  13780. }
  13781. if (JSON_UNLIKELY(not is_object()))
  13782. {
  13783. JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
  13784. }
  13785. // check if range iterators belong to the same JSON object
  13786. if (JSON_UNLIKELY(first.m_object != last.m_object))
  13787. {
  13788. JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
  13789. }
  13790. // passed iterators must belong to objects
  13791. if (JSON_UNLIKELY(not first.m_object->is_object()
  13792. or not last.m_object->is_object()))
  13793. {
  13794. JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
  13795. }
  13796. for (auto it = first; it != last; ++it)
  13797. {
  13798. m_value.object->operator[](it.key()) = it.value();
  13799. }
  13800. }
  13801. /*!
  13802. @brief exchanges the values
  13803. Exchanges the contents of the JSON value with those of @a other. Does not
  13804. invoke any move, copy, or swap operations on individual elements. All
  13805. iterators and references remain valid. The past-the-end iterator is
  13806. invalidated.
  13807. @param[in,out] other JSON value to exchange the contents with
  13808. @complexity Constant.
  13809. @liveexample{The example below shows how JSON values can be swapped with
  13810. `swap()`.,swap__reference}
  13811. @since version 1.0.0
  13812. */
  13813. void swap(reference other) noexcept (
  13814. std::is_nothrow_move_constructible<value_t>::value and
  13815. std::is_nothrow_move_assignable<value_t>::value and
  13816. std::is_nothrow_move_constructible<json_value>::value and
  13817. std::is_nothrow_move_assignable<json_value>::value
  13818. )
  13819. {
  13820. std::swap(m_type, other.m_type);
  13821. std::swap(m_value, other.m_value);
  13822. assert_invariant();
  13823. }
  13824. /*!
  13825. @brief exchanges the values
  13826. Exchanges the contents of a JSON array with those of @a other. Does not
  13827. invoke any move, copy, or swap operations on individual elements. All
  13828. iterators and references remain valid. The past-the-end iterator is
  13829. invalidated.
  13830. @param[in,out] other array to exchange the contents with
  13831. @throw type_error.310 when JSON value is not an array; example: `"cannot
  13832. use swap() with string"`
  13833. @complexity Constant.
  13834. @liveexample{The example below shows how arrays can be swapped with
  13835. `swap()`.,swap__array_t}
  13836. @since version 1.0.0
  13837. */
  13838. void swap(array_t& other)
  13839. {
  13840. // swap only works for arrays
  13841. if (JSON_LIKELY(is_array()))
  13842. {
  13843. std::swap(*(m_value.array), other);
  13844. }
  13845. else
  13846. {
  13847. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  13848. }
  13849. }
  13850. /*!
  13851. @brief exchanges the values
  13852. Exchanges the contents of a JSON object with those of @a other. Does not
  13853. invoke any move, copy, or swap operations on individual elements. All
  13854. iterators and references remain valid. The past-the-end iterator is
  13855. invalidated.
  13856. @param[in,out] other object to exchange the contents with
  13857. @throw type_error.310 when JSON value is not an object; example:
  13858. `"cannot use swap() with string"`
  13859. @complexity Constant.
  13860. @liveexample{The example below shows how objects can be swapped with
  13861. `swap()`.,swap__object_t}
  13862. @since version 1.0.0
  13863. */
  13864. void swap(object_t& other)
  13865. {
  13866. // swap only works for objects
  13867. if (JSON_LIKELY(is_object()))
  13868. {
  13869. std::swap(*(m_value.object), other);
  13870. }
  13871. else
  13872. {
  13873. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  13874. }
  13875. }
  13876. /*!
  13877. @brief exchanges the values
  13878. Exchanges the contents of a JSON string with those of @a other. Does not
  13879. invoke any move, copy, or swap operations on individual elements. All
  13880. iterators and references remain valid. The past-the-end iterator is
  13881. invalidated.
  13882. @param[in,out] other string to exchange the contents with
  13883. @throw type_error.310 when JSON value is not a string; example: `"cannot
  13884. use swap() with boolean"`
  13885. @complexity Constant.
  13886. @liveexample{The example below shows how strings can be swapped with
  13887. `swap()`.,swap__string_t}
  13888. @since version 1.0.0
  13889. */
  13890. void swap(string_t& other)
  13891. {
  13892. // swap only works for strings
  13893. if (JSON_LIKELY(is_string()))
  13894. {
  13895. std::swap(*(m_value.string), other);
  13896. }
  13897. else
  13898. {
  13899. JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
  13900. }
  13901. }
  13902. /// @}
  13903. public:
  13904. //////////////////////////////////////////
  13905. // lexicographical comparison operators //
  13906. //////////////////////////////////////////
  13907. /// @name lexicographical comparison operators
  13908. /// @{
  13909. /*!
  13910. @brief comparison: equal
  13911. Compares two JSON values for equality according to the following rules:
  13912. - Two JSON values are equal if (1) they are from the same type and (2)
  13913. their stored values are the same according to their respective
  13914. `operator==`.
  13915. - Integer and floating-point numbers are automatically converted before
  13916. comparison. Note than two NaN values are always treated as unequal.
  13917. - Two JSON null values are equal.
  13918. @note Floating-point inside JSON values numbers are compared with
  13919. `json::number_float_t::operator==` which is `double::operator==` by
  13920. default. To compare floating-point while respecting an epsilon, an alternative
  13921. [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
  13922. could be used, for instance
  13923. @code {.cpp}
  13924. template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
  13925. inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
  13926. {
  13927. return std::abs(a - b) <= epsilon;
  13928. }
  13929. @endcode
  13930. @note NaN values never compare equal to themselves or to other NaN values.
  13931. @param[in] lhs first JSON value to consider
  13932. @param[in] rhs second JSON value to consider
  13933. @return whether the values @a lhs and @a rhs are equal
  13934. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  13935. @complexity Linear.
  13936. @liveexample{The example demonstrates comparing several JSON
  13937. types.,operator__equal}
  13938. @since version 1.0.0
  13939. */
  13940. friend bool operator==(const_reference lhs, const_reference rhs) noexcept
  13941. {
  13942. const auto lhs_type = lhs.type();
  13943. const auto rhs_type = rhs.type();
  13944. if (lhs_type == rhs_type)
  13945. {
  13946. switch (lhs_type)
  13947. {
  13948. case value_t::array:
  13949. return (*lhs.m_value.array == *rhs.m_value.array);
  13950. case value_t::object:
  13951. return (*lhs.m_value.object == *rhs.m_value.object);
  13952. case value_t::null:
  13953. return true;
  13954. case value_t::string:
  13955. return (*lhs.m_value.string == *rhs.m_value.string);
  13956. case value_t::boolean:
  13957. return (lhs.m_value.boolean == rhs.m_value.boolean);
  13958. case value_t::number_integer:
  13959. return (lhs.m_value.number_integer == rhs.m_value.number_integer);
  13960. case value_t::number_unsigned:
  13961. return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);
  13962. case value_t::number_float:
  13963. return (lhs.m_value.number_float == rhs.m_value.number_float);
  13964. default:
  13965. return false;
  13966. }
  13967. }
  13968. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  13969. {
  13970. return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);
  13971. }
  13972. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  13973. {
  13974. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));
  13975. }
  13976. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  13977. {
  13978. return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);
  13979. }
  13980. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  13981. {
  13982. return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));
  13983. }
  13984. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  13985. {
  13986. return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);
  13987. }
  13988. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  13989. {
  13990. return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));
  13991. }
  13992. return false;
  13993. }
  13994. /*!
  13995. @brief comparison: equal
  13996. @copydoc operator==(const_reference, const_reference)
  13997. */
  13998. template<typename ScalarType, typename std::enable_if<
  13999. std::is_scalar<ScalarType>::value, int>::type = 0>
  14000. friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
  14001. {
  14002. return (lhs == basic_json(rhs));
  14003. }
  14004. /*!
  14005. @brief comparison: equal
  14006. @copydoc operator==(const_reference, const_reference)
  14007. */
  14008. template<typename ScalarType, typename std::enable_if<
  14009. std::is_scalar<ScalarType>::value, int>::type = 0>
  14010. friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
  14011. {
  14012. return (basic_json(lhs) == rhs);
  14013. }
  14014. /*!
  14015. @brief comparison: not equal
  14016. Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
  14017. @param[in] lhs first JSON value to consider
  14018. @param[in] rhs second JSON value to consider
  14019. @return whether the values @a lhs and @a rhs are not equal
  14020. @complexity Linear.
  14021. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14022. @liveexample{The example demonstrates comparing several JSON
  14023. types.,operator__notequal}
  14024. @since version 1.0.0
  14025. */
  14026. friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
  14027. {
  14028. return not (lhs == rhs);
  14029. }
  14030. /*!
  14031. @brief comparison: not equal
  14032. @copydoc operator!=(const_reference, const_reference)
  14033. */
  14034. template<typename ScalarType, typename std::enable_if<
  14035. std::is_scalar<ScalarType>::value, int>::type = 0>
  14036. friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
  14037. {
  14038. return (lhs != basic_json(rhs));
  14039. }
  14040. /*!
  14041. @brief comparison: not equal
  14042. @copydoc operator!=(const_reference, const_reference)
  14043. */
  14044. template<typename ScalarType, typename std::enable_if<
  14045. std::is_scalar<ScalarType>::value, int>::type = 0>
  14046. friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
  14047. {
  14048. return (basic_json(lhs) != rhs);
  14049. }
  14050. /*!
  14051. @brief comparison: less than
  14052. Compares whether one JSON value @a lhs is less than another JSON value @a
  14053. rhs according to the following rules:
  14054. - If @a lhs and @a rhs have the same type, the values are compared using
  14055. the default `<` operator.
  14056. - Integer and floating-point numbers are automatically converted before
  14057. comparison
  14058. - In case @a lhs and @a rhs have different types, the values are ignored
  14059. and the order of the types is considered, see
  14060. @ref operator<(const value_t, const value_t).
  14061. @param[in] lhs first JSON value to consider
  14062. @param[in] rhs second JSON value to consider
  14063. @return whether @a lhs is less than @a rhs
  14064. @complexity Linear.
  14065. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14066. @liveexample{The example demonstrates comparing several JSON
  14067. types.,operator__less}
  14068. @since version 1.0.0
  14069. */
  14070. friend bool operator<(const_reference lhs, const_reference rhs) noexcept
  14071. {
  14072. const auto lhs_type = lhs.type();
  14073. const auto rhs_type = rhs.type();
  14074. if (lhs_type == rhs_type)
  14075. {
  14076. switch (lhs_type)
  14077. {
  14078. case value_t::array:
  14079. return (*lhs.m_value.array) < (*rhs.m_value.array);
  14080. case value_t::object:
  14081. return *lhs.m_value.object < *rhs.m_value.object;
  14082. case value_t::null:
  14083. return false;
  14084. case value_t::string:
  14085. return *lhs.m_value.string < *rhs.m_value.string;
  14086. case value_t::boolean:
  14087. return lhs.m_value.boolean < rhs.m_value.boolean;
  14088. case value_t::number_integer:
  14089. return lhs.m_value.number_integer < rhs.m_value.number_integer;
  14090. case value_t::number_unsigned:
  14091. return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
  14092. case value_t::number_float:
  14093. return lhs.m_value.number_float < rhs.m_value.number_float;
  14094. default:
  14095. return false;
  14096. }
  14097. }
  14098. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
  14099. {
  14100. return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
  14101. }
  14102. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
  14103. {
  14104. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
  14105. }
  14106. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
  14107. {
  14108. return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
  14109. }
  14110. else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
  14111. {
  14112. return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
  14113. }
  14114. else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
  14115. {
  14116. return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
  14117. }
  14118. else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
  14119. {
  14120. return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
  14121. }
  14122. // We only reach this line if we cannot compare values. In that case,
  14123. // we compare types. Note we have to call the operator explicitly,
  14124. // because MSVC has problems otherwise.
  14125. return operator<(lhs_type, rhs_type);
  14126. }
  14127. /*!
  14128. @brief comparison: less than
  14129. @copydoc operator<(const_reference, const_reference)
  14130. */
  14131. template<typename ScalarType, typename std::enable_if<
  14132. std::is_scalar<ScalarType>::value, int>::type = 0>
  14133. friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
  14134. {
  14135. return (lhs < basic_json(rhs));
  14136. }
  14137. /*!
  14138. @brief comparison: less than
  14139. @copydoc operator<(const_reference, const_reference)
  14140. */
  14141. template<typename ScalarType, typename std::enable_if<
  14142. std::is_scalar<ScalarType>::value, int>::type = 0>
  14143. friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
  14144. {
  14145. return (basic_json(lhs) < rhs);
  14146. }
  14147. /*!
  14148. @brief comparison: less than or equal
  14149. Compares whether one JSON value @a lhs is less than or equal to another
  14150. JSON value by calculating `not (rhs < lhs)`.
  14151. @param[in] lhs first JSON value to consider
  14152. @param[in] rhs second JSON value to consider
  14153. @return whether @a lhs is less than or equal to @a rhs
  14154. @complexity Linear.
  14155. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14156. @liveexample{The example demonstrates comparing several JSON
  14157. types.,operator__greater}
  14158. @since version 1.0.0
  14159. */
  14160. friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
  14161. {
  14162. return not (rhs < lhs);
  14163. }
  14164. /*!
  14165. @brief comparison: less than or equal
  14166. @copydoc operator<=(const_reference, const_reference)
  14167. */
  14168. template<typename ScalarType, typename std::enable_if<
  14169. std::is_scalar<ScalarType>::value, int>::type = 0>
  14170. friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
  14171. {
  14172. return (lhs <= basic_json(rhs));
  14173. }
  14174. /*!
  14175. @brief comparison: less than or equal
  14176. @copydoc operator<=(const_reference, const_reference)
  14177. */
  14178. template<typename ScalarType, typename std::enable_if<
  14179. std::is_scalar<ScalarType>::value, int>::type = 0>
  14180. friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
  14181. {
  14182. return (basic_json(lhs) <= rhs);
  14183. }
  14184. /*!
  14185. @brief comparison: greater than
  14186. Compares whether one JSON value @a lhs is greater than another
  14187. JSON value by calculating `not (lhs <= rhs)`.
  14188. @param[in] lhs first JSON value to consider
  14189. @param[in] rhs second JSON value to consider
  14190. @return whether @a lhs is greater than to @a rhs
  14191. @complexity Linear.
  14192. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14193. @liveexample{The example demonstrates comparing several JSON
  14194. types.,operator__lessequal}
  14195. @since version 1.0.0
  14196. */
  14197. friend bool operator>(const_reference lhs, const_reference rhs) noexcept
  14198. {
  14199. return not (lhs <= rhs);
  14200. }
  14201. /*!
  14202. @brief comparison: greater than
  14203. @copydoc operator>(const_reference, const_reference)
  14204. */
  14205. template<typename ScalarType, typename std::enable_if<
  14206. std::is_scalar<ScalarType>::value, int>::type = 0>
  14207. friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
  14208. {
  14209. return (lhs > basic_json(rhs));
  14210. }
  14211. /*!
  14212. @brief comparison: greater than
  14213. @copydoc operator>(const_reference, const_reference)
  14214. */
  14215. template<typename ScalarType, typename std::enable_if<
  14216. std::is_scalar<ScalarType>::value, int>::type = 0>
  14217. friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
  14218. {
  14219. return (basic_json(lhs) > rhs);
  14220. }
  14221. /*!
  14222. @brief comparison: greater than or equal
  14223. Compares whether one JSON value @a lhs is greater than or equal to another
  14224. JSON value by calculating `not (lhs < rhs)`.
  14225. @param[in] lhs first JSON value to consider
  14226. @param[in] rhs second JSON value to consider
  14227. @return whether @a lhs is greater than or equal to @a rhs
  14228. @complexity Linear.
  14229. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14230. @liveexample{The example demonstrates comparing several JSON
  14231. types.,operator__greaterequal}
  14232. @since version 1.0.0
  14233. */
  14234. friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
  14235. {
  14236. return not (lhs < rhs);
  14237. }
  14238. /*!
  14239. @brief comparison: greater than or equal
  14240. @copydoc operator>=(const_reference, const_reference)
  14241. */
  14242. template<typename ScalarType, typename std::enable_if<
  14243. std::is_scalar<ScalarType>::value, int>::type = 0>
  14244. friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
  14245. {
  14246. return (lhs >= basic_json(rhs));
  14247. }
  14248. /*!
  14249. @brief comparison: greater than or equal
  14250. @copydoc operator>=(const_reference, const_reference)
  14251. */
  14252. template<typename ScalarType, typename std::enable_if<
  14253. std::is_scalar<ScalarType>::value, int>::type = 0>
  14254. friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
  14255. {
  14256. return (basic_json(lhs) >= rhs);
  14257. }
  14258. /// @}
  14259. ///////////////////
  14260. // serialization //
  14261. ///////////////////
  14262. /// @name serialization
  14263. /// @{
  14264. /*!
  14265. @brief serialize to stream
  14266. Serialize the given JSON value @a j to the output stream @a o. The JSON
  14267. value will be serialized using the @ref dump member function.
  14268. - The indentation of the output can be controlled with the member variable
  14269. `width` of the output stream @a o. For instance, using the manipulator
  14270. `std::setw(4)` on @a o sets the indentation level to `4` and the
  14271. serialization result is the same as calling `dump(4)`.
  14272. - The indentation character can be controlled with the member variable
  14273. `fill` of the output stream @a o. For instance, the manipulator
  14274. `std::setfill('\\t')` sets indentation to use a tab character rather than
  14275. the default space character.
  14276. @param[in,out] o stream to serialize to
  14277. @param[in] j JSON value to serialize
  14278. @return the stream @a o
  14279. @throw type_error.316 if a string stored inside the JSON value is not
  14280. UTF-8 encoded
  14281. @complexity Linear.
  14282. @liveexample{The example below shows the serialization with different
  14283. parameters to `width` to adjust the indentation level.,operator_serialize}
  14284. @since version 1.0.0; indentation character added in version 3.0.0
  14285. */
  14286. friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
  14287. {
  14288. // read width member and use it as indentation parameter if nonzero
  14289. const bool pretty_print = (o.width() > 0);
  14290. const auto indentation = (pretty_print ? o.width() : 0);
  14291. // reset width to 0 for subsequent calls to this stream
  14292. o.width(0);
  14293. // do the actual serialization
  14294. serializer s(detail::output_adapter<char>(o), o.fill());
  14295. s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
  14296. return o;
  14297. }
  14298. /*!
  14299. @brief serialize to stream
  14300. @deprecated This stream operator is deprecated and will be removed in
  14301. future 4.0.0 of the library. Please use
  14302. @ref operator<<(std::ostream&, const basic_json&)
  14303. instead; that is, replace calls like `j >> o;` with `o << j;`.
  14304. @since version 1.0.0; deprecated since version 3.0.0
  14305. */
  14306. JSON_DEPRECATED
  14307. friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
  14308. {
  14309. return o << j;
  14310. }
  14311. /// @}
  14312. /////////////////////
  14313. // deserialization //
  14314. /////////////////////
  14315. /// @name deserialization
  14316. /// @{
  14317. /*!
  14318. @brief deserialize from a compatible input
  14319. This function reads from a compatible input. Examples are:
  14320. - an array of 1-byte values
  14321. - strings with character/literal type with size of 1 byte
  14322. - input streams
  14323. - container with contiguous storage of 1-byte values. Compatible container
  14324. types include `std::vector`, `std::string`, `std::array`,
  14325. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  14326. arrays can be used with `std::begin()`/`std::end()`. User-defined
  14327. containers can be used as long as they implement random-access iterators
  14328. and a contiguous storage.
  14329. @pre Each element of the container has a size of 1 byte. Violating this
  14330. precondition yields undefined behavior. **This precondition is enforced
  14331. with a static assertion.**
  14332. @pre The container storage is contiguous. Violating this precondition
  14333. yields undefined behavior. **This precondition is enforced with an
  14334. assertion.**
  14335. @pre Each element of the container has a size of 1 byte. Violating this
  14336. precondition yields undefined behavior. **This precondition is enforced
  14337. with a static assertion.**
  14338. @warning There is no way to enforce all preconditions at compile-time. If
  14339. the function is called with a noncompliant container and with
  14340. assertions switched off, the behavior is undefined and will most
  14341. likely yield segmentation violation.
  14342. @param[in] i input to read from
  14343. @param[in] cb a parser callback function of type @ref parser_callback_t
  14344. which is used to control the deserialization by filtering unwanted values
  14345. (optional)
  14346. @return result of the deserialization
  14347. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  14348. of input; expected string literal""`
  14349. @throw parse_error.102 if to_unicode fails or surrogate error
  14350. @throw parse_error.103 if to_unicode fails
  14351. @complexity Linear in the length of the input. The parser is a predictive
  14352. LL(1) parser. The complexity can be higher if the parser callback function
  14353. @a cb has a super-linear complexity.
  14354. @note A UTF-8 byte order mark is silently ignored.
  14355. @liveexample{The example below demonstrates the `parse()` function reading
  14356. from an array.,parse__array__parser_callback_t}
  14357. @liveexample{The example below demonstrates the `parse()` function with
  14358. and without callback function.,parse__string__parser_callback_t}
  14359. @liveexample{The example below demonstrates the `parse()` function with
  14360. and without callback function.,parse__istream__parser_callback_t}
  14361. @liveexample{The example below demonstrates the `parse()` function reading
  14362. from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
  14363. @since version 2.0.3 (contiguous containers)
  14364. */
  14365. static basic_json parse(detail::input_adapter&& i,
  14366. const parser_callback_t cb = nullptr,
  14367. const bool allow_exceptions = true)
  14368. {
  14369. basic_json result;
  14370. parser(i, cb, allow_exceptions).parse(true, result);
  14371. return result;
  14372. }
  14373. static bool accept(detail::input_adapter&& i)
  14374. {
  14375. return parser(i).accept(true);
  14376. }
  14377. /*!
  14378. @brief generate SAX events
  14379. The SAX event lister must follow the interface of @ref json_sax.
  14380. This function reads from a compatible input. Examples are:
  14381. - an array of 1-byte values
  14382. - strings with character/literal type with size of 1 byte
  14383. - input streams
  14384. - container with contiguous storage of 1-byte values. Compatible container
  14385. types include `std::vector`, `std::string`, `std::array`,
  14386. `std::valarray`, and `std::initializer_list`. Furthermore, C-style
  14387. arrays can be used with `std::begin()`/`std::end()`. User-defined
  14388. containers can be used as long as they implement random-access iterators
  14389. and a contiguous storage.
  14390. @pre Each element of the container has a size of 1 byte. Violating this
  14391. precondition yields undefined behavior. **This precondition is enforced
  14392. with a static assertion.**
  14393. @pre The container storage is contiguous. Violating this precondition
  14394. yields undefined behavior. **This precondition is enforced with an
  14395. assertion.**
  14396. @pre Each element of the container has a size of 1 byte. Violating this
  14397. precondition yields undefined behavior. **This precondition is enforced
  14398. with a static assertion.**
  14399. @warning There is no way to enforce all preconditions at compile-time. If
  14400. the function is called with a noncompliant container and with
  14401. assertions switched off, the behavior is undefined and will most
  14402. likely yield segmentation violation.
  14403. @param[in] i input to read from
  14404. @param[in,out] sax SAX event listener
  14405. @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
  14406. @param[in] strict whether the input has to be consumed completely
  14407. @return return value of the last processed SAX event
  14408. @throw parse_error.101 if a parse error occurs; example: `""unexpected end
  14409. of input; expected string literal""`
  14410. @throw parse_error.102 if to_unicode fails or surrogate error
  14411. @throw parse_error.103 if to_unicode fails
  14412. @complexity Linear in the length of the input. The parser is a predictive
  14413. LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
  14414. a super-linear complexity.
  14415. @note A UTF-8 byte order mark is silently ignored.
  14416. @liveexample{The example below demonstrates the `sax_parse()` function
  14417. reading from string and processing the events with a user-defined SAX
  14418. event consumer.,sax_parse}
  14419. @since version 3.2.0
  14420. */
  14421. template <typename SAX>
  14422. static bool sax_parse(detail::input_adapter&& i, SAX* sax,
  14423. input_format_t format = input_format_t::json,
  14424. const bool strict = true)
  14425. {
  14426. assert(sax);
  14427. switch (format)
  14428. {
  14429. case input_format_t::json:
  14430. return parser(std::move(i)).sax_parse(sax, strict);
  14431. default:
  14432. return detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
  14433. }
  14434. }
  14435. /*!
  14436. @brief deserialize from an iterator range with contiguous storage
  14437. This function reads from an iterator range of a container with contiguous
  14438. storage of 1-byte values. Compatible container types include
  14439. `std::vector`, `std::string`, `std::array`, `std::valarray`, and
  14440. `std::initializer_list`. Furthermore, C-style arrays can be used with
  14441. `std::begin()`/`std::end()`. User-defined containers can be used as long
  14442. as they implement random-access iterators and a contiguous storage.
  14443. @pre The iterator range is contiguous. Violating this precondition yields
  14444. undefined behavior. **This precondition is enforced with an assertion.**
  14445. @pre Each element in the range has a size of 1 byte. Violating this
  14446. precondition yields undefined behavior. **This precondition is enforced
  14447. with a static assertion.**
  14448. @warning There is no way to enforce all preconditions at compile-time. If
  14449. the function is called with noncompliant iterators and with
  14450. assertions switched off, the behavior is undefined and will most
  14451. likely yield segmentation violation.
  14452. @tparam IteratorType iterator of container with contiguous storage
  14453. @param[in] first begin of the range to parse (included)
  14454. @param[in] last end of the range to parse (excluded)
  14455. @param[in] cb a parser callback function of type @ref parser_callback_t
  14456. which is used to control the deserialization by filtering unwanted values
  14457. (optional)
  14458. @param[in] allow_exceptions whether to throw exceptions in case of a
  14459. parse error (optional, true by default)
  14460. @return result of the deserialization
  14461. @throw parse_error.101 in case of an unexpected token
  14462. @throw parse_error.102 if to_unicode fails or surrogate error
  14463. @throw parse_error.103 if to_unicode fails
  14464. @complexity Linear in the length of the input. The parser is a predictive
  14465. LL(1) parser. The complexity can be higher if the parser callback function
  14466. @a cb has a super-linear complexity.
  14467. @note A UTF-8 byte order mark is silently ignored.
  14468. @liveexample{The example below demonstrates the `parse()` function reading
  14469. from an iterator range.,parse__iteratortype__parser_callback_t}
  14470. @since version 2.0.3
  14471. */
  14472. template<class IteratorType, typename std::enable_if<
  14473. std::is_base_of<
  14474. std::random_access_iterator_tag,
  14475. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  14476. static basic_json parse(IteratorType first, IteratorType last,
  14477. const parser_callback_t cb = nullptr,
  14478. const bool allow_exceptions = true)
  14479. {
  14480. basic_json result;
  14481. parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
  14482. return result;
  14483. }
  14484. template<class IteratorType, typename std::enable_if<
  14485. std::is_base_of<
  14486. std::random_access_iterator_tag,
  14487. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  14488. static bool accept(IteratorType first, IteratorType last)
  14489. {
  14490. return parser(detail::input_adapter(first, last)).accept(true);
  14491. }
  14492. template<class IteratorType, class SAX, typename std::enable_if<
  14493. std::is_base_of<
  14494. std::random_access_iterator_tag,
  14495. typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
  14496. static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
  14497. {
  14498. return parser(detail::input_adapter(first, last)).sax_parse(sax);
  14499. }
  14500. /*!
  14501. @brief deserialize from stream
  14502. @deprecated This stream operator is deprecated and will be removed in
  14503. version 4.0.0 of the library. Please use
  14504. @ref operator>>(std::istream&, basic_json&)
  14505. instead; that is, replace calls like `j << i;` with `i >> j;`.
  14506. @since version 1.0.0; deprecated since version 3.0.0
  14507. */
  14508. JSON_DEPRECATED
  14509. friend std::istream& operator<<(basic_json& j, std::istream& i)
  14510. {
  14511. return operator>>(i, j);
  14512. }
  14513. /*!
  14514. @brief deserialize from stream
  14515. Deserializes an input stream to a JSON value.
  14516. @param[in,out] i input stream to read a serialized JSON value from
  14517. @param[in,out] j JSON value to write the deserialized input to
  14518. @throw parse_error.101 in case of an unexpected token
  14519. @throw parse_error.102 if to_unicode fails or surrogate error
  14520. @throw parse_error.103 if to_unicode fails
  14521. @complexity Linear in the length of the input. The parser is a predictive
  14522. LL(1) parser.
  14523. @note A UTF-8 byte order mark is silently ignored.
  14524. @liveexample{The example below shows how a JSON value is constructed by
  14525. reading a serialization from a stream.,operator_deserialize}
  14526. @sa parse(std::istream&, const parser_callback_t) for a variant with a
  14527. parser callback function to filter values while parsing
  14528. @since version 1.0.0
  14529. */
  14530. friend std::istream& operator>>(std::istream& i, basic_json& j)
  14531. {
  14532. parser(detail::input_adapter(i)).parse(false, j);
  14533. return i;
  14534. }
  14535. /// @}
  14536. ///////////////////////////
  14537. // convenience functions //
  14538. ///////////////////////////
  14539. /*!
  14540. @brief return the type as string
  14541. Returns the type name as string to be used in error messages - usually to
  14542. indicate that a function was called on a wrong JSON type.
  14543. @return a string representation of a the @a m_type member:
  14544. Value type | return value
  14545. ----------- | -------------
  14546. null | `"null"`
  14547. boolean | `"boolean"`
  14548. string | `"string"`
  14549. number | `"number"` (for all number types)
  14550. object | `"object"`
  14551. array | `"array"`
  14552. discarded | `"discarded"`
  14553. @exceptionsafety No-throw guarantee: this function never throws exceptions.
  14554. @complexity Constant.
  14555. @liveexample{The following code exemplifies `type_name()` for all JSON
  14556. types.,type_name}
  14557. @sa @ref type() -- return the type of the JSON value
  14558. @sa @ref operator value_t() -- return the type of the JSON value (implicit)
  14559. @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
  14560. since 3.0.0
  14561. */
  14562. const char* type_name() const noexcept
  14563. {
  14564. {
  14565. switch (m_type)
  14566. {
  14567. case value_t::null:
  14568. return "null";
  14569. case value_t::object:
  14570. return "object";
  14571. case value_t::array:
  14572. return "array";
  14573. case value_t::string:
  14574. return "string";
  14575. case value_t::boolean:
  14576. return "boolean";
  14577. case value_t::discarded:
  14578. return "discarded";
  14579. default:
  14580. return "number";
  14581. }
  14582. }
  14583. }
  14584. private:
  14585. //////////////////////
  14586. // member variables //
  14587. //////////////////////
  14588. /// the type of the current element
  14589. value_t m_type = value_t::null;
  14590. /// the value of the current element
  14591. json_value m_value = {};
  14592. //////////////////////////////////////////
  14593. // binary serialization/deserialization //
  14594. //////////////////////////////////////////
  14595. /// @name binary serialization/deserialization support
  14596. /// @{
  14597. public:
  14598. /*!
  14599. @brief create a CBOR serialization of a given JSON value
  14600. Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
  14601. Binary Object Representation) serialization format. CBOR is a binary
  14602. serialization format which aims to be more compact than JSON itself, yet
  14603. more efficient to parse.
  14604. The library uses the following mapping from JSON values types to
  14605. CBOR types according to the CBOR specification (RFC 7049):
  14606. JSON value type | value/range | CBOR type | first byte
  14607. --------------- | ------------------------------------------ | ---------------------------------- | ---------------
  14608. null | `null` | Null | 0xF6
  14609. boolean | `true` | True | 0xF5
  14610. boolean | `false` | False | 0xF4
  14611. number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
  14612. number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
  14613. number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
  14614. number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
  14615. number_integer | -24..-1 | Negative integer | 0x20..0x37
  14616. number_integer | 0..23 | Integer | 0x00..0x17
  14617. number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
  14618. number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  14619. number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  14620. number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  14621. number_unsigned | 0..23 | Integer | 0x00..0x17
  14622. number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
  14623. number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
  14624. number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
  14625. number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
  14626. number_float | *any value* | Double-Precision Float | 0xFB
  14627. string | *length*: 0..23 | UTF-8 string | 0x60..0x77
  14628. string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
  14629. string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
  14630. string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
  14631. string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
  14632. array | *size*: 0..23 | array | 0x80..0x97
  14633. array | *size*: 23..255 | array (1 byte follow) | 0x98
  14634. array | *size*: 256..65535 | array (2 bytes follow) | 0x99
  14635. array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
  14636. array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
  14637. object | *size*: 0..23 | map | 0xA0..0xB7
  14638. object | *size*: 23..255 | map (1 byte follow) | 0xB8
  14639. object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
  14640. object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
  14641. object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
  14642. @note The mapping is **complete** in the sense that any JSON value type
  14643. can be converted to a CBOR value.
  14644. @note If NaN or Infinity are stored inside a JSON number, they are
  14645. serialized properly. This behavior differs from the @ref dump()
  14646. function which serializes NaN or Infinity to `null`.
  14647. @note The following CBOR types are not used in the conversion:
  14648. - byte strings (0x40..0x5F)
  14649. - UTF-8 strings terminated by "break" (0x7F)
  14650. - arrays terminated by "break" (0x9F)
  14651. - maps terminated by "break" (0xBF)
  14652. - date/time (0xC0..0xC1)
  14653. - bignum (0xC2..0xC3)
  14654. - decimal fraction (0xC4)
  14655. - bigfloat (0xC5)
  14656. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  14657. - expected conversions (0xD5..0xD7)
  14658. - simple values (0xE0..0xF3, 0xF8)
  14659. - undefined (0xF7)
  14660. - half and single-precision floats (0xF9-0xFA)
  14661. - break (0xFF)
  14662. @param[in] j JSON value to serialize
  14663. @return MessagePack serialization as byte vector
  14664. @complexity Linear in the size of the JSON value @a j.
  14665. @liveexample{The example shows the serialization of a JSON value to a byte
  14666. vector in CBOR format.,to_cbor}
  14667. @sa http://cbor.io
  14668. @sa @ref from_cbor(detail::input_adapter, const bool strict) for the
  14669. analogous deserialization
  14670. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  14671. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  14672. related UBJSON format
  14673. @since version 2.0.9
  14674. */
  14675. static std::vector<uint8_t> to_cbor(const basic_json& j)
  14676. {
  14677. std::vector<uint8_t> result;
  14678. to_cbor(j, result);
  14679. return result;
  14680. }
  14681. static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
  14682. {
  14683. binary_writer<uint8_t>(o).write_cbor(j);
  14684. }
  14685. static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
  14686. {
  14687. binary_writer<char>(o).write_cbor(j);
  14688. }
  14689. /*!
  14690. @brief create a MessagePack serialization of a given JSON value
  14691. Serializes a given JSON value @a j to a byte vector using the MessagePack
  14692. serialization format. MessagePack is a binary serialization format which
  14693. aims to be more compact than JSON itself, yet more efficient to parse.
  14694. The library uses the following mapping from JSON values types to
  14695. MessagePack types according to the MessagePack specification:
  14696. JSON value type | value/range | MessagePack type | first byte
  14697. --------------- | --------------------------------- | ---------------- | ----------
  14698. null | `null` | nil | 0xC0
  14699. boolean | `true` | true | 0xC3
  14700. boolean | `false` | false | 0xC2
  14701. number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
  14702. number_integer | -2147483648..-32769 | int32 | 0xD2
  14703. number_integer | -32768..-129 | int16 | 0xD1
  14704. number_integer | -128..-33 | int8 | 0xD0
  14705. number_integer | -32..-1 | negative fixint | 0xE0..0xFF
  14706. number_integer | 0..127 | positive fixint | 0x00..0x7F
  14707. number_integer | 128..255 | uint 8 | 0xCC
  14708. number_integer | 256..65535 | uint 16 | 0xCD
  14709. number_integer | 65536..4294967295 | uint 32 | 0xCE
  14710. number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
  14711. number_unsigned | 0..127 | positive fixint | 0x00..0x7F
  14712. number_unsigned | 128..255 | uint 8 | 0xCC
  14713. number_unsigned | 256..65535 | uint 16 | 0xCD
  14714. number_unsigned | 65536..4294967295 | uint 32 | 0xCE
  14715. number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
  14716. number_float | *any value* | float 64 | 0xCB
  14717. string | *length*: 0..31 | fixstr | 0xA0..0xBF
  14718. string | *length*: 32..255 | str 8 | 0xD9
  14719. string | *length*: 256..65535 | str 16 | 0xDA
  14720. string | *length*: 65536..4294967295 | str 32 | 0xDB
  14721. array | *size*: 0..15 | fixarray | 0x90..0x9F
  14722. array | *size*: 16..65535 | array 16 | 0xDC
  14723. array | *size*: 65536..4294967295 | array 32 | 0xDD
  14724. object | *size*: 0..15 | fix map | 0x80..0x8F
  14725. object | *size*: 16..65535 | map 16 | 0xDE
  14726. object | *size*: 65536..4294967295 | map 32 | 0xDF
  14727. @note The mapping is **complete** in the sense that any JSON value type
  14728. can be converted to a MessagePack value.
  14729. @note The following values can **not** be converted to a MessagePack value:
  14730. - strings with more than 4294967295 bytes
  14731. - arrays with more than 4294967295 elements
  14732. - objects with more than 4294967295 elements
  14733. @note The following MessagePack types are not used in the conversion:
  14734. - bin 8 - bin 32 (0xC4..0xC6)
  14735. - ext 8 - ext 32 (0xC7..0xC9)
  14736. - float 32 (0xCA)
  14737. - fixext 1 - fixext 16 (0xD4..0xD8)
  14738. @note Any MessagePack output created @ref to_msgpack can be successfully
  14739. parsed by @ref from_msgpack.
  14740. @note If NaN or Infinity are stored inside a JSON number, they are
  14741. serialized properly. This behavior differs from the @ref dump()
  14742. function which serializes NaN or Infinity to `null`.
  14743. @param[in] j JSON value to serialize
  14744. @return MessagePack serialization as byte vector
  14745. @complexity Linear in the size of the JSON value @a j.
  14746. @liveexample{The example shows the serialization of a JSON value to a byte
  14747. vector in MessagePack format.,to_msgpack}
  14748. @sa http://msgpack.org
  14749. @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
  14750. analogous deserialization
  14751. @sa @ref to_cbor(const basic_json& for the related CBOR format
  14752. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  14753. related UBJSON format
  14754. @since version 2.0.9
  14755. */
  14756. static std::vector<uint8_t> to_msgpack(const basic_json& j)
  14757. {
  14758. std::vector<uint8_t> result;
  14759. to_msgpack(j, result);
  14760. return result;
  14761. }
  14762. static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
  14763. {
  14764. binary_writer<uint8_t>(o).write_msgpack(j);
  14765. }
  14766. static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
  14767. {
  14768. binary_writer<char>(o).write_msgpack(j);
  14769. }
  14770. /*!
  14771. @brief create a UBJSON serialization of a given JSON value
  14772. Serializes a given JSON value @a j to a byte vector using the UBJSON
  14773. (Universal Binary JSON) serialization format. UBJSON aims to be more compact
  14774. than JSON itself, yet more efficient to parse.
  14775. The library uses the following mapping from JSON values types to
  14776. UBJSON types according to the UBJSON specification:
  14777. JSON value type | value/range | UBJSON type | marker
  14778. --------------- | --------------------------------- | ----------- | ------
  14779. null | `null` | null | `Z`
  14780. boolean | `true` | true | `T`
  14781. boolean | `false` | false | `F`
  14782. number_integer | -9223372036854775808..-2147483649 | int64 | `L`
  14783. number_integer | -2147483648..-32769 | int32 | `l`
  14784. number_integer | -32768..-129 | int16 | `I`
  14785. number_integer | -128..127 | int8 | `i`
  14786. number_integer | 128..255 | uint8 | `U`
  14787. number_integer | 256..32767 | int16 | `I`
  14788. number_integer | 32768..2147483647 | int32 | `l`
  14789. number_integer | 2147483648..9223372036854775807 | int64 | `L`
  14790. number_unsigned | 0..127 | int8 | `i`
  14791. number_unsigned | 128..255 | uint8 | `U`
  14792. number_unsigned | 256..32767 | int16 | `I`
  14793. number_unsigned | 32768..2147483647 | int32 | `l`
  14794. number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
  14795. number_float | *any value* | float64 | `D`
  14796. string | *with shortest length indicator* | string | `S`
  14797. array | *see notes on optimized format* | array | `[`
  14798. object | *see notes on optimized format* | map | `{`
  14799. @note The mapping is **complete** in the sense that any JSON value type
  14800. can be converted to a UBJSON value.
  14801. @note The following values can **not** be converted to a UBJSON value:
  14802. - strings with more than 9223372036854775807 bytes (theoretical)
  14803. - unsigned integer numbers above 9223372036854775807
  14804. @note The following markers are not used in the conversion:
  14805. - `Z`: no-op values are not created.
  14806. - `C`: single-byte strings are serialized with `S` markers.
  14807. @note Any UBJSON output created @ref to_ubjson can be successfully parsed
  14808. by @ref from_ubjson.
  14809. @note If NaN or Infinity are stored inside a JSON number, they are
  14810. serialized properly. This behavior differs from the @ref dump()
  14811. function which serializes NaN or Infinity to `null`.
  14812. @note The optimized formats for containers are supported: Parameter
  14813. @a use_size adds size information to the beginning of a container and
  14814. removes the closing marker. Parameter @a use_type further checks
  14815. whether all elements of a container have the same type and adds the
  14816. type marker to the beginning of the container. The @a use_type
  14817. parameter must only be used together with @a use_size = true. Note
  14818. that @a use_size = true alone may result in larger representations -
  14819. the benefit of this parameter is that the receiving side is
  14820. immediately informed on the number of elements of the container.
  14821. @param[in] j JSON value to serialize
  14822. @param[in] use_size whether to add size annotations to container types
  14823. @param[in] use_type whether to add type annotations to container types
  14824. (must be combined with @a use_size = true)
  14825. @return UBJSON serialization as byte vector
  14826. @complexity Linear in the size of the JSON value @a j.
  14827. @liveexample{The example shows the serialization of a JSON value to a byte
  14828. vector in UBJSON format.,to_ubjson}
  14829. @sa http://ubjson.org
  14830. @sa @ref from_ubjson(detail::input_adapter, const bool strict) for the
  14831. analogous deserialization
  14832. @sa @ref to_cbor(const basic_json& for the related CBOR format
  14833. @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
  14834. @since version 3.1.0
  14835. */
  14836. static std::vector<uint8_t> to_ubjson(const basic_json& j,
  14837. const bool use_size = false,
  14838. const bool use_type = false)
  14839. {
  14840. std::vector<uint8_t> result;
  14841. to_ubjson(j, result, use_size, use_type);
  14842. return result;
  14843. }
  14844. static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
  14845. const bool use_size = false, const bool use_type = false)
  14846. {
  14847. binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
  14848. }
  14849. static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
  14850. const bool use_size = false, const bool use_type = false)
  14851. {
  14852. binary_writer<char>(o).write_ubjson(j, use_size, use_type);
  14853. }
  14854. /*!
  14855. @brief create a JSON value from an input in CBOR format
  14856. Deserializes a given input @a i to a JSON value using the CBOR (Concise
  14857. Binary Object Representation) serialization format.
  14858. The library maps CBOR types to JSON value types as follows:
  14859. CBOR type | JSON value type | first byte
  14860. ---------------------- | --------------- | ----------
  14861. Integer | number_unsigned | 0x00..0x17
  14862. Unsigned integer | number_unsigned | 0x18
  14863. Unsigned integer | number_unsigned | 0x19
  14864. Unsigned integer | number_unsigned | 0x1A
  14865. Unsigned integer | number_unsigned | 0x1B
  14866. Negative integer | number_integer | 0x20..0x37
  14867. Negative integer | number_integer | 0x38
  14868. Negative integer | number_integer | 0x39
  14869. Negative integer | number_integer | 0x3A
  14870. Negative integer | number_integer | 0x3B
  14871. Negative integer | number_integer | 0x40..0x57
  14872. UTF-8 string | string | 0x60..0x77
  14873. UTF-8 string | string | 0x78
  14874. UTF-8 string | string | 0x79
  14875. UTF-8 string | string | 0x7A
  14876. UTF-8 string | string | 0x7B
  14877. UTF-8 string | string | 0x7F
  14878. array | array | 0x80..0x97
  14879. array | array | 0x98
  14880. array | array | 0x99
  14881. array | array | 0x9A
  14882. array | array | 0x9B
  14883. array | array | 0x9F
  14884. map | object | 0xA0..0xB7
  14885. map | object | 0xB8
  14886. map | object | 0xB9
  14887. map | object | 0xBA
  14888. map | object | 0xBB
  14889. map | object | 0xBF
  14890. False | `false` | 0xF4
  14891. True | `true` | 0xF5
  14892. Nill | `null` | 0xF6
  14893. Half-Precision Float | number_float | 0xF9
  14894. Single-Precision Float | number_float | 0xFA
  14895. Double-Precision Float | number_float | 0xFB
  14896. @warning The mapping is **incomplete** in the sense that not all CBOR
  14897. types can be converted to a JSON value. The following CBOR types
  14898. are not supported and will yield parse errors (parse_error.112):
  14899. - byte strings (0x40..0x5F)
  14900. - date/time (0xC0..0xC1)
  14901. - bignum (0xC2..0xC3)
  14902. - decimal fraction (0xC4)
  14903. - bigfloat (0xC5)
  14904. - tagged items (0xC6..0xD4, 0xD8..0xDB)
  14905. - expected conversions (0xD5..0xD7)
  14906. - simple values (0xE0..0xF3, 0xF8)
  14907. - undefined (0xF7)
  14908. @warning CBOR allows map keys of any type, whereas JSON only allows
  14909. strings as keys in object values. Therefore, CBOR maps with keys
  14910. other than UTF-8 strings are rejected (parse_error.113).
  14911. @note Any CBOR output created @ref to_cbor can be successfully parsed by
  14912. @ref from_cbor.
  14913. @param[in] i an input in CBOR format convertible to an input adapter
  14914. @param[in] strict whether to expect the input to be consumed until EOF
  14915. (true by default)
  14916. @param[in] allow_exceptions whether to throw exceptions in case of a
  14917. parse error (optional, true by default)
  14918. @return deserialized JSON value
  14919. @throw parse_error.110 if the given input ends prematurely or the end of
  14920. file was not reached when @a strict was set to true
  14921. @throw parse_error.112 if unsupported features from CBOR were
  14922. used in the given input @a v or if the input is not valid CBOR
  14923. @throw parse_error.113 if a string was expected as map key, but not found
  14924. @complexity Linear in the size of the input @a i.
  14925. @liveexample{The example shows the deserialization of a byte vector in CBOR
  14926. format to a JSON value.,from_cbor}
  14927. @sa http://cbor.io
  14928. @sa @ref to_cbor(const basic_json&) for the analogous serialization
  14929. @sa @ref from_msgpack(detail::input_adapter, const bool, const bool) for the
  14930. related MessagePack format
  14931. @sa @ref from_ubjson(detail::input_adapter, const bool, const bool) for the
  14932. related UBJSON format
  14933. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  14934. consume input adapters, removed start_index parameter, and added
  14935. @a strict parameter since 3.0.0; added @allow_exceptions parameter
  14936. since 3.2.0
  14937. */
  14938. static basic_json from_cbor(detail::input_adapter&& i,
  14939. const bool strict = true,
  14940. const bool allow_exceptions = true)
  14941. {
  14942. basic_json result;
  14943. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  14944. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
  14945. return res ? result : basic_json(value_t::discarded);
  14946. }
  14947. /*!
  14948. @copydoc from_cbor(detail::input_adapter, const bool, const bool)
  14949. */
  14950. template<typename A1, typename A2,
  14951. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  14952. static basic_json from_cbor(A1 && a1, A2 && a2,
  14953. const bool strict = true,
  14954. const bool allow_exceptions = true)
  14955. {
  14956. basic_json result;
  14957. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  14958. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
  14959. return res ? result : basic_json(value_t::discarded);
  14960. }
  14961. /*!
  14962. @brief create a JSON value from an input in MessagePack format
  14963. Deserializes a given input @a i to a JSON value using the MessagePack
  14964. serialization format.
  14965. The library maps MessagePack types to JSON value types as follows:
  14966. MessagePack type | JSON value type | first byte
  14967. ---------------- | --------------- | ----------
  14968. positive fixint | number_unsigned | 0x00..0x7F
  14969. fixmap | object | 0x80..0x8F
  14970. fixarray | array | 0x90..0x9F
  14971. fixstr | string | 0xA0..0xBF
  14972. nil | `null` | 0xC0
  14973. false | `false` | 0xC2
  14974. true | `true` | 0xC3
  14975. float 32 | number_float | 0xCA
  14976. float 64 | number_float | 0xCB
  14977. uint 8 | number_unsigned | 0xCC
  14978. uint 16 | number_unsigned | 0xCD
  14979. uint 32 | number_unsigned | 0xCE
  14980. uint 64 | number_unsigned | 0xCF
  14981. int 8 | number_integer | 0xD0
  14982. int 16 | number_integer | 0xD1
  14983. int 32 | number_integer | 0xD2
  14984. int 64 | number_integer | 0xD3
  14985. str 8 | string | 0xD9
  14986. str 16 | string | 0xDA
  14987. str 32 | string | 0xDB
  14988. array 16 | array | 0xDC
  14989. array 32 | array | 0xDD
  14990. map 16 | object | 0xDE
  14991. map 32 | object | 0xDF
  14992. negative fixint | number_integer | 0xE0-0xFF
  14993. @warning The mapping is **incomplete** in the sense that not all
  14994. MessagePack types can be converted to a JSON value. The following
  14995. MessagePack types are not supported and will yield parse errors:
  14996. - bin 8 - bin 32 (0xC4..0xC6)
  14997. - ext 8 - ext 32 (0xC7..0xC9)
  14998. - fixext 1 - fixext 16 (0xD4..0xD8)
  14999. @note Any MessagePack output created @ref to_msgpack can be successfully
  15000. parsed by @ref from_msgpack.
  15001. @param[in] i an input in MessagePack format convertible to an input
  15002. adapter
  15003. @param[in] strict whether to expect the input to be consumed until EOF
  15004. (true by default)
  15005. @param[in] allow_exceptions whether to throw exceptions in case of a
  15006. parse error (optional, true by default)
  15007. @return deserialized JSON value
  15008. @throw parse_error.110 if the given input ends prematurely or the end of
  15009. file was not reached when @a strict was set to true
  15010. @throw parse_error.112 if unsupported features from MessagePack were
  15011. used in the given input @a i or if the input is not valid MessagePack
  15012. @throw parse_error.113 if a string was expected as map key, but not found
  15013. @complexity Linear in the size of the input @a i.
  15014. @liveexample{The example shows the deserialization of a byte vector in
  15015. MessagePack format to a JSON value.,from_msgpack}
  15016. @sa http://msgpack.org
  15017. @sa @ref to_msgpack(const basic_json&) for the analogous serialization
  15018. @sa @ref from_cbor(detail::input_adapter, const bool, const bool) for the
  15019. related CBOR format
  15020. @sa @ref from_ubjson(detail::input_adapter, const bool, const bool) for
  15021. the related UBJSON format
  15022. @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
  15023. consume input adapters, removed start_index parameter, and added
  15024. @a strict parameter since 3.0.0; added @allow_exceptions parameter
  15025. since 3.2.0
  15026. */
  15027. static basic_json from_msgpack(detail::input_adapter&& i,
  15028. const bool strict = true,
  15029. const bool allow_exceptions = true)
  15030. {
  15031. basic_json result;
  15032. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  15033. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
  15034. return res ? result : basic_json(value_t::discarded);
  15035. }
  15036. /*!
  15037. @copydoc from_msgpack(detail::input_adapter, const bool, const bool)
  15038. */
  15039. template<typename A1, typename A2,
  15040. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  15041. static basic_json from_msgpack(A1 && a1, A2 && a2,
  15042. const bool strict = true,
  15043. const bool allow_exceptions = true)
  15044. {
  15045. basic_json result;
  15046. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  15047. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
  15048. return res ? result : basic_json(value_t::discarded);
  15049. }
  15050. /*!
  15051. @brief create a JSON value from an input in UBJSON format
  15052. Deserializes a given input @a i to a JSON value using the UBJSON (Universal
  15053. Binary JSON) serialization format.
  15054. The library maps UBJSON types to JSON value types as follows:
  15055. UBJSON type | JSON value type | marker
  15056. ----------- | --------------------------------------- | ------
  15057. no-op | *no value, next value is read* | `N`
  15058. null | `null` | `Z`
  15059. false | `false` | `F`
  15060. true | `true` | `T`
  15061. float32 | number_float | `d`
  15062. float64 | number_float | `D`
  15063. uint8 | number_unsigned | `U`
  15064. int8 | number_integer | `i`
  15065. int16 | number_integer | `I`
  15066. int32 | number_integer | `l`
  15067. int64 | number_integer | `L`
  15068. string | string | `S`
  15069. char | string | `C`
  15070. array | array (optimized values are supported) | `[`
  15071. object | object (optimized values are supported) | `{`
  15072. @note The mapping is **complete** in the sense that any UBJSON value can
  15073. be converted to a JSON value.
  15074. @param[in] i an input in UBJSON format convertible to an input adapter
  15075. @param[in] strict whether to expect the input to be consumed until EOF
  15076. (true by default)
  15077. @param[in] allow_exceptions whether to throw exceptions in case of a
  15078. parse error (optional, true by default)
  15079. @return deserialized JSON value
  15080. @throw parse_error.110 if the given input ends prematurely or the end of
  15081. file was not reached when @a strict was set to true
  15082. @throw parse_error.112 if a parse error occurs
  15083. @throw parse_error.113 if a string could not be parsed successfully
  15084. @complexity Linear in the size of the input @a i.
  15085. @liveexample{The example shows the deserialization of a byte vector in
  15086. UBJSON format to a JSON value.,from_ubjson}
  15087. @sa http://ubjson.org
  15088. @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
  15089. analogous serialization
  15090. @sa @ref from_cbor(detail::input_adapter, const bool, const bool) for the
  15091. related CBOR format
  15092. @sa @ref from_msgpack(detail::input_adapter, const bool, const bool) for
  15093. the related MessagePack format
  15094. @since version 3.1.0; added @allow_exceptions parameter since 3.2.0
  15095. */
  15096. static basic_json from_ubjson(detail::input_adapter&& i,
  15097. const bool strict = true,
  15098. const bool allow_exceptions = true)
  15099. {
  15100. basic_json result;
  15101. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  15102. const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
  15103. return res ? result : basic_json(value_t::discarded);
  15104. }
  15105. /*!
  15106. @copydoc from_ubjson(detail::input_adapter, const bool, const bool)
  15107. */
  15108. template<typename A1, typename A2,
  15109. detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
  15110. static basic_json from_ubjson(A1 && a1, A2 && a2,
  15111. const bool strict = true,
  15112. const bool allow_exceptions = true)
  15113. {
  15114. basic_json result;
  15115. detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
  15116. const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
  15117. return res ? result : basic_json(value_t::discarded);
  15118. }
  15119. /// @}
  15120. //////////////////////////
  15121. // JSON Pointer support //
  15122. //////////////////////////
  15123. /// @name JSON Pointer functions
  15124. /// @{
  15125. /*!
  15126. @brief access specified element via JSON Pointer
  15127. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  15128. No bound checking is performed. Similar to @ref operator[](const typename
  15129. object_t::key_type&), `null` values are created in arrays and objects if
  15130. necessary.
  15131. In particular:
  15132. - If the JSON pointer points to an object key that does not exist, it
  15133. is created an filled with a `null` value before a reference to it
  15134. is returned.
  15135. - If the JSON pointer points to an array index that does not exist, it
  15136. is created an filled with a `null` value before a reference to it
  15137. is returned. All indices between the current maximum and the given
  15138. index are also filled with `null`.
  15139. - The special value `-` is treated as a synonym for the index past the
  15140. end.
  15141. @param[in] ptr a JSON pointer
  15142. @return reference to the element pointed to by @a ptr
  15143. @complexity Constant.
  15144. @throw parse_error.106 if an array index begins with '0'
  15145. @throw parse_error.109 if an array index was not a number
  15146. @throw out_of_range.404 if the JSON pointer can not be resolved
  15147. @liveexample{The behavior is shown in the example.,operatorjson_pointer}
  15148. @since version 2.0.0
  15149. */
  15150. reference operator[](const json_pointer& ptr)
  15151. {
  15152. return ptr.get_unchecked(this);
  15153. }
  15154. /*!
  15155. @brief access specified element via JSON Pointer
  15156. Uses a JSON pointer to retrieve a reference to the respective JSON value.
  15157. No bound checking is performed. The function does not change the JSON
  15158. value; no `null` values are created. In particular, the the special value
  15159. `-` yields an exception.
  15160. @param[in] ptr JSON pointer to the desired element
  15161. @return const reference to the element pointed to by @a ptr
  15162. @complexity Constant.
  15163. @throw parse_error.106 if an array index begins with '0'
  15164. @throw parse_error.109 if an array index was not a number
  15165. @throw out_of_range.402 if the array index '-' is used
  15166. @throw out_of_range.404 if the JSON pointer can not be resolved
  15167. @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
  15168. @since version 2.0.0
  15169. */
  15170. const_reference operator[](const json_pointer& ptr) const
  15171. {
  15172. return ptr.get_unchecked(this);
  15173. }
  15174. /*!
  15175. @brief access specified element via JSON Pointer
  15176. Returns a reference to the element at with specified JSON pointer @a ptr,
  15177. with bounds checking.
  15178. @param[in] ptr JSON pointer to the desired element
  15179. @return reference to the element pointed to by @a ptr
  15180. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  15181. begins with '0'. See example below.
  15182. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  15183. is not a number. See example below.
  15184. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  15185. is out of range. See example below.
  15186. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  15187. pointer @a ptr. As `at` provides checked access (and no elements are
  15188. implicitly inserted), the index '-' is always invalid. See example below.
  15189. @throw out_of_range.403 if the JSON pointer describes a key of an object
  15190. which cannot be found. See example below.
  15191. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  15192. See example below.
  15193. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15194. changes in the JSON value.
  15195. @complexity Constant.
  15196. @since version 2.0.0
  15197. @liveexample{The behavior is shown in the example.,at_json_pointer}
  15198. */
  15199. reference at(const json_pointer& ptr)
  15200. {
  15201. return ptr.get_checked(this);
  15202. }
  15203. /*!
  15204. @brief access specified element via JSON Pointer
  15205. Returns a const reference to the element at with specified JSON pointer @a
  15206. ptr, with bounds checking.
  15207. @param[in] ptr JSON pointer to the desired element
  15208. @return reference to the element pointed to by @a ptr
  15209. @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
  15210. begins with '0'. See example below.
  15211. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
  15212. is not a number. See example below.
  15213. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
  15214. is out of range. See example below.
  15215. @throw out_of_range.402 if the array index '-' is used in the passed JSON
  15216. pointer @a ptr. As `at` provides checked access (and no elements are
  15217. implicitly inserted), the index '-' is always invalid. See example below.
  15218. @throw out_of_range.403 if the JSON pointer describes a key of an object
  15219. which cannot be found. See example below.
  15220. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
  15221. See example below.
  15222. @exceptionsafety Strong guarantee: if an exception is thrown, there are no
  15223. changes in the JSON value.
  15224. @complexity Constant.
  15225. @since version 2.0.0
  15226. @liveexample{The behavior is shown in the example.,at_json_pointer_const}
  15227. */
  15228. const_reference at(const json_pointer& ptr) const
  15229. {
  15230. return ptr.get_checked(this);
  15231. }
  15232. /*!
  15233. @brief return flattened JSON value
  15234. The function creates a JSON object whose keys are JSON pointers (see [RFC
  15235. 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
  15236. primitive. The original JSON value can be restored using the @ref
  15237. unflatten() function.
  15238. @return an object that maps JSON pointers to primitive values
  15239. @note Empty objects and arrays are flattened to `null` and will not be
  15240. reconstructed correctly by the @ref unflatten() function.
  15241. @complexity Linear in the size the JSON value.
  15242. @liveexample{The following code shows how a JSON object is flattened to an
  15243. object whose keys consist of JSON pointers.,flatten}
  15244. @sa @ref unflatten() for the reverse function
  15245. @since version 2.0.0
  15246. */
  15247. basic_json flatten() const
  15248. {
  15249. basic_json result(value_t::object);
  15250. json_pointer::flatten("", *this, result);
  15251. return result;
  15252. }
  15253. /*!
  15254. @brief unflatten a previously flattened JSON value
  15255. The function restores the arbitrary nesting of a JSON value that has been
  15256. flattened before using the @ref flatten() function. The JSON value must
  15257. meet certain constraints:
  15258. 1. The value must be an object.
  15259. 2. The keys must be JSON pointers (see
  15260. [RFC 6901](https://tools.ietf.org/html/rfc6901))
  15261. 3. The mapped values must be primitive JSON types.
  15262. @return the original JSON from a flattened version
  15263. @note Empty objects and arrays are flattened by @ref flatten() to `null`
  15264. values and can not unflattened to their original type. Apart from
  15265. this example, for a JSON value `j`, the following is always true:
  15266. `j == j.flatten().unflatten()`.
  15267. @complexity Linear in the size the JSON value.
  15268. @throw type_error.314 if value is not an object
  15269. @throw type_error.315 if object values are not primitive
  15270. @liveexample{The following code shows how a flattened JSON object is
  15271. unflattened into the original nested JSON object.,unflatten}
  15272. @sa @ref flatten() for the reverse function
  15273. @since version 2.0.0
  15274. */
  15275. basic_json unflatten() const
  15276. {
  15277. return json_pointer::unflatten(*this);
  15278. }
  15279. /// @}
  15280. //////////////////////////
  15281. // JSON Patch functions //
  15282. //////////////////////////
  15283. /// @name JSON Patch functions
  15284. /// @{
  15285. /*!
  15286. @brief applies a JSON patch
  15287. [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
  15288. expressing a sequence of operations to apply to a JSON) document. With
  15289. this function, a JSON Patch is applied to the current JSON value by
  15290. executing all operations from the patch.
  15291. @param[in] json_patch JSON patch document
  15292. @return patched document
  15293. @note The application of a patch is atomic: Either all operations succeed
  15294. and the patched document is returned or an exception is thrown. In
  15295. any case, the original value is not changed: the patch is applied
  15296. to a copy of the value.
  15297. @throw parse_error.104 if the JSON patch does not consist of an array of
  15298. objects
  15299. @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
  15300. attributes are missing); example: `"operation add must have member path"`
  15301. @throw out_of_range.401 if an array index is out of range.
  15302. @throw out_of_range.403 if a JSON pointer inside the patch could not be
  15303. resolved successfully in the current JSON value; example: `"key baz not
  15304. found"`
  15305. @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
  15306. "move")
  15307. @throw other_error.501 if "test" operation was unsuccessful
  15308. @complexity Linear in the size of the JSON value and the length of the
  15309. JSON patch. As usually only a fraction of the JSON value is affected by
  15310. the patch, the complexity can usually be neglected.
  15311. @liveexample{The following code shows how a JSON patch is applied to a
  15312. value.,patch}
  15313. @sa @ref diff -- create a JSON patch by comparing two JSON values
  15314. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  15315. @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
  15316. @since version 2.0.0
  15317. */
  15318. basic_json patch(const basic_json& json_patch) const
  15319. {
  15320. // make a working copy to apply the patch to
  15321. basic_json result = *this;
  15322. // the valid JSON Patch operations
  15323. enum class patch_operations {add, remove, replace, move, copy, test, invalid};
  15324. const auto get_op = [](const std::string & op)
  15325. {
  15326. if (op == "add")
  15327. {
  15328. return patch_operations::add;
  15329. }
  15330. if (op == "remove")
  15331. {
  15332. return patch_operations::remove;
  15333. }
  15334. if (op == "replace")
  15335. {
  15336. return patch_operations::replace;
  15337. }
  15338. if (op == "move")
  15339. {
  15340. return patch_operations::move;
  15341. }
  15342. if (op == "copy")
  15343. {
  15344. return patch_operations::copy;
  15345. }
  15346. if (op == "test")
  15347. {
  15348. return patch_operations::test;
  15349. }
  15350. return patch_operations::invalid;
  15351. };
  15352. // wrapper for "add" operation; add value at ptr
  15353. const auto operation_add = [&result](json_pointer & ptr, basic_json val)
  15354. {
  15355. // adding to the root of the target document means replacing it
  15356. if (ptr.is_root())
  15357. {
  15358. result = val;
  15359. }
  15360. else
  15361. {
  15362. // make sure the top element of the pointer exists
  15363. json_pointer top_pointer = ptr.top();
  15364. if (top_pointer != ptr)
  15365. {
  15366. result.at(top_pointer);
  15367. }
  15368. // get reference to parent of JSON pointer ptr
  15369. const auto last_path = ptr.pop_back();
  15370. basic_json& parent = result[ptr];
  15371. switch (parent.m_type)
  15372. {
  15373. case value_t::null:
  15374. case value_t::object:
  15375. {
  15376. // use operator[] to add value
  15377. parent[last_path] = val;
  15378. break;
  15379. }
  15380. case value_t::array:
  15381. {
  15382. if (last_path == "-")
  15383. {
  15384. // special case: append to back
  15385. parent.push_back(val);
  15386. }
  15387. else
  15388. {
  15389. const auto idx = json_pointer::array_index(last_path);
  15390. if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
  15391. {
  15392. // avoid undefined behavior
  15393. JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
  15394. }
  15395. else
  15396. {
  15397. // default case: insert add offset
  15398. parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
  15399. }
  15400. }
  15401. break;
  15402. }
  15403. // LCOV_EXCL_START
  15404. default:
  15405. {
  15406. // if there exists a parent it cannot be primitive
  15407. assert(false);
  15408. }
  15409. // LCOV_EXCL_STOP
  15410. }
  15411. }
  15412. };
  15413. // wrapper for "remove" operation; remove value at ptr
  15414. const auto operation_remove = [&result](json_pointer & ptr)
  15415. {
  15416. // get reference to parent of JSON pointer ptr
  15417. const auto last_path = ptr.pop_back();
  15418. basic_json& parent = result.at(ptr);
  15419. // remove child
  15420. if (parent.is_object())
  15421. {
  15422. // perform range check
  15423. auto it = parent.find(last_path);
  15424. if (JSON_LIKELY(it != parent.end()))
  15425. {
  15426. parent.erase(it);
  15427. }
  15428. else
  15429. {
  15430. JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
  15431. }
  15432. }
  15433. else if (parent.is_array())
  15434. {
  15435. // note erase performs range check
  15436. parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
  15437. }
  15438. };
  15439. // type check: top level value must be an array
  15440. if (JSON_UNLIKELY(not json_patch.is_array()))
  15441. {
  15442. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  15443. }
  15444. // iterate and apply the operations
  15445. for (const auto& val : json_patch)
  15446. {
  15447. // wrapper to get a value for an operation
  15448. const auto get_value = [&val](const std::string & op,
  15449. const std::string & member,
  15450. bool string_type) -> basic_json &
  15451. {
  15452. // find value
  15453. auto it = val.m_value.object->find(member);
  15454. // context-sensitive error message
  15455. const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
  15456. // check if desired value is present
  15457. if (JSON_UNLIKELY(it == val.m_value.object->end()))
  15458. {
  15459. JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
  15460. }
  15461. // check if result is of type string
  15462. if (JSON_UNLIKELY(string_type and not it->second.is_string()))
  15463. {
  15464. JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
  15465. }
  15466. // no error: return value
  15467. return it->second;
  15468. };
  15469. // type check: every element of the array must be an object
  15470. if (JSON_UNLIKELY(not val.is_object()))
  15471. {
  15472. JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
  15473. }
  15474. // collect mandatory members
  15475. const std::string op = get_value("op", "op", true);
  15476. const std::string path = get_value(op, "path", true);
  15477. json_pointer ptr(path);
  15478. switch (get_op(op))
  15479. {
  15480. case patch_operations::add:
  15481. {
  15482. operation_add(ptr, get_value("add", "value", false));
  15483. break;
  15484. }
  15485. case patch_operations::remove:
  15486. {
  15487. operation_remove(ptr);
  15488. break;
  15489. }
  15490. case patch_operations::replace:
  15491. {
  15492. // the "path" location must exist - use at()
  15493. result.at(ptr) = get_value("replace", "value", false);
  15494. break;
  15495. }
  15496. case patch_operations::move:
  15497. {
  15498. const std::string from_path = get_value("move", "from", true);
  15499. json_pointer from_ptr(from_path);
  15500. // the "from" location must exist - use at()
  15501. basic_json v = result.at(from_ptr);
  15502. // The move operation is functionally identical to a
  15503. // "remove" operation on the "from" location, followed
  15504. // immediately by an "add" operation at the target
  15505. // location with the value that was just removed.
  15506. operation_remove(from_ptr);
  15507. operation_add(ptr, v);
  15508. break;
  15509. }
  15510. case patch_operations::copy:
  15511. {
  15512. const std::string from_path = get_value("copy", "from", true);
  15513. const json_pointer from_ptr(from_path);
  15514. // the "from" location must exist - use at()
  15515. basic_json v = result.at(from_ptr);
  15516. // The copy is functionally identical to an "add"
  15517. // operation at the target location using the value
  15518. // specified in the "from" member.
  15519. operation_add(ptr, v);
  15520. break;
  15521. }
  15522. case patch_operations::test:
  15523. {
  15524. bool success = false;
  15525. JSON_TRY
  15526. {
  15527. // check if "value" matches the one at "path"
  15528. // the "path" location must exist - use at()
  15529. success = (result.at(ptr) == get_value("test", "value", false));
  15530. }
  15531. JSON_INTERNAL_CATCH (out_of_range&)
  15532. {
  15533. // ignore out of range errors: success remains false
  15534. }
  15535. // throw an exception if test fails
  15536. if (JSON_UNLIKELY(not success))
  15537. {
  15538. JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
  15539. }
  15540. break;
  15541. }
  15542. case patch_operations::invalid:
  15543. {
  15544. // op must be "add", "remove", "replace", "move", "copy", or
  15545. // "test"
  15546. JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
  15547. }
  15548. }
  15549. }
  15550. return result;
  15551. }
  15552. /*!
  15553. @brief creates a diff as a JSON patch
  15554. Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
  15555. be changed into the value @a target by calling @ref patch function.
  15556. @invariant For two JSON values @a source and @a target, the following code
  15557. yields always `true`:
  15558. @code {.cpp}
  15559. source.patch(diff(source, target)) == target;
  15560. @endcode
  15561. @note Currently, only `remove`, `add`, and `replace` operations are
  15562. generated.
  15563. @param[in] source JSON value to compare from
  15564. @param[in] target JSON value to compare against
  15565. @param[in] path helper value to create JSON pointers
  15566. @return a JSON patch to convert the @a source to @a target
  15567. @complexity Linear in the lengths of @a source and @a target.
  15568. @liveexample{The following code shows how a JSON patch is created as a
  15569. diff for two JSON values.,diff}
  15570. @sa @ref patch -- apply a JSON patch
  15571. @sa @ref merge_patch -- apply a JSON Merge Patch
  15572. @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
  15573. @since version 2.0.0
  15574. */
  15575. static basic_json diff(const basic_json& source, const basic_json& target,
  15576. const std::string& path = "")
  15577. {
  15578. // the patch
  15579. basic_json result(value_t::array);
  15580. // if the values are the same, return empty patch
  15581. if (source == target)
  15582. {
  15583. return result;
  15584. }
  15585. if (source.type() != target.type())
  15586. {
  15587. // different types: replace value
  15588. result.push_back(
  15589. {
  15590. {"op", "replace"}, {"path", path}, {"value", target}
  15591. });
  15592. }
  15593. else
  15594. {
  15595. switch (source.type())
  15596. {
  15597. case value_t::array:
  15598. {
  15599. // first pass: traverse common elements
  15600. std::size_t i = 0;
  15601. while (i < source.size() and i < target.size())
  15602. {
  15603. // recursive call to compare array values at index i
  15604. auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
  15605. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  15606. ++i;
  15607. }
  15608. // i now reached the end of at least one array
  15609. // in a second pass, traverse the remaining elements
  15610. // remove my remaining elements
  15611. const auto end_index = static_cast<difference_type>(result.size());
  15612. while (i < source.size())
  15613. {
  15614. // add operations in reverse order to avoid invalid
  15615. // indices
  15616. result.insert(result.begin() + end_index, object(
  15617. {
  15618. {"op", "remove"},
  15619. {"path", path + "/" + std::to_string(i)}
  15620. }));
  15621. ++i;
  15622. }
  15623. // add other remaining elements
  15624. while (i < target.size())
  15625. {
  15626. result.push_back(
  15627. {
  15628. {"op", "add"},
  15629. {"path", path + "/" + std::to_string(i)},
  15630. {"value", target[i]}
  15631. });
  15632. ++i;
  15633. }
  15634. break;
  15635. }
  15636. case value_t::object:
  15637. {
  15638. // first pass: traverse this object's elements
  15639. for (auto it = source.cbegin(); it != source.cend(); ++it)
  15640. {
  15641. // escape the key name to be used in a JSON patch
  15642. const auto key = json_pointer::escape(it.key());
  15643. if (target.find(it.key()) != target.end())
  15644. {
  15645. // recursive call to compare object values at key it
  15646. auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
  15647. result.insert(result.end(), temp_diff.begin(), temp_diff.end());
  15648. }
  15649. else
  15650. {
  15651. // found a key that is not in o -> remove it
  15652. result.push_back(object(
  15653. {
  15654. {"op", "remove"}, {"path", path + "/" + key}
  15655. }));
  15656. }
  15657. }
  15658. // second pass: traverse other object's elements
  15659. for (auto it = target.cbegin(); it != target.cend(); ++it)
  15660. {
  15661. if (source.find(it.key()) == source.end())
  15662. {
  15663. // found a key that is not in this -> add it
  15664. const auto key = json_pointer::escape(it.key());
  15665. result.push_back(
  15666. {
  15667. {"op", "add"}, {"path", path + "/" + key},
  15668. {"value", it.value()}
  15669. });
  15670. }
  15671. }
  15672. break;
  15673. }
  15674. default:
  15675. {
  15676. // both primitive type: replace value
  15677. result.push_back(
  15678. {
  15679. {"op", "replace"}, {"path", path}, {"value", target}
  15680. });
  15681. break;
  15682. }
  15683. }
  15684. }
  15685. return result;
  15686. }
  15687. /// @}
  15688. ////////////////////////////////
  15689. // JSON Merge Patch functions //
  15690. ////////////////////////////////
  15691. /// @name JSON Merge Patch functions
  15692. /// @{
  15693. /*!
  15694. @brief applies a JSON Merge Patch
  15695. The merge patch format is primarily intended for use with the HTTP PATCH
  15696. method as a means of describing a set of modifications to a target
  15697. resource's content. This function applies a merge patch to the current
  15698. JSON value.
  15699. The function implements the following algorithm from Section 2 of
  15700. [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
  15701. ```
  15702. define MergePatch(Target, Patch):
  15703. if Patch is an Object:
  15704. if Target is not an Object:
  15705. Target = {} // Ignore the contents and set it to an empty Object
  15706. for each Name/Value pair in Patch:
  15707. if Value is null:
  15708. if Name exists in Target:
  15709. remove the Name/Value pair from Target
  15710. else:
  15711. Target[Name] = MergePatch(Target[Name], Value)
  15712. return Target
  15713. else:
  15714. return Patch
  15715. ```
  15716. Thereby, `Target` is the current object; that is, the patch is applied to
  15717. the current value.
  15718. @param[in] patch the patch to apply
  15719. @complexity Linear in the lengths of @a patch.
  15720. @liveexample{The following code shows how a JSON Merge Patch is applied to
  15721. a JSON document.,merge_patch}
  15722. @sa @ref patch -- apply a JSON patch
  15723. @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
  15724. @since version 3.0.0
  15725. */
  15726. void merge_patch(const basic_json& patch)
  15727. {
  15728. if (patch.is_object())
  15729. {
  15730. if (not is_object())
  15731. {
  15732. *this = object();
  15733. }
  15734. for (auto it = patch.begin(); it != patch.end(); ++it)
  15735. {
  15736. if (it.value().is_null())
  15737. {
  15738. erase(it.key());
  15739. }
  15740. else
  15741. {
  15742. operator[](it.key()).merge_patch(it.value());
  15743. }
  15744. }
  15745. }
  15746. else
  15747. {
  15748. *this = patch;
  15749. }
  15750. }
  15751. /// @}
  15752. };
  15753. } // namespace nlohmann
  15754. ///////////////////////
  15755. // nonmember support //
  15756. ///////////////////////
  15757. // specialization of std::swap, and std::hash
  15758. namespace std
  15759. {
  15760. /*!
  15761. @brief exchanges the values of two JSON objects
  15762. @since version 1.0.0
  15763. */
  15764. template<>
  15765. inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
  15766. is_nothrow_move_constructible<nlohmann::json>::value and
  15767. is_nothrow_move_assignable<nlohmann::json>::value
  15768. )
  15769. {
  15770. j1.swap(j2);
  15771. }
  15772. /// hash value for JSON objects
  15773. template<>
  15774. struct hash<nlohmann::json>
  15775. {
  15776. /*!
  15777. @brief return a hash value for a JSON object
  15778. @since version 1.0.0
  15779. */
  15780. std::size_t operator()(const nlohmann::json& j) const
  15781. {
  15782. // a naive hashing via the string representation
  15783. const auto& h = hash<nlohmann::json::string_t>();
  15784. return h(j.dump());
  15785. }
  15786. };
  15787. /// specialization for std::less<value_t>
  15788. /// @note: do not remove the space after '<',
  15789. /// see https://github.com/nlohmann/json/pull/679
  15790. template<>
  15791. struct less< ::nlohmann::detail::value_t>
  15792. {
  15793. /*!
  15794. @brief compare two value_t enum values
  15795. @since version 3.0.0
  15796. */
  15797. bool operator()(nlohmann::detail::value_t lhs,
  15798. nlohmann::detail::value_t rhs) const noexcept
  15799. {
  15800. return nlohmann::detail::operator<(lhs, rhs);
  15801. }
  15802. };
  15803. } // namespace std
  15804. /*!
  15805. @brief user-defined string literal for JSON values
  15806. This operator implements a user-defined string literal for JSON objects. It
  15807. can be used by adding `"_json"` to a string literal and returns a JSON object
  15808. if no parse error occurred.
  15809. @param[in] s a string representation of a JSON object
  15810. @param[in] n the length of string @a s
  15811. @return a JSON object
  15812. @since version 1.0.0
  15813. */
  15814. inline nlohmann::json operator "" _json(const char* s, std::size_t n)
  15815. {
  15816. return nlohmann::json::parse(s, s + n);
  15817. }
  15818. /*!
  15819. @brief user-defined string literal for JSON pointer
  15820. This operator implements a user-defined string literal for JSON Pointers. It
  15821. can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
  15822. object if no parse error occurred.
  15823. @param[in] s a string representation of a JSON Pointer
  15824. @param[in] n the length of string @a s
  15825. @return a JSON pointer object
  15826. @since version 2.0.0
  15827. */
  15828. inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
  15829. {
  15830. return nlohmann::json::json_pointer(std::string(s, n));
  15831. }
  15832. // #include <nlohmann/detail/macro_unscope.hpp>
  15833. // restore GCC/clang diagnostic settings
  15834. #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
  15835. #pragma GCC diagnostic pop
  15836. #endif
  15837. #if defined(__clang__)
  15838. #pragma GCC diagnostic pop
  15839. #endif
  15840. // clean up
  15841. #undef JSON_INTERNAL_CATCH
  15842. #undef JSON_CATCH
  15843. #undef JSON_THROW
  15844. #undef JSON_TRY
  15845. #undef JSON_LIKELY
  15846. #undef JSON_UNLIKELY
  15847. #undef JSON_DEPRECATED
  15848. #undef JSON_HAS_CPP_14
  15849. #undef JSON_HAS_CPP_17
  15850. #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION
  15851. #undef NLOHMANN_BASIC_JSON_TPL
  15852. #undef NLOHMANN_JSON_HAS_HELPER
  15853. #endif